简体   繁体   English

Laravel 条纹结帐:419(未知状态)

[英]Laravel Stripe checkout: 419 (unknown status)

I am trying to use Stripe checkout using the payment page hosted on Stripe.我正在尝试使用 Stripe 上托管的付款页面使用 Stripe 结帐。 Stripe documentation works with pure PHP. Stripe 文档适用于纯 PHP。 But with Laravel, its not redirecting to Stripe payment page.但是对于 Laravel,它不会重定向到 Stripe 支付页面。 In the console, it shows POST http://127.0.0.1:8000/stripe 419 (unknown status) and Error: SyntaxError: Unexpected token < in JSON at position 0 .在控制台中,它显示POST http://127.0.0.1:8000/stripe 419 (unknown status)Error: SyntaxError: Unexpected token < in JSON at position 0 According to some posts, I added https://checkout.stripe.com/ in the VerifyCsrfToken middleware.根据一些帖子,我在VerifyCsrfToken中间件中添加了https://checkout.stripe.com/

The checkout page:结帐页面:

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

In controller:在 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);
}

The route for the controller method is Route::post('stripe', [StripeController::class, 'store'])->name('stripe-store'); controller 方法的路由是Route::post('stripe', [StripeController::class, 'store'])->name('stripe-store');

Please help.请帮忙。

add your route url in VerifyCsrfToken .This will exclude validating csrf token.You can find this middleware in App\Http\Middleware path folder在 VerifyCsrfToken 中添加您的路线VerifyCsrfToken 。这将排除验证 csrf 令牌。您可以在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',
       
    ];
}

As official documentation says正如官方文档所说

Sometimes you may wish to exclude a set of URIs from CSRF protection.有时您可能希望从 CSRF 保护中排除一组 URI。 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.例如,如果您使用 Stripe 处理付款并使用他们的 webhook 系统,则需要将您的 Stripe webhook 处理程序路由从 CSRF 保护中排除,因为 Stripe 不会知道要向您的路由发送什么 CSRF 令牌。 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.通常,您应该将这些类型的路由放在 web 中间件组之外,App\Providers\RouteServiceProvider 应用于 routes/web.php 文件中的所有路由。 However, you may also exclude the routes by adding their URIs to the $except property of the VerifyCsrfToken middleware:但是,您也可以通过将路由的 URI 添加到 VerifyCsrfToken 中间件的 $except 属性来排除路由:

Ref: https://laravel.com/docs/8.x/csrf#preventing-csrf-requests参考: https://laravel.com/docs/8.x/csrf#preventing-csrf-requests

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM