首页 文章

如何在Stripe,Rails中保存客户卡更新?

提问于
浏览
3

我希望客户能够在我的Rails应用中更新他们的信用卡详细信息 . Stripe有关于如何实现这一目标的文档,但本文在PHP中展示了一个示例,但我需要一个Rails示例:https://stripe.com/docs/recipes/updating-customer-cards

基本上,我需要保存客户的信用卡而不收费 .

这是 subscribers_controller.rb

class SubscribersController < ApplicationController        
  before_filter :authenticate_user!

  def new
  end

  def update
    token = params[:stripeToken]

    customer = Stripe::Customer.create(
      card: token,
      plan: 1212,
      email: current_user.email
    )

    current_user.subscribed = true
    current_user.stripeid = customer.id
    current_user.save

    redirect_to profiles_user_path
  end
end

2 回答

  • 4

    您可能还想查看此SO答案How to create a charge and a customer in Stripe ( Rails),以获取有关在Rails应用程序中使用Stripe的更多详细信息 .

    对于Ruby文档,您可以在Stripe Ruby API上找到很好的示例 . 在Stripe术语中,客户将卡称为 source . 您可以从 token 创建 source ,但一旦创建,您将处理Customer对象上的 sourcedefault_source 元素,并从客户的 source 中检索 card 对象 . 另请注意,除了创建 source (或一次性费用)之外,您绝不应尝试使用 token .

    Stripe Ruby API for Customers表示您可以创建 customer 并同时分配 source

    customer = Stripe::Customer.create(
        source: token,
        email: current_user.email
    )
    

    您不必分配 source 来创建客户 . 但是,如果您在订阅时设置客户,则需要 source 可用,并且将向客户的 default_source 收取费用 . 如果客户只有一个 source ,则自动为 default_source .

    Stripe Ruby API for Cards表示您还可以使用令牌向现有客户添加新卡:

    customer = Stripe::Customer.retrieve(customer_id)
    customer.sources.create({source: token_id})
    

    一旦您将卡分配给客户,您可以使用以下内容将其设为 default_source

    customer.default_source = customer.sources.retrieve(card_id)
    

    这就是获得设置并准备开始为客户充电所需的条件 . 快乐结算!

  • 1

    要更新现有客户的卡,您提到的PHP配方中的相关代码段是:

    $cu = \Stripe\Customer::retrieve($customer_id); // stored in your application
    $cu->source = $_POST['stripeToken']; // obtained with Checkout
    $cu->save();
    

    在Ruby中,这将是:

    cu = Stripe::Customer.retrieve(customer_id)
    cu.source = params[:stripeToken]
    cu.save
    

    这将使用 stripeToken 参数中包含的令牌使用卡更新现有客户 .

相关问题