首页 > 解决方案 > Stripe Prebuilt Checkout Session 在 Laravel 8 中返回 404 错误

问题描述

我在 Laravel 8 中实现 Stripe 的预建结帐页面时遇到了非常令人沮丧的时间。经过研究,我将控制器调整如下

 // We grab the Stripe key information we added in the .env file
        \Stripe\Stripe::setApiKey('####');

        // Creates the Stripe session
        $session = \Stripe\Checkout\Session::create ([
            'payment_method_types' => ['card'],
            'billing_address_collection' => 'required',
            'shipping_address_collection' => ['allowed_countries' => ['US', 'CA'],],
            'line_items' => [[
                'price_data' => [
                    'currency' => 'usd',
                    'product_data' => [
                   'name' => 'T-shirt',
               ],
                    'unit_amount' => $total_amount*100,
                ],
                'quantity' => 1,
            ]],
            'mode' => 'payment',
            'allow_promotion_codes' => true,
            'success_url' => 'http://127.0.0.1:8002/',
            'cancel_url' => 'http://127.0.0.1:8002/',
        ]);

        // Return the Stripe Session id so the fetch command in our frontend redirects users to Stripe's checkout page
        return response()->json(['id' => $session->id]);

我的 routes.web 文件中的代码是 Route::post('/stripe/order', [StripeController::class, 'payment']);

我确保我的表格看起来像这样

<form action="/stripe/order" method="POST" id="payment-form">
                            @csrf

还有一些像这样的javascript代码......

 // Create an instance of the Stripe object with your publishable API key
    var stripe = Stripe('####');
    var checkoutButton = document.getElementById('checkout-button');

    checkoutButton.addEventListener('click', function() {
        // Create a new Checkout Session using the server-side endpoint you
        // created in step 3.
        fetch('/stripe/order', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'Accept': 'application/json',
                'url': '/stripe/order',
                "X-CSRF-Token": document.querySelector('input[name=_token]').value
            },
        })
        .then(function(response) {
            return response.json();
        })
        .then(function(session) {
            return stripe.redirectToCheckout({ sessionId: session.id });
        })
        .then(function(result) {
            // If `redirectToCheckout` fails due to a browser or network
            // error, you should display the localized error message to your
            // customer using `error.message`.
            if (result.error) {
                alert(result.error.message);
            }
        })
        .catch(function(error) {
            console.error('Error:', error);
        });
    });

有人知道它为什么返回 404 错误吗?

标签: phpstripe-paymentslaravel-8

解决方案


推荐阅读