NextGenBeing Founder
Listen to Article
Loading...Introduction to Stripe Integration
When I first started working with Stripe, I realized that the documentation, while extensive, didn't cover the nuances of integrating it with Laravel. Our team had to figure out how to handle webhooks, recurring subscriptions, and refunds manually. Here's what I learned from that experience.
Setting Up Stripe in Laravel
The first step is to install the Stripe PHP library. You can do this by running the following command in your terminal:
composer require stripe/stripe-php
After the installation, you need to configure your Stripe keys. You can do this by adding the following lines to your .env file:
STRIPE_KEY=YOUR_STRIPE_SECRET_KEY
STRIPE_PUBLIC_KEY=YOUR_STRIPE_PUBLIC_KEY
Replace YOUR_STRIPE_SECRET_KEY and YOUR_STRIPE_PUBLIC_KEY with your actual Stripe keys.
Handling Payments
To handle payments, you'll need to create a form that sends a request to your server, which then creates a Stripe charge. Here's an example of how you can do this:
use IlluminateHttpRequest;
use StripeCharge;
use StripeStripe;
// Set your secret key: remember to replace this with your live secret key in production
Stripe::setApiKey(env('STRIPE_KEY'));
Route::post('/charge', function (Request $request) {
$charge = Charge::create([
'amount' => $request->input('amount'),
'currency' => 'usd',
'source' => $request->input('stripeToken'),
'description' => 'Test Charge'
]);
// This is your charge ID.
echo $charge->id;
});
This code creates a new charge using the Stripe PHP library. Make sure to replace YOUR_STRIPE_SECRET_KEY with your actual secret key.
Webhooks
Webhooks are crucial for handling events such as successful payments or failed subscriptions. To set up webhooks, you need to configure Stripe to send events to your server. Here's an example of how you can handle webhooks in Laravel:
use IlluminateHttpRequest;
use StripeWebhook;
Route::post('/webhook', function (Request $request) {
$webhookSecret = env('STRIPE_WEBHOOK_SECRET');
$sig_header = $request->header('Stripe-Signature);
$event = Webhook::constructEvent(
$request->all(), $sig_header, $webhookSecret
);
// Handle the event
switch ($event->type) {
case 'charge.succeeded':
// Handle charge succeeded
break;
case 'charge.failed':
// Handle charge failed
break;
}
});
This code constructs a Stripe event from the request data and then handles it based on its type.
Conclusion
Integrating Stripe with Laravel requires careful handling of payments, webhooks, and recurring subscriptions. By following the steps outlined in this guide, you can create a robust and scalable Stripe integration for your Laravel application.
Advertisement
Advertisement
Never Miss an Article
Get our best content delivered to your inbox weekly. No spam, unsubscribe anytime.
Comments (0)
Please log in to leave a comment.
Log In