how-to-implement-stripe-payment-gateway-in-laravel-step-by-step-guide

How to Implement Stripe Payment Gateway in Laravel: Step-by-Step Guide

Hi Brothers,

How to Implement Stripe Payment Gateway in Laravel

Stripe is one of the most popular payment gateways, providing a developer-friendly API for integrating payments into applications. In this guide, we'll explore step-by-step how to implement Stripe in a Laravel project. Whether you're building an e-commerce website, a subscription-based application, or a donation platform, Stripe can handle all your payment needs.


Prerequisites

Before diving into the implementation, ensure the following:

  1. Laravel Installed: A Laravel application set up on your local or server environment. If not, you can create one using:

    composer create-project laravel/laravel stripe-integration
  2. Stripe Account: Sign up for a Stripe account and get your API keys from the dashboard.

  3. Composer Installed: Ensure you have Composer installed for package management.

  4. Basic Laravel Knowledge: Familiarity with routes, controllers, and views in Laravel.


Step 1: Install Stripe Package

To begin, install the Stripe PHP SDK using Composer:

composer require stripe/stripe-php

Step 2: Set Up Environment Variables

Add your Stripe API keys to your .env file:

STRIPE_KEY=your_stripe_publishable_key
STRIPE_SECRET=your_stripe_secret_key

These keys can be found in the Stripe Dashboard.


Step 3: Create a Controller

Generate a new controller to handle Stripe payments:

php artisan make:controller StripeController

In the newly created StripeController, add the following code:

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Stripe\Stripe;
use Stripe\Charge;

class StripeController extends Controller
{
public function paymentPage()
{
return view('stripe.payment');
}

public function processPayment(Request $request)
{
$request->validate([
	'amount' => 'required|numeric|min:1',
	'stripeToken' => 'required',
]);

try {
	Stripe::setApiKey(env('STRIPE_SECRET'));

	Charge::create([
		'amount' => $request->amount * 100,
		'currency' => 'usd',
		'source' => $request->stripeToken,
		'description' => 'Payment from ' . $request->email,
	]);

	return back()->with('success', 'Payment successful!');
} catch (\Exception $e) {
	return back()->with('error', $e->getMessage());
}
}
}

Step 4: Define Routes

Add the following routes to your routes/web.php file:

use App\Http\Controllers\StripeController;

Route::get('/stripe/payment', [StripeController::class, 'paymentPage']);
Route::post('/stripe/process', [StripeController::class, 'processPayment'])->name('stripe.process');

Step 5: Create the Payment View

Create a view file at resources/views/stripe/payment.blade.php:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Stripe Payment</title>
<script src="https://js.stripe.com/v3/"></script>
</head>
<body>
<h1>Stripe Payment Gateway</h1>
@if (session('success'))
<p class="alert alert-success">{{ session('success') }}</p>
@endif

@if (session('error'))
<p class="alert alert-error">{{ session('error') }}</p>
@endif

<form action="{{ route('stripe.process') }}" method="POST">
@csrf
<label for="amount">Amount (USD):</label>
<input type="number" name="amount" id="amount" required>

<label for="card-element">Credit or debit card:</label>
<div id="card-element"></div>

<input type="hidden" name="stripeToken" id="stripeToken">
<button type="submit">Pay</button>
</form>

<script>
const stripe = Stripe("{{ env('STRIPE_KEY') }}");
const elements = stripe.elements();
const cardElement = elements.create('card');
cardElement.mount('#card-element');

const form = document.querySelector('form');
form.addEventListener('submit', async (event) => {
	event.preventDefault();
	const { token, error } = await stripe.createToken(cardElement);
	if (error) {
		console.error(error);
	} else {
		document.getElementById('stripeToken').value = token.id;
		form.submit();
	}
});
</script>
</body>
</html>

Step 6: Test the Integration

Start your Laravel server:

php artisan serve

Visit http://127.0.0.1:8000/stripe/payment to access the payment form. Fill in the amount and use the Stripe test card details for testing:

  • Card Number: 4242 4242 4242 4242
  • Expiry Date: Any future date
  • CVV: Any 3 digits

Submit the form to process the payment.


Step 7: Handle Webhooks (Optional)

To handle asynchronous events such as refunds or disputes, set up Stripe webhooks. Use the Stripe CLI or the dashboard to configure webhooks and add a route to handle events:

Route::post('/stripe/webhook', [WebhookController::class, 'handle']);

You can use Laravel's Cashier package for advanced integrations.


Conclusion

Congratulations! You've successfully integrated Stripe into your Laravel application. This basic implementation can be extended for subscriptions, invoicing, and more. By leveraging Stripe's powerful API, you can create a seamless payment experience for your users.

Scroll