javascript - Laravel Stripe 结帐 : 419 (unknown status)

标签 javascript php laravel stripe-payments

我正在尝试使用 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 .根据一些帖子,我添加了 https://checkout.stripe.com/VerifyCsrfToken 中间件中。

结帐页面:

<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>

在 Controller 中:

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);
}

Controller 方法的路由是Route::post('stripe', [StripeController::class, 'store'])->name('stripe-store');

请帮忙。

最佳答案

VerifyCsrfToken 中添加您的路由 url。这将排除验证 csrf token 。您可以在 App\Http\Middleware 路径文件夹中找到此中间件

<?php

namespace App\Http\Middleware;

use Illuminate\Foundation\Http\Middleware\VerifyCsrfToken as Middleware;

class VerifyCsrfToken extends Middleware
{
    /**
     * The URIs that should be excluded from CSRF verification.
     *
     * @var array
     */
    protected $except = [
        'stripe',
       
    ];
}

正如官方文档所说

Sometimes you may wish to exclude a set of URIs from CSRF protection. For example, if you are using Stripe to process payments and are utilizing their webhook system, you will need to exclude your Stripe webhook handler route from CSRF protection since Stripe will not know what CSRF token to send to your routes. Typically, you should place these kinds of routes outside of the web middleware group that the App\Providers\RouteServiceProvider applies to all routes in the routes/web.php file. However, you may also exclude the routes by adding their URIs to the $except property of the VerifyCsrfToken middleware:

引用:https://laravel.com/docs/8.x/csrf#preventing-csrf-requests

关于javascript - Laravel Stripe 结帐 : 419 (unknown status),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67946176/

相关文章:

php - 登录系统设计允许每个用户一次登录一台机器

mysql - 查询总和(总计)

laravel - 使用 laravel 上传到 s3 存储桶文件夹

javascript - 如何在开始时播放播放列表中的单个轨道编号?

javascript - 具有多种类型复选框的数据表

php - Foreach 与 php 和 mysql

php - 如何根据php中的条件复选框回显隐藏的表单字段?

javascript - 如何在异步等待操作中测试 catch 语句

javascript - 如何修复 linting no shadowed variable 警告

php - 如何使 MySQL 对类型严格