Ruby on Rails新手遇Stripe::InvalidRequestError:Checkout参数使用错误
解决Stripe Checkout的Stripe::InvalidRequestError问题
你遇到的错误是因为当前Stripe API版本已废弃line_items.amount、line_items.currency、line_items.name等直接定义商品信息的字段,必须改用price或price_data参数。以下是两种可行的修复方案:
方案1:用price_data动态定义商品价格(适合临时/动态定价场景)
直接在代码中动态生成价格和商品信息:
# CheckoutController#create 代码示例 def create session = Stripe::Checkout::Session.create({ payment_method_types: ['card'], line_items: [{ price_data: { currency: 'cny', # 替换为你的货币代码,如'usd' product_data: { name: '你的商品名称', description: '商品描述内容', images: ['https://your-domain.com/product-image.jpg'] # 替换为实际图片URL }, unit_amount: 9900 # 单位为分,此处代表99元 }, quantity: 1 }], mode: 'payment', # 一次性付款用payment,订阅用subscription success_url: 'http://your-domain.com/payment-success', # 替换为你的成功跳转URL cancel_url: 'http://your-domain.com/payment-cancel', # 替换为你的取消跳转URL }) redirect_to session.url, allow_other_host: true end
方案2:用预先创建的Price对象(适合固定价格商品,生产环境推荐)
- 先在Stripe后台创建Product和对应的Price,复制Price的ID(格式类似
price_xxxxxx) - 在代码中直接引用该Price ID:
# CheckoutController#create 代码示例 def create session = Stripe::Checkout::Session.create({ payment_method_types: ['card'], line_items: [{ price: 'price_xxxxxx', # 替换为你在Stripe后台创建的Price ID quantity: 1 }], mode: 'payment', success_url: 'http://your-domain.com/payment-success', cancel_url: 'http://your-domain.com/payment-cancel', }) redirect_to session.url, allow_other_host: true end
额外注意事项
- 确认
mode参数与你的收费类型匹配:一次性付款用payment,订阅服务用subscription - 替换所有占位符为你的实际业务信息
- 若仍报错,运行
bundle update stripe更新Stripe SDK到最新版本
内容的提问来源于stack exchange,提问作者user21515097
相关产品推荐
相关产品推荐

