2017-07-02 66 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

非常感謝!這工作完美 –