Rails/React集成Stripe时后端重定向被拦截问题求助
Rails集成Stripe重定向支付表单出错问题
问题描述
我正在网站上集成Stripe以接收付款,但从Rails后端API重定向到Stripe支付表单时遇到错误,是否需要进行特定配置才能解决该问题?我已添加Rack CORS以允许前后端之间的资源共享。
相关代码与配置
PaymentController.rb
class Api::PaymentsController < ApplicationController def create price = Listing.find(params[:listing_id]) @session = Stripe::Checkout::Session.create({ customer: current_user.stripe_customer_id, payment_method_types: ['card'], line_items: [{ price: price.stripe_price_id, quantity: params[:quantity], }], allow_promotion_codes: true, mode: 'payment', success_url: "#{api_success_url}?session_id={CHECKOUT_SESSION_ID}", cancel_url: api_cancel_url }) redirect_to @session.url, status: 303, allow_other_host: true end end
routes.rb
Rails.application.routes.draw do root to: 'static_pages#root' namespace :api do resources :listings, only: [:show, :index, :new, :create] post '/create-checkout-session', to: "payments#create" get "/success", to: "payments#success" get "cancel", to: "payments#cancel" end end
cors.rb
Rails.application.config.middleware.insert_before 0, Rack::Cors do allow do origins "*" resource "*", headers: :any, methods: [:get, :post, :put, :patch, :delete] end end
Checkout.js
import React from 'react'; import PulseLoader from '../loaders/pulse_loader'; import ListingShowFooter from '../listings/listing_show/listing_show_footer'; import axios from "axios"; class Checkout extends React.Component { constructor(props) { super(props); this.state = { loading: true, total: 100, days: 7 } this.submit = this.submit.bind(this); } componentDidMount() { this.props.fetchListing(this.props.listingId); } async submit(e) { e.preventDefault(); const data = { price: this.state.total, quantity: this.state.days, } const response = await axios.post("/api/create-checkout-session", data, { headers: { 'Content-Type': 'application/json', 'Accept': 'application/json' }, }) const res = await response.data; return res; } render() { let { currentUser, listing, bookingParams } = this.props; if (this.state.loading || !listing) { return ( <div className="loader__container"> <PulseLoader /> </div> ); } return ( <div className="checkout__container"> <form className="checkout__btn-wrapper" onSubmit={this.submit}> <button type="submit" className="checkout__btn" >Agree and book</button> </form> </div> ); } } export default Checkout;
错误信息
请求的资源上不存在Access-Control-Allow-Origin头,因此源http://localhost:3000不被允许访问。如果不需要获取响应内容,可以将请求的mode设置为no-cors以禁用CORS来获取资源。
内容的提问来源于stack exchange,提问作者Mwape Samuel
相关产品推荐
相关产品推荐

