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.
Before diving into the implementation, ensure the following:
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
Stripe Account: Sign up for a Stripe account and get your API keys from the dashboard.
Composer Installed: Ensure you have Composer installed for package management.
Basic Laravel Knowledge: Familiarity with routes, controllers, and views in Laravel.
To begin, install the Stripe PHP SDK using Composer:
composer require stripe/stripe-php
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.
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());
}
}
}
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');
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>
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:
4242 4242 4242 4242
Submit the form to process the payment.
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.
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.