在 Rails 中使用 Stripe 处理返回用户

Handling returning users with Stripe in Rails

我正在努力将 Stripe 集成到我的 Rails 应用程序中。我无法找到有关如何处理回头客的说明。不过,我不是指订户,而是指可能会回来购买其他商品的用户帐户。我不想一直向他们询问信用卡信息。例如在 airbnb,我把我的卡放了一次,现在它记住了。我如何在 Rails 中做同样的事情?

假设您已经在前端创建了一个 stripe_token 并将其传递给服务器,您可以 create a customer object (using the Stripe gem) 使用自己的令牌保存到数据库,例如:

customer = Stripe::Customer.create(
  source: stripe_token,
  description: "#{user.full_name} (#{user.email})"
)
user.stripe_customer_token = customer.id
user.save!

我发现设置一个好的描述很有用,因为此信息将显示在 Stripe 网络 GUI 中。

然后您可以使用此令牌按需创建新费用:

charge = Stripe::Charge.create({
  amount: (amount * 100).to_i, # billed in cents
  currency: 'USD',
  customer: user.stripe_customer_token,
  description: "Charge",
  statement_descriptor: "Example.com Charge",
})

这笔费用还有一个令牌,您可以根据需要保留该令牌:

user.charges.create! stripe_token: charge.id