Stripe Payment Gateway Integration In Laravel 12 Step By Step Guide With Example

image
image
image
image
image
image
image
image
Stripe Payment Gateway Integration In Laravel 12 Step By Step Guide With Example

Stripe Payment Gateway Integration In Laravel 12 Step By Step Guide With Example

If you're building a Laravel application and need to accept payments, Stripe is one of the best and most developer-friendly payment gateways available. In this blog, we will walk you through a complete integration of Stripe Payments in Laravel, using Bootstrap 5 for frontend styling, and including real customer billing details with card element UI provided by Stripe.js.


Before Moving must ensure that you have stripe account, if you don't have please create from here , https://dashboard.stripe.com/register?redirect=%2Ftest%2Fpayments


When you click on the above URL you have something like the below image



After signup you can see your dashboard like the below, just switch to the sandbox mode to get your stripe secret and publishable key




Table of Contents


  1. Introduction to Stripe Payments in Laravel
  2. Prerequisites
  3. Stripe Setup
  4. Step 1: Create the Payment Controller
  5. Step 2: Create the Route for Checkout
  6. Step 3: Blade Template for Stripe Payment
  7. Step 4: Adding Stripe Elements and JavaScript Logic
  8. Step 5: Submitting and Handling the Payment
  9. Bonus: Tips for Going Live
  10. Conclusion


Understanding Stripe's Requirements for Indian Businesses


Before integrating Stripe, it's crucial to understand the specific requirements for Indian businesses:

  1. Business Registration: Only registered Indian businesses (sole proprietorships, LLPs, or companies) can accept international payments. Individuals are not permitted.
  2. Import Export Code (IEC): To accept international payments, you must obtain an IEC from the Director General of Foreign Trade (DGFT).Stripe Support+3Stripe Support+3Stripe Support+3
  3. Purpose Code: You'll need to provide a Transaction Purpose Code that aligns with your business activities.Stripe Support+4Stripe Support+4Stripe Support+4
  4. Currency Restrictions: Domestic transactions must be in INR. For international transactions, ensure that the customer's card is issued outside India and that the billing address is located outside India.Stripe Support

For more detailed information, refer to Stripe's documentation on accepting international payments from Stripe accounts in India.


Introduction to Stripe Payments in Laravel


Stripe allows you to securely collect and process credit card information. Laravel makes it easy to integrate Stripe via HTTP requests. With just a few steps, you can create a payment intent, securely collect card details, and handle the payment status on the frontend.


Prerequisites


Before we begin, ensure you have the following:

  1. Laravel 8 or later installed
  2. Composer
  3. Stripe account (test keys)
  4. Basic knowledge of Laravel controllers, views, and routes
  5. Bootstrap 5 CDN


Stripe Setup


First, sign up at https://stripe.com. From your dashboard:

  1. Get your Publishable Key and Secret Key.
  2. Add the keys to your .env file:


STRIPE_PUBLIC_KEY=pk_test_...
STRIPE_SECRET_KEY=sk_test_...



Setting Up the Laravel Backend


We'll start by creating a controller to handle the payment process.

1. Create the Controller

Run the following Artisan command to create a new controller:

php artisan make:controller StripePaymentController


2. Implement the Controller Methods

In app/Http/Controllers/StripePaymentController.php:

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Http;

class StripePaymentController extends Controller
{
public function createPaymentIntent(Request $request)
{
$response = Http::withBasicAuth(env('STRIPE_SECRET_KEY'), '')
->asForm()
->post('https://api.stripe.com/v1/payment_intents', [
'amount' => 10000, // Amount in paise (₹100)
'currency' => 'inr',
'automatic_payment_methods[enabled]' => 'true',
]);

$clientSecret = $response->json()['client_secret'];
$publishableKey = env('STRIPE_PUBLIC_KEY');

return view('stripe.checkout', [
'clientSecret' => $clientSecret,
'publishableKey' => $publishableKey
]);
}

public function stripeCheckout()
{
// Handle post-payment logic here
return 'Payment successfully processed';
}
}


Creating the Payment Intent


The createPaymentIntent method in the controller uses Laravel's HTTP client to send a POST request to Stripe's API, creating a Payment Intent with the specified amount and currency. The automatic_payment_methods[enabled] parameter allows Stripe to handle the payment method selection automatically.


Designing the Frontend with Bootstrap 5

We'll create a simple payment form using Bootstrap 5.

