创建条带事务,而不是每次都重新创建用户

时间:2015-06-08 21:58:08

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

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

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

这是我目前的charge_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行是什么,它都应该在那里徘徊?

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

1 个答案:

答案 0 :(得分:0)

我认为问题在于您是从控制器请求customer_token,而不是从current_user请求。 stripe_customer_token是否存储在用户身上?您是否想要在取得客户之前检查是否存在?如果是的话......

更改:

if self.customer_token.present?

到:

if current_user.stripe_customer_token.present?
相关问题