Stripe为现有用户的购买创建新客户

时间:2014-02-25 21:21:26

标签: ruby-on-rails ruby-on-rails-4 stripe-payments

我发现如果用户第二次购买产品,我的条带信息中心会创建一个新客户。我想这样,一旦客户首次购买,购买后将向现有客户及其保存的卡收取费用。 我的应用正在运行Rails 4。

charges_controller.rb

def create
  @user = current_user
  @gift = Gift.friendly.find(params[:gift_id])
  @charge = Charge.new(charge_params)
  @codes = Code.all
  @code = @gift.codes.where(:used => false).order("created_at ASC").first
  token = params[:stripeToken]
  if @user.customer_id.nil?
    # Create customer
      customer = Stripe::Customer.create(
      :card => token,
      :email => @user.email
    )
    # Charge the customer instead of the card
    Stripe::Charge.create(
      :amount => (@gift.price * 100).to_i,
      :currency => "cad",
      :customer => customer.id
    )
    # Customer_id is set to the Stripe customer.id
    customer_id = customer.id
    # If the transaction is approved
    if @charge.save
      # And user selects save_cc
      if @charge.save_cc == true
        # Update User's cusomter_id field to the var
        @user.update_attributes(:customer_id => customer_id)
        send_code(@user, @gift, @charge, @code)
      else 
        send_code(@user, @gift, @charge, @code)                     
      end 
    else 
      render 'charges/new'
    end 
  else
    # If user already has customer_id
    Stripe::Charge.create(
      :amount => (@gift.price * 100).to_i,
      :currency => "cad",
      :customer => @user.customer_id
    )
    if @charge.save 
      send_code(@user, @gift, @charge, @code)
    else 
      render 'charges/new'
    end 
  end 
end

1 个答案:

答案 0 :(得分:2)

您可以尝试首先从Stripe检索客户(如果她已经存在),然后进行交易。

在此示例中,customer_token是我存储在数据库中的客户ID。

customer = nil
if self.customer_token.present?
  customer = Stripe::Customer.retrieve(self.customer_token)
else
  customer = Stripe::Customer.create(
    :email => self.manager.email,
    :card  => stripe_token
  )
end

charge = Stripe::Charge.create(
  :customer    => customer.id,
  :amount      => total_amount_cents,
  :description => "...",
  :currency    => 'cad'
)

self.update_attributes(has_membership: true,
                       customer_token: customer.id,
                       last_payment_at: Time.zone.now)

PS:我建议将其放在transaction块中,以确保一切顺利。