Laravel Stripe Integration: Step-by-Step Guide (2024) | Gujarat, Mehsana
Integrating Stripe payment gateway in Laravel allows you to accept online payments securely. Follow this step-by-step guide to set up Stripe in your Laravel project, optimized for developers in Gujarat, Mehsana, India.
Step 1: Install Laravel and Stripe Package
First, install a new Laravel project (if not already installed) and require the Stripe package:
composer require stripe/stripe-php
Step 2: Set Up Stripe API Keys
Get your API keys from Stripe Dashboard and add them to your .env file:
STRIPE_KEY=your_publishable_key
STRIPE_SECRET=your_secret_key
Step 3: Configure Stripe in Laravel
Open config/services.php and add the following:
'stripe' => [
'key' => env('STRIPE_KEY'),
'secret' => env('STRIPE_SECRET'),
],
Step 4: Create Payment Controller
Run the command below to create a new controller:
php artisan make:controller PaymentController
Now, open app/Http/Controllers/PaymentController.php and add the following code:
use Stripe\Stripe;
use Stripe\Charge;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
class PaymentController extends Controller {
public function charge(Request $request) {
Stripe::setApiKey(env('STRIPE_SECRET'));
$charge = Charge::create([
'amount' => 1000, // Amount in cents
'currency' => 'usd',
'source' => $request->stripeToken,
'description' => 'Laravel Stripe Payment',
]);
return back()->with('success', 'Payment Successful!');
}
}
Step 5: Create Payment Routes
Open routes/web.php and add:
use App\Http\Controllers\PaymentController;
Route::post('/charge', [PaymentController::class, 'charge'])->name('charge');
Step 6: Create Payment Form
Create a simple form in your resources/views/payment.blade.php file:
<form action="{{ route('charge') }}" method="POST">
@csrf
<script src="https://checkout.stripe.com/checkout.js" class="stripe-button"
data-key="{{ env('STRIPE_KEY') }}"
data-amount="1000"
data-name="Laravel Stripe Payment"
data-description="Secure Payment with Stripe"
data-currency="usd">
</script>
</form>
Step 7: Test Stripe Payment
Run your Laravel project and visit the payment page. Use Stripe test card 4242 4242 4242 4242 to simulate a payment.
Conclusion
You have successfully integrated Stripe payment gateway in Laravel! This setup allows secure online transactions with minimal effort. This guide is particularly beneficial for Laravel developers in Gujarat, Mehsana, and beyond.
Visit Developer Sahayak
0 Comments