'How to use format js in rails 7?
I'm using gem stripe in rails 7 and I'd like to access the checkout page to make the payments or cancel the order, however, since it is rails 7 (and does not have a webpacker and nothing related to javascripts) it does not want to recognize the js format at the time of the request
My checkout_controller.rb
class CheckoutController < ApplicationController def create @session = Stripe::Checkout::Session.create({ success_url: root_url, cancel_url: root_url, payment_method_types: ['card'], line_items: [ { price: 'price_1JLaadjkjcanlsr', quantity: 1 }, ], mode: 'payment', }) # here is my problem, not working respond_to do |format| format.js end end end
This is the code in case it recognizes the format.js in the request /chekout/create.js.erb
var stripe = Stripe("<%= Rails.application.credentials.dig(:public_key) %>"); stripe.redirectToCheckout({ sessionId: '<%= @session.id %>' }).then(function (result) { console.log(result.error.message); });
routes
post "checkout/create", to: "checkout#create", as: "checkout_create"
Link to access the stripe payment method
<%= button_to 'Checkout', checkout_create_path, method: :post, remote: true %>
My stripe script in application.html.erb
<script src="https://js.stripe.com/v3/"></script> <%= stylesheet_link_tag "inter-font", "data-turbo-track": "reload" %>
The error that I get it
# ActionController::UnknownFormat Extracted source (around line #21):
})
respond_to do |format|
format.js
end
end
If anyone has been able to work on rails 7 with format js in requests and could help me I'd be very grateful
Solution 1:[1]
class CheckoutController < ApplicationController
def create
@session = Stripe::Checkout::Session.create({
success_url: root_url,
cancel_url: root_url,
payment_method_types: ['card'],
line_items: [
{ price: 'price_1JLaadjkjcanlsr', quantity: 1 },
],
mode: 'payment',
})
# Try do this! Hope this work for you
redirect_to @session.url, allow_other_host: true
end
When you use the Stripe Checkout you need to redirect to the Stripe Site to complete the transaction. Here is a youtube link where explain how to set up in Rails 7 and I found the solution here - Hope it works for you
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 |