In resources/views/stripe/checkout.blade.php:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Stripe Payment</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- Bootstrap 5 -->
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
<div class="container py-5">
<div class="row justify-content-center">
<div class="col-md-6">
<h4 class="mb-4">You will be charged ₹100</h4>
<div class="card">
<form action="{{ route('checkout.credit-card') }}" method="post" id="payment-form" class="p-4">
@csrf
<div class="mb-3">
<label for="card-element" class="form-label">Card Details</label>
<div id="card-element" class="form-control">
<!-- Stripe Card Element will be inserted here -->
</div>
<div id="card-errors" role="alert" class="text-danger mt-2"></div>
</div>
<button
id="card-button"
type="button"
class="btn btn-primary w-100"
data-secret="{{ $clientSecret }}">
Pay ₹100
</button>
</form>
</div>
</div>
</div>
</div>

<!-- Stripe JS -->
<script src="https://js.stripe.com/v3/"></script>
<script>
// JavaScript code will be added here
</script>
</body>
</html>


Implementing Stripe Elements and JavaScript Logic

We'll now add the JavaScript code to handle the payment process using Stripe Elements.

const stripe = Stripe('{{ $publishableKey }}');
const elements = stripe.elements();
const card = elements.create('card', {
style: {
base: {
fontSize: '16px',
color: '#32325d',
fontFamily: 'Arial, sans-serif',
'::placeholder': {
color: '#a0aec0',
}
},
invalid: {
color: '#fa755a',
iconColor: '#fa755a'
}
}
});

// Mount card input into the DOM
card.mount('#card-element');

// Real-time validation errors
card.on('change', event => {
const displayError = document.getElementById('card-errors');
displayError.textContent = event.error ? event.error.message : '';
});

const cardButton = document.getElementById('card-button');
const clientSecret = cardButton.dataset.secret;

cardButton.addEventListener('click', async () => {
// 1. Create Payment Method with billing details
const { error: pmError, paymentMethod } = await stripe.createPaymentMethod({
type: 'card',
card: card,
billing_details: {
name: 'Shaiv Roy',
address: {
line1: 'Gurhatta',
city: 'Patna City',
country: 'IN',
postal_code: '800008'
}
}
});

if (pmError) {
document.getElementById('card-errors').textContent = pmError.message;
return;
}

// 2. Confirm the Payment Intent
const { error: confirmError, paymentIntent } = await stripe.confirmCardPayment(clientSecret, {
payment_method: paymentMethod.id
});

if (confirmError) {
document.getElementById('card-errors').textContent = confirmError.message;
} else if (paymentIntent.status === 'succeeded') {
alert('Payment successful!');
document.getElementById('payment-form').submit(); // Optional: submit to server
}
});


Add the routes in your routes/web.php

<?php

use Illuminate\Support\Facades\Route;

use App\Http\Controllers\StripePaymentController;

Route::post('/stripe/checkout', [StripePaymentController::class, 'stripeCheckout'])->name('checkout.credit-card');
Route::get('/stripe/create-payment', [StripePaymentController::class, 'createPaymentIntent']);


Handling Payment Confirmation and Errors


The JavaScript code handles the creation of the Payment Method and confirms the Payment Intent. It also provides real-time feedback to the user by displaying error messages if any issues occur during the payment process.


Testing the Integration

To test the integration:

  1. Ensure your .env file has the correct Stripe test keys.
  2. Start your Laravel development server:
php artisan serve


  1. Navigate to http://localhost:8000/stripe/create-payment to access the payment form.


when you visit the above URL you can see the image like the below one


  1. Use Stripe's test card numbers to simulate payments. For example:
  2. Card Number: 4242 4242 4242 4242 for USA
  3. Card Number: 4000 0035 6000 0008 for INDIA
  4. Expiry Date: Any future date
  5. CVC: Any 3-digit numberWikipedia+6Stripe Support+6Stripe Support+6
  6. ZIP: Any 5-digit number (for indian not required)

For more test card numbers and scenarios, refer to Stripe's testing documentation.


Download the project from github directly https://github.com/codehunger-team/how-to-integrate-stripe-payment-gateway-in-laravel-12.git


Conclusion


Integrating Stripe into your Laravel application without external packages is straightforward and allows for greater control over the payment process. By adhering to Indian regulations and using Stripe's APIs directly, you can create a secure and compliant payment system for your business.

Remember to switch your Stripe keys to live mode when you're ready to accept real payments, and ensure that all necessary business verifications and compliance requirements are met.