Laravel 9 - Stripe payment gateway
Laravel 9 - Stripe payment gateway
In this tutorial, we'll explore integrating the Stripe payment gateway in Laravel 9, a platform for secure and easy online payment management.
If you're a video person, feel free to skip the post and check out the video instead!
Step # 1 : Create fresh Laravel project or use an existing Laravel project.
Two commands to create fresh Laravel project.
Global Command : laravel new stripe
Or use
Non Global Command : composer create-project laravel/laravel --prefer-dist stripe
Step # 2 : Access the project.
Open a terminal (e.g., Git Bash) and navigate to your Laravel project's root folder.
Git Bash : cd c:xampp/htdocs/stripe
Run the Laravel Vite development server. Install the required dependencies and start the Vite server for front-end assets.
Command : npm install && npm run dev
Open a new Git Bash window or tab, and navigate to the same project directory to run further Laravel commands.
Step # 3 : Let's install stripe package.
Command : composer require stripe/stripe-php
Step # 4 : Creating stripe account.
Create an account on Stripe by visiting the below link.
link : https://stripe.com/
After completing this step, you will be able to access your publishable and secret keys from the Stripe dashboard.
Step # 5: Add Stripe keys to .env.
Open your .env file and add the following.
STRIPE_KEY=your_publishable_key
STRIPE_SECRET=your_secret_key
Step # 6 : Create a controller.
Generate a new controller.
Command : php artisan make:controller CheckoutController
Update the CheckoutController with the following code.
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class CheckoutController extends Controller
{
public function checkout()
{
\Stripe\Stripe::setApiKey(env('STRIPE_SECRET'));
$amount = 100 * 100;
$payment_intent = \Stripe\PaymentIntent::create([
'description' => 'Stripe Test Payment',
'amount' => $amount,
'currency' => 'AED',
'payment_method_types' => ['card'],
]);
$intent = $payment_intent->client_secret;
return view('checkout.credit-card', compact('intent'));
}
public function afterPayment()
{
return 'Payment received. Thank you for using our services.';
}
}
Step # 7 : Create routes.
Import CheckoutController class.
use App\Http\Controllers\CheckoutController;
Create following routes.
Route::get('/checkout', [CheckoutController::class, 'checkout']);
Route::post('/checkout', [CheckoutController::class, 'afterPayment'])->name('checkout.credit-card');
Step # 8 : Create a view.
Create a folder inside resources/views named checkout and a file named credit-card.blade.php inside the checkout folder.
It should look something like this (resources/views/checkout/credit-card.blade.php)
Paste the following code into credit-card.blade.php
<!DOCTYPE html>
<html lang="en">
<head>
<title>Stripe Payment</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>
</head>
<body>
<div class="container" style="margin-top:10%;margin-bottom:10%">
<div class="row justify-content-center">
<div class="col-md-12">
<div class="">
<p>Your Total Amount is 100 AED</p>
</div>
<div class="card">
<form action="{{ route('checkout.credit-card') }}" method="post" id="payment-form">
@csrf
<div class="form-group">
<div class="card-header">
<label for="card-element">Enter your credit card information</label>
</div>
<div class="card-body">
<div id="card-element">
<!-- A Stripe Element will be inserted here. -->
</div>
<!-- Used to display form errors. -->
<div id="card-errors" role="alert"></div>
<input type="hidden" name="plan" value="" />
</div>
</div>
<div class="card-footer">
<button
id="card-button"
class="btn btn-dark"
type="submit"
data-secret="{{ $intent }}"
> Pay </button>
</div>
</form>
</div>
</div>
</div>
</div>
<script src="https://js.stripe.com/v3/"></script>
<script>
var style = {
base: {
color: '#32325d',
lineHeight: '18px',
fontFamily: '"Helvetica Neue", Helvetica, sans-serif',
fontSmoothing: 'antialiased',
fontSize: '16px',
'::placeholder': {
color: '#aab7c4'
}
},
invalid: {
color: '#fa755a',
iconColor: '#fa755a'
}
};
const stripe = Stripe('{{ env('STRIPE_KEY') }}', { locale: 'en' });
const elements = stripe.elements();
const cardElement = elements.create('card', { style: style });
const cardButton = document.getElementById('card-button');
const clientSecret = cardButton.dataset.secret;
cardElement.mount('#card-element');
cardElement.addEventListener('change', function(event) {
var displayError = document.getElementById('card-errors');
if (event.error) {
displayError.textContent = event.error.message;
} else {
displayError.textContent = '';
}
});
var form = document.getElementById('payment-form');
form.addEventListener('submit', function(event) {
event.preventDefault();
stripe.handleCardPayment(clientSecret, cardElement, {
payment_method_data: {
//billing_details: { name: cardHolderName.value }
}
})
.then(function(result) {
if (result.error) {
var errorElement = document.getElementById('card-errors');
errorElement.textContent = result.error.message;
} else {
form.submit();
}
});
});
</script>
</body>
</html>
Step # 9 : It's time to test.
Run the Laravel server.
Command : php artisan serve
Visit url : 127.0.0.1/checkout
Step # 10 : Test Stripe integration using below dummy data.
Card Number - 4242 4242 4242 4242
EXP - 12/32
CVV - 123
ZIP - 12345
If you've followed the steps correctly, you should see a message similar to the one below.
You can also view the payment details in your Stripe dashboard.
Share this with friends!
To engage in commentary, kindly proceed by logging in or registering
Subscribe to Our Newsletter
Stay ahead of the curve! Join our newsletter to see what everyone’s talking about.
0 Comments