Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CORS error when loading Stripe checkout form in Rails

I'm getting a CORS error when trying to redirect to the Stripe component.

Checkout page

<%= form_with scope: :upgrade, url: upgrades_path do |f| %>
   <%= f.hidden_field :plan, value: "price_xxxxxx" %>
   <div class="card-btn">
      <button type="submit" class="btn btn-primary" role="button">Upgrade</button>
   </div>
<% end %>

upgrades_controller.rb

def create
  session = Stripe::Checkout::Session.create({
    line_items: [{
      price: strong_params[:plan],
      quantity: 1,
     }],
     mode: 'subscription',
     success_url: subscribed_upgrades_url,
     cancel_url: cancelled_upgrades_url,
    })

    redirect_to session.url, status: 303, allow_other_host: true
end

initializers/cors.rb

Rails.application.config.middleware.insert_before 0, Rack::Cors do
  allow do
    origins 'https://checkout.stripe.com'
    resource '/upgrades',
      :headers => :any,
      methods: [:get, :post, :put, :patch, :delete, :options, :head]
  end
end

Am seeing this error:

upgrades:1 Access to fetch at 'https://checkout.stripe.com/c/pay/cs_test_a1lErANbYzMDNmAbwfiliytAjAmVeNez4dzJVIBxetc..etc' (redirected from 'http://localhost:3000/upgrades') from origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

How do I get past this error?

like image 437
port5432 Avatar asked Oct 26 '25 15:10

port5432


1 Answers

I could only get this to work by using a link to the GET#new action instead of submitting a form.

Checkout page

<%= link_to 'Upgrade', new_upgrade_path(upgrade: { plan: 'price_xxxxx' }), class: "btn btn-primary" %>

upgrades_controller.rb

def new
  session = Stripe::Checkout::Session.create({
      line_items: [{
        price: strong_params['plan'],
        quantity: 1,
      }],
      mode: 'subscription',
      success_url: subscribed_upgrades_url,
      cancel_url: cancelled_upgrades_url,
    })

  redirect_to session.url
end

private

    def strong_params
      params
        .require(:upgrade)
        .permit(:plan)
    end

The rack-cors gem was no longer needed.

like image 140
port5432 Avatar answered Oct 29 '25 05:10

port5432



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!