Skip to content

Instantly share code, notes, and snippets.

@daugaard47
Last active January 31, 2023 23:59
Show Gist options
  • Save daugaard47/d1fc64a00989d4857224a2f3cbc1abd2 to your computer and use it in GitHub Desktop.
Save daugaard47/d1fc64a00989d4857224a2f3cbc1abd2 to your computer and use it in GitHub Desktop.

Install this

composer require stripe/stripe-php

Web Routes

I'm using Laravel 8 Jetstream, but this should transfer over

Route::get('test-payment',[App\Http\Controllers\PaymentController::class, 'index'])->name('testPayment');
Route::post('charge',[App\Http\Controllers\PaymentController::class, 'charge']);

Tailwind

I'm using Tailwind so you might need this so you can see the form correctly

<link href="https://unpkg.com/tailwindcss@^1.0/dist/tailwind.min.css" rel="stylesheet">

<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Stripe\Stripe;
class PaymentController extends Controller {
public function index() {
return view('test-payment');
}
public function charge(Request $request) {
// \Stripe\Stripe::setApiKey('stripe.secret.key.goes.here'));
\Stripe\Stripe::setApiKey(config('cashier.secret'));
try {
//Create the customer
$customer = \Stripe\Customer::create([
'email' => $request->email,
'source' => $request->stripeToken,
// This description should actually be the "Users" full name, not the Card Holders Name. Example: The Users could be paying with someone else card.
'description' => $request->cardHoldersName,
]);
// Change the newly create customer
$charge = \Stripe\Charge::create([
'amount' => $request->amount * 100, // Converting the amount into cents
'currency' => 'USD',
'customer' => $customer->id, // Grabbing the new customers id from above
'description' => $request->cardHoldersName,
'receipt_email' => $request->email,
// Any extra data you may want to store in Stripe
'metadata' => [
'data1' => 'metadata 1',
'data2' => 'metadata 2',
'data3' => 'metadata 3'
]
]);
// save this info to your database if needed
// successful message
return back()->with('success', 'Thank you! Your payment has been accepted.');
} catch (\Stripe\Exception\CardException $e) {
// Since it's a decline, \Stripe\Exception\CardException will be caught
echo 'Status is:' . $e->getHttpStatus() . '\n';
echo 'Type is:' . $e->getError()->type . '\n';
echo 'Code is:' . $e->getError()->code . '\n';
// param is '' in this case
echo 'Param is:' . $e->getError()->param . '\n';
echo 'Message is:' . $e->getError()->message . '\n';
} catch (\Stripe\Exception\RateLimitException $e) {
// Too many requests made to the API too quickly
} catch (\Stripe\Exception\InvalidRequestException $e) {
// Invalid parameters were supplied to Stripe's API
} catch (\Stripe\Exception\AuthenticationException $e) {
// Authentication with Stripe's API failed
// (maybe you changed API keys recently)
} catch (\Stripe\Exception\ApiConnectionException $e) {
// Network communication with Stripe failed
} catch (\Stripe\Exception\ApiErrorException $e) {
// Display a very generic error to the user, and maybe send
// yourself an email
} catch (Exception $e) {
// Something else happened, completely unrelated to Stripe
}
return back()->withErrors('Error! ' . $e->getMessage());
}
}
<x-app-layout>
@if ($message = Session::get('success'))
<p class="text-green-600 font-black">{{ $message }}</p>
@endif
@if ($message = Session::get('error'))
<p class="text-red-700 font-black">{{ $message }}</p>
@endif
<div class="max-w-7xl mx-auto px-4 sm:px-0 mb-20 relative z-20">
<div class="text-center px-4">
<p class="text-base leading-6 text-teal-600 font-semibold tracking-wide uppercase">Stripe</p>
<h3 class="mt-2 text-3xl leading-8 font-black uppercase tracking-tight bg-clip-text text-transparent bg-gradient-to-b from-teal-400 to-teal-700 sm:text-4xl sm:leading-10">
Stripe One-Off Payment
</h3>
<p class="mt-4 text-xl leading-7 text-teal-500 lg:mx-auto">
This is an example of how to collect a one-off payment with Stripe without a user being logged in.
</p>
</div>
</div>
<div class="max-w-7xl mx-auto px-4 sm:px-0 mb-20 relative z-20">
<div class="grid grid-cols-1 gap-6 sm:px-4">
<div class="lg:col-span-2 col-span-1">
<div class="bg-white overflow-hidden shadow-xl rounded">
<div
class="border-b border-teal-200 px-4 py-6 bg-gradient-to-r from-teal-700 via-teal-700 to-teal-600 sm:px-6 rounded-t">
<h2 class="text-lg leading-8 font-medium text-white">
Pay for this sweet product.
</h2>
<div>
<p class="text-lg leading-5 text-teal-300">
Simply enter your email and card info below.
</p>
</div>
</div>
<form action="/charge" method="post" id="payment-form">
@csrf
<div class="px-4 py-5 sm:p-6">
<div class="grid sm:grid-cols-2 grid-cols-1 gap-4">
<div class="sm:col-span-2 col-span-1">
<label
class="block font-medium text-sm text-gray-700 text-lg leading-6 font-bold text-teal-700">
Enter your email
</label>
<input class="form-input rounded-md shadow-sm block mt-1 w-full py-2 mb-4"
id="email" name="email" type="email" autofocus="autofocus"
autocomplete="email">
</div>
<div class="sm:col-span-2 col-span-1">
<label
class="block font-medium text-sm text-gray-700 text-lg leading-6 font-bold text-teal-700">
Name on card
</label>
<input class="form-input rounded-md shadow-sm block mt-1 w-full py-2 mb-4"
id="cardHoldersName" name="cardHoldersName" type="text" autofocus="autofocus"
autocomplete="cardHoldersName">
</div>
<div class="col-span-2">
<div>
<label
class="block font-medium text-sm text-gray-700 text-lg leading-6 font-bold text-teal-700">
Credit or Debit card number
</label>
<div id="card-element"
class="form-input rounded-md shadow-sm block mt-1 w-full py-3.5 mb-4">
<!-- A Stripe Element will be inserted here. -->
</div>
</div>
</div>
</div>
</div>
<div class="border-t border-teal-100 px-4 py-4 sm:px-6">
<div class="col-span-2">
<span class="flex justify-end">
<button type="submit"
class="inline-flex justify-center px-4 py-2 border border-transparent text-base leading-6 font-medium rounded-md text-white bg-teal-600 hover:bg-teal-500 focus:outline-none focus:border-teal-700 focus:shadow-outline-gray active:bg-teal-700 transition duration-150 ease-in-out">
Pay for Product
</button>
</span>
</div>
</div>
<input type="hidden" name="amount" value="100">
</form>
</div>
</div>
</div>
</div>
{{-- In your Header add @stack('stripe')--}}
@push('stripe')
<script src="https://js.stripe.com/v3/"></script>
@endpush
{{-- Before Body close tag add @yield('scripts')--}}
@section('scripts')
<script>
// Create a Stripe client. // I have cashier installed, but not using it here. Replace the cashier.key with your Stripe Public Key
{{--var stripe = Stripe('{{ env('STRIPE_KEY') }}');--}}
var stripe = Stripe('{{ config('cashier.key') }}');
// Create an instance of Elements.
var elements = stripe.elements();
// Custom styling can be passed to options when creating an Element.
// (Note that this demo uses a wider set of styles than the guide below.)
var style = {
base: {
color: '#32325d',
fontFamily: '"Helvetica Neue", Helvetica, sans-serif',
fontSmoothing: 'antialiased',
fontSize: '16px',
'::placeholder': {
color: '#aab7c4'
}
},
invalid: {
color: '#fa755a',
iconColor: '#fa755a'
}
};
// Create an instance of the card Element.
var card = elements.create('card', {style: style});
// Add an instance of the card Element into the `card-element` <div>.
card.mount('#card-element');
// Handle real-time validation errors from the card Element.
card.on('change', function (event) {
var displayError = document.getElementById('card-errors');
if (event.error) {
displayError.textContent = event.error.message;
} else {
displayError.textContent = '';
}
});
// Handle form submission.
var form = document.getElementById('payment-form');
form.addEventListener('submit', function (event) {
event.preventDefault();
stripe.createToken(card).then(function (result) {
if (result.error) {
// Inform the user if there was an error.
var errorElement = document.getElementById('card-errors');
errorElement.textContent = result.error.message;
} else {
// Send the token to your server.
stripeTokenHandler(result.token);
}
});
});
// Submit the form with the token ID.
function stripeTokenHandler(token) {
// Insert the token ID into the form so it gets submitted to the server
var form = document.getElementById('payment-form'); // This matches the id in <form>
var hiddenInput = document.createElement('input');
hiddenInput.setAttribute('type', 'hidden');
hiddenInput.setAttribute('name', 'stripeToken');
hiddenInput.setAttribute('value', token.id);
form.appendChild(hiddenInput);
// Submit the form
form.submit();
}
</script>
@endsection
</x-app-layout>
@daugaard47
Copy link
Author

form

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment