Search code examples
phplaravelstripe-paymentslaravel-livewire

How to fix CORS Error using Livewire Stripe Prebuilt Checkout


I'm using a simple Stripe Prebuilt Checkout (HTML/PHP) within a Livewire component.

It works fine on local but not in production.

When I view the Network I see I get a Status: CORS Error then a Status: 403 error.

See image: enter image description here

Here is my code:

Component:

<form wire:submit.prevent="checkout">
    <x-assets.checkout-button type="submit" id="checkout-button">
        Buy Now
    </x-assets.checkout-button>
</form>
@push('stripe')
    <script src="https://polyfill.io/v3/polyfill.min.js?version=3.52.1&features=fetch"></script>
    <script src="https://js.stripe.com/v3/"></script>
@endpush

Then in the Server Side:

    public function checkout()
    {
        \Stripe\Stripe::setApiKey(config('services.stripe.secret'));

        header('Content-Type: application/json');

        $YOUR_DOMAIN      = config('app.url');
        $checkout_session = \Stripe\Checkout\Session::create([
            'billing_address_collection'  => 'required',
            'shipping_address_collection' => [
                'allowed_countries' => ['US'],
            ],
            'line_items' => [[
                // Provide the exact Price ID (e.g. pr_1234) of the product you want to sell
                'price'    => $this->product->stripe_plan,
                'quantity' => 1,
            ]],
            'mode' => 'payment',
            'allow_promotion_codes' => true,
            'success_url'   => url($YOUR_DOMAIN . '/product/thank-you'),
            'cancel_url'    => $YOUR_DOMAIN . '/product',
            'automatic_tax' => [
                'enabled' => false,
            ],
        ]);

        header('HTTP/1.1 303 See Other');
        header('Location: ' . $checkout_session->url);

        return redirect($checkout_session->url);
    }

These are the directions I'm following: https://stripe.com/docs/checkout/quickstart

I have a form element and I'm not using @CSRF because I'm using Livewire.

In my VerifyCsrfToken.php file I have the following for Livewire:

    protected $except = [
        'stripe/webhook',
        'shippo/webhook',
        'discord/webhook',
        'livewire/*',
    ];

Is it something to do with the Headers in the Server side code? header('Content-Type: application/json');


Solution

  • You cannot send a redirect response to a fetch / XMLHttpRequest. You need to either change your client request pattern (eg, a form submit), or send the session url back to the client as data and redirect client-side instead.

    See this previous answer for an example of this: https://stackoverflow.com/a/68630525