无需每次都重新创建用户即可创建 Stripe 事务

Creating Stripe transactions without recreating the user each time

我一直在开发 Rails 购物车应用程序,并注意到每次我下(测试)订单时,Stripe API 中的示例代码都会创建一个新客户。

这显然是不可取的,作为一个 Ruby/Rails 新手,我一直在搜索 SO 和我能找到的每个教程,以弄清楚如何让它在创建客户之前检查客户是否存在。这样做的标准方法似乎是检查 stripe_customer_token 并根据是否存在进行处理。但是无论我如何处理它,我都会得到 customer_token 的 NoMethodError。

这是我现在的charges_controller.rb:

class ChargesController < ApplicationController
  def new
  end

  def create
    if self.customer_token.present?
    @customer = Stripe::Customer.retrieve(current_user.stripe_customer_token)
    else
    @customer = Stripe::Customer.create(
      :email => self.manager.email, card => stripe_token
    )
      charge = Stripe::Charge.create(
        :amount => (params[:amount].to_f * 100).abs.to_i,
        currency => "usd",
        card => params[:stripeToken],
        description => params[:email]
      )
      @amount = params[:amount]
      @payment_id = charge.id
    end
  end
end 

我从服务器得到的是:

Started POST "/charges" for 50.184.82.198 at 2015-06-08 21:26:57 +0000
Processing by ChargesController#create as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"BLAHBLAHBLAH", "stripeToken"=>"BLAHBLAH", "stripeTokenType"=>"card", "stripeEmail"=>"danicastone@gmail.com"}
Completed 500 Internal Server Error in 7ms

NoMethodError (undefined method `customer_token' for #<ChargesController:0x007fa788783638>):
app/controllers/charges_controller.rb:48:in `create'

第 48 和 49 行是:

if self.customer_token.present?
@customer = Stripe::Customer.retrieve(current_user.stripe_customer_token)

(行号如此之高,因为上面有相当多的注释掉的代码,我尝试过不同的东西)

奇怪的是(对我的新手来说)它在 stripe_customer_token 处乱码,但是如果我将 stripe_customer_token 更改为 customer_token,它会在它之前的行处乱码 - - 在 self.customer_token。当然,如果那是个问题,不管第 49 行是什么,它都应该在那里乱扔垃圾?

更重要的是,任何人都可以阐明我在这里做错了什么,或者我在这个网站上可能遗漏的任何解决方案吗?谢谢!!

我认为问题是您从控制器而不是 current_user 请求 customer_tokenstripe_customer_token 是存储在用户身上的东西吗?您是否想在吸引客户之前检查它是否存在?如果是这样……

变化:

if self.customer_token.present?

至:

if current_user.stripe_customer_token.present?