2017-07-02 99 views
0

我是Rails的新手,目前正在开发我的第一个网站。 所以这里是我的问题:
每次我创建一个服务的订阅,它给了我一个Stripe :: InvalidRequestError说“计划已经存在”。我发现这是必须对Stripe Plan ID做些什么的。Rails条纹“计划已经存在”

我想要做的是,当用户点击订阅时,它应该检查具有相同ID的计划是否已经存在。如果具有相同ID的计划不存在,则应该创建该计划。如果它确实存在,它不应该创建该计划,而只是订阅该计划的客户。

这里是我的尝试:

class PaymentsController < ApplicationController 
    before_action :set_order 

    def create 
    @user = current_user 

    unless Stripe::Plan.id == @order.service.title 
    plan = Stripe::Plan.create(
     :name => @order.service.title, 
     :id => @order.service.title, 
     :interval => "month", 
     :currency => @order.amount.currency, 
     :amount => @order.amount_pennies, 
    ) 
    end 

在上面,你可以看到,我想,我可以只使用条纹的ID,但显然这是行不通的。

customer = Stripe::Customer.create(
    source: params[:stripeToken], 
    email: params[:stripeEmail], 
    ) 

    # Storing the customer.id in the customer_id field of user 
    @user.customer_id = customer.id 

    Stripe::Subscription.create(
    :customer => @user.customer_id, 
    :plan => @order.service.title, 
    ) 

    @order.update(payment: plan.to_json, state: 'paid') 
    redirect_to order_path(@order) 

    rescue Stripe::CardError => e 
     flash[:error] = e.message 
     redirect_to new_order_payment_path(@order) 
    end 

    private 

    def set_order 
     @order = Order.where(state: 'pending').find(params[:order_id]) 
    end 
    end 
+0

检查'条纹:: Plan.id'并打印它的值 – Pavan

+0

它告诉我! #未定义的方法'id“。所以当我尝试打印时没有任何价值。当我第一次创建它时,我将ID分配给字符串“测试”。 –

+0

您可以发布用户点击订阅按钮时生成的参数吗? – Pavan

回答

0

你检查计划的存在没有写的方式。 Stripe::Plan.id不起作用,所以这个unless Stripe::Plan.id == @order.service.title总是失败。通过使用retrieve方法你应该得到计划和使用,像下面

@plan = Stripe::Plan.retrieve(@order.service.title) 
unless @plan 
    plan = Stripe::Plan.create(
    :name => @order.service.title, 
    :id => @order.service.title, 
    :interval => "month", 
    :currency => @order.amount.currency, 
    :amount => @order.amount_pennies, 
) 
end 

What I want to do is, when the User clicks subscribe, it should check if the plan with the same id already exists. If the Plan with the same ID doesn't exist, it should create the Plan. If it does exist, it should not create the Plan and just subscribe the customer to the plan

编写代码来创建预订在上述方法的else一部分计划。所以最后的方法是

@plan = Stripe::Plan.retrieve(@order.service.title) 
unless @plan 
    plan = Stripe::Plan.create(
    :name => @order.service.title, 
    :id => @order.service.title, 
    :interval => "month", 
    :currency => @order.amount.currency, 
    :amount => @order.amount_pennies, 
) 
else 
    subscription = Stripe::Subscription.create(
    :customer => Your customer here, 
    :plan => @order.service.title 
) 
end 
+1

非常感谢!这工作完美 –