首先在Stripe官網(wǎng)注冊并獲取API密鑰,安裝stripe/stripe-php擴(kuò)展包并將密鑰配置到.env文件;2. 創(chuàng)建PaymentController并定義checkout、pay、success和error路由;3. 使用Blade模板構(gòu)建支付表單,通過Stripe.js加載信用卡輸入元素并生成token;4. 在processPayment方法中使用secret key和Charge類創(chuàng)建支付,處理成功或失敗響應(yīng);5. 可選但推薦配置webhook來處理支付成功、退款等異步事件,并在Stripe后臺設(shè)置對應(yīng)端點(diǎn);最終實(shí)現(xiàn)了一個安全的Laravel應(yīng)用內(nèi)Stripe支付集成,以完整句?結(jié)束。

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 require 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 (e.g., https://yourdomain.com/webhook
).
Verify the payload signature and handle events accordingly.
Bonus Tips
- Use test mode with test cards (e.g.,
4242 4242 4242 4242
) during development.
- Store charge metadata (e.g., 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.
以上是如何整合Laravel中的Stripe之類的付款網(wǎng)關(guān)?的詳細(xì)內(nèi)容。更多信息請關(guān)注PHP中文網(wǎng)其他相關(guān)文章!