Stripe is one of the most popular and secure payment gateways for handling online payments. Laravel makes Stripe integration easy using its clean syntax and powerful ecosystem. In this tutorial, you’ll learn how to integrate Stripe payments in a Laravel application step by step.
Prerequisites
- A Laravel application
- A Stripe account
- Stripe API keys (Test mode)
Step 1: Install Stripe PHP Library
Install the official Stripe PHP SDK using Composer:
composer require stripe/stripe-php
Step 2: Configure Stripe API Keys
Add your Stripe keys to the .env file:
STRIPE_KEY=pk_test_your_public_key STRIPE_SECRET=sk_test_your_secret_key
Step 3: Update Services Configuration
Open config/services.php and add the Stripe configuration:
'stripe' => [
'key' => env('STRIPE_KEY'),
'secret' => env('STRIPE_SECRET'),
],
Step 4: Create Payment Route
Define routes for displaying the payment form and processing the payment:
use App\Http\Controllers\StripeController;
Route::get('/stripe', [StripeController::class, 'index']);
Route::post('/stripe/payment', [StripeController::class, 'payment'])->name('stripe.payment');
Step 5: Create Payment Controller
Create a controller to handle Stripe payments:
use Illuminate\Http\Request;
use Stripe\Stripe;
use Stripe\Charge;
public function index()
{
return view('stripe');
}
public function payment(Request $request)
{
Stripe::setApiKey(config('services.stripe.secret'));
Charge::create([
'amount' => $request->amount * 100,
'currency' => 'usd',
'source' => $request->stripeToken,
'description' => 'Stripe Payment'
]);
return back()->with('success', 'Payment successful!');
}
Step 6: Create Stripe Payment Form
Create a Blade file to collect payment details:
<form action="{{ route('stripe.payment') }}" method="POST">
@csrf
<input type="number" name="amount" placeholder="Enter Amount" required>
<script
src="https://checkout.stripe.com/checkout.js"
class="stripe-button"
data-key="{{ config('services.stripe.key') }}"
data-name="Laravel Stripe Payment"
data-description="Test Payment"
data-currency="usd">
</script>
</form>
Step 7: Handle Success Message
Display success messages after payment completion:
@if(session('success'))
<div class="alert alert-success">
{{ session('success') }}
</div>
@endif
Common Issues
- Invalid Stripe API keys
- Incorrect currency or amount
- Missing CSRF token
Conclusion
Integrating Stripe payment gateway in Laravel is simple and efficient. By following this guide, you can securely accept online payments and scale your application with confidence using Stripe’s powerful APIs.
Comments
Post a Comment