First, register and obtain the API key on the Stripe official website, install the stripe/stripe-php extension package and configure the key to the .env file; 2. Create a PaymentController and define checkout, pay, success and error routes; 3. Use the Blade template to build a payment form, load the credit card input elements through Stripe.js and generate a token; 4. Use the secret key and Charge classes in the processPayment method to create payments, process success or failure responses; 5. Optional but recommended to configure a webhook to handle asynchronous events such as payment success and refund, and set corresponding endpoints in the Stripe background; finally, a secure Stripe payment integration in Laravel application ends with a complete sentence.

Integrating a payment gateway like Stripe in a Laravel application is straightforward thanks to Laravel Cashier and Stripe's well-documented API. While Laravel Cashier provides a full subscription billing system, you can also integrate Stripe directly for one-time payments or custom logic without needing Cashier. Below is a practical guide to manually integrate Stripe in Laravel for simple payments.

? 1. Set Up Stripe and Install Dependencies
First, sign up at http://ipnx.cn/link/ab8e9ef52f45f5ccd819e0d96f017447 and get your API keys (publishable key and secret key). You'll use these to authenticate requests.
Install the official Stripe PHP SDK via Composer:

composer requires stripe/stripe-php
Add your Stripe keys to your .env
file:
STRIPE_KEY=pk_test_your_publishable_key
STRIPE_SECRET=sk_test_your_secret_key
Then, reference them in your config or controllers.

? 2. Create Routes and Controller
Generate a controller to handle payment logic:
php artisan make:controller PaymentController
Define routes in routes/web.php
:
Route::get('/checkout', [PaymentController::class, 'showCheckout']);
Route::post('/pay', [PaymentController::class, 'processPayment']);
Route::get('/success', function () {
return "Payment successful!";
});
Route::get('/error', function () {
return "Payment failed!";
});
In your PaymentController
, create a method to show the checkout page:
// app/Http/Controllers/PaymentController.php
use Illuminate\Http\Request;
use Stripe\Stripe;
class PaymentController extends Controller
{
public function showCheckout()
{
return view('checkout');
}
}
Create a Blade view ( resources/views/checkout.blade.php
) with a form and Stripe.js:
<!DOCTYPE html>
<html>
<head>
<title>Checkout</title>
<script src="https://js.stripe.com/v3/"></script>
</head>
<body>
<h2>Pay $10.00</h2>
<form id="payment-form">
@csrf
<div id="card-element">
<!-- Stripe.js injects the Card Element -->
</div>
<button id="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.getElementById('payment-form');
form.addEventListener('submit', async (e) => {
e.preventDefault();
const {token, error} = await stripe.createToken(cardElement);
if (error) {
alert(error.message);
} else {
// Send token to your Laravel backend
const response = await fetch('/pay', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').getAttribute('content')
},
body: JSON.stringify({ token: token.id })
});
const result = await response.json();
if (result.success) {
window.location.href = '/success';
} else {
window.location.href = '/error';
}
}
});
</script>
</body>
</html>
? Never expose your secret key in frontend code. The token is sent securely to your backend, where you use the secret key.
? 4. Process Payment on the Server
Update the processPayment
method in your controller:
use Stripe\Charge;
use Illuminate\Http\JsonResponse;
public function processPayment(Request $request): JsonResponse
{
\Stripe\Stripe::setApiKey(env('STRIPE_SECRET'));
try {
Charge::create([
'amount' => 1000, // $10.00 in cents
'currency' => 'usd',
'source' => $request->token,
'description' => 'Example charge'
]);
return response()->json(['success' => true]);
} catch (\Exception $e) {
return response()->json(['success' => false, 'error' => $e->getMessage()]);
}
}
This creates a charge using the token generated by Stripe.js.
? 5. Handle Webhooks (Optional but Recommended)
For production, always use webhooks to verify asynchronous events like payment_intent.succeeded
, refunds, or failed payments.
Set up a webhook endpoint in routes/web.php
:
Route::post('/webhook', [PaymentController::class, 'handleWebhook']);
In your Stripe dashboard, register the webhook URL (eg, https://yourdomain.com/webhook
).
Verify the payload signature and handle events accordingly.
Bonus Tips
- Use test mode with test cards (eg,
4242 4242 4242 4242
) during development.
- Store charge metadata (eg, user ID, order ID) for tracking.
- For subscriptions, consider using Laravel Cashier , which simplifies recurring billing with Stripe.
Basically, that's it. You've got a working Stripe integration in Laravel. Not too complex, but easy to mess up if you skip security steps like CSRF protection or error handling.
The above is the detailed content of How to integrate a payment gateway like Stripe in Laravel?. For more information, please follow other related articles on the PHP Chinese website!