You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Stripe Checkout会话创建控制器语法错误排查求助

CheckoutsController 语法错误修复

问题定位

  • 哈希结构嵌套错误:Stripe::Checkout::Session.create的参数中,mode、success_url、cancel_url应与payment_method_types、line_items同级,但原代码在line_items闭合后多写了一个},导致这些参数被排除在主哈希外,触发语法错误。
  • line_items参数结构错误:quantity字段属于line_items数组内的对象属性,而非price_data的子属性,原代码的嵌套方式既不符合Stripe API要求,也会引发Ruby语法问题。
  • 冗余逗号(可选修复):metadata哈希中post_id键值对末尾的逗号虽不影响Ruby运行,但可能导致语法检查警告。

修正后的代码

class CheckoutsController < ApplicationController
  respond_to :js

  def create
    @session = Stripe::Checkout::Session.create({
      payment_method_types: ['card'],
      line_items: [{
        price_data: {
          product: "prod_Miva1sJtJ2u812",
          currency: 'usd',
          metadata: {
            post_id: params[:post_id]
          }
        },
        quantity: 1
      }],
      mode: 'payment',
      success_url: "http://localhost:3000",
      cancel_url: "http://localhost:3000"
    })

    respond_to do |format|
      format.js
    end
  end
end

修改说明

  1. 移除line_items闭合后的多余},让mode、success_url等参数归位到主哈希中。
  2. 将quantity从price_data内移出,放到line_items的对应对象里,匹配Stripe API的参数结构。
  3. 移除metadata哈希内的冗余逗号,代码更规范。
  4. 统一缩进格式,提升可读性。

内容的提问来源于stack exchange,提问作者bad-reputation

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.13 12:21:12