我尝试使用Stripe结帐使用Stripe托管的支付页面。Stripe文档与纯PHP兼容。但使用Laravel,它不会重定向到Stripe支付页面。在控制台中,它显示POST http://127.0.0.1:8000/stripe 419 (unknown status)
和Error: SyntaxError: Unexpected token < in JSON at position 0
。根据一些帖子,我在 VerifyCsrfToken 中间件中添加了https://checkout.stripe.com/
。
结帐页面:
<head>
...
<script src="https://polyfill.io/v3/polyfill.min.js?version=3.52.1&features=fetch"></script>
<script src="https://js.stripe.com/v3/"></script>
</head>
<body>
<button type="button" id="checkout-button">Checkout</button>
<script type="text/javascript">
var stripe = Stripe("{{ env('STRIPE_KEY') }}");;
var checkoutButton = document.getElementById("checkout-button");
checkoutButton.addEventListener("click", function () {
fetch("{{ route('stripe-store') }}", {
method: "POST",
})
.then(function (response) {
return response.json();
})
.then(function (session) {
return stripe.redirectToCheckout({ sessionId: session.id });
})
.then(function (result) {
if (result.error) {
alert(result.error.message);
}
})
.catch(function (error) {
console.error("Error:", error);
});
});
</script>
在控制器中:
public function store(Request $request)
{
Stripe::setApiKey(env('STRIPE_SECRET'));
header('Content-Type: application/json');
$checkout_session = Session::create([
'payment_method_types' => ['card'],
'line_items' => [[
'price_data' => [
'currency' => 'usd',
'unit_amount' => 2000,
'product_data' => [
'name' => 'Stubborn Attachments',
],
],
'quantity' => 1,
]],
'mode' => 'payment',
'success_url' => route('welcome'),
'cancel_url' => route('welcome'),
]);
echo json_encode(['id' => $checkout_session->id], JSON_THROW_ON_ERROR);
}
控制器方法的路由是Route::post('stripe', [StripeController::class, 'store'])->name('stripe-store');
请帮帮我。
1条答案
按热度按时间wyyhbhjk1#
在
VerifyCsrfToken
中添加您的路由url。这将排除验证csrf令牌。您可以在App\Http\Middleware
路径文件夹中找到此中间件正如官方文件所说
有时您可能希望从CSRF保护中排除一组URI。例如,如果您使用Stripe处理付款并使用其webhook系统,则需要从CSRF保护中排除Stripe webhook处理程序路由,因为Stripe不知道要向您的路由发送什么CSRF令牌。通常情况下,您应该将这些类型的路由放置在Web中间件组之外,App\Providers\RouteServiceProvider应用于routes/web.php文件中的所有路由。但是,您也可以通过将路由的URI添加到VerifyCsrfToken中间件的$except属性来排除路由:
Laravel 8参考:https://laravel.com/docs/8.x/csrf#preventing-csrf-requests
参考Laravel 10:https://laravel.com/docs/10.x/csrf#csrf-excluding-uris