2016-11-12 151 views
0

我刚刚使用Stripe转换功能模型以创建charge以创建subscription,出于某种原因,现在它创建了两个订阅而不是一个订阅。我new查看代码,因为它的工作并没有改变,所以问题不在这里(在我看来),但由于this SO post曾与JS一个问题,我想反正表露出来:Stripe创建两个订阅

<%= form_tag charges_path do %> 
    <article> 
    <% if flash[:error].present? %> 
     <div id="error_explanation"> 
     <p><%= flash[:error] %></p> 
     </div> 
    <% end %> 
    <label class="amount"> 
     <span>Amount: $7.99/month</span> 
    </label> 
    </article> 

    <script src="https://checkout.stripe.com/checkout.js" class="stripe-button" 
      data-key="<%= Rails.configuration.stripe[:publishable_key] %>" 
      data-description="Generator Subscription" 
      data-amount="799" 
      data-locale="auto"></script> 
<% end %> 

这里是我的控制器,在那里我相信这个问题必须位于:

class ChargesController < ApplicationController 
    def new 
    unless current_user 
     flash[:error] = "Step one is to create an account!" 
     redirect_to new_user_registration_path 
    end 

    if current_user.access_generator 
     flash[:notice] = "Silly rabbit, you already have access to the generator!" 
     redirect_to controller: 'generators', action: 'new' 
    end 
    end 

    def create 
    customer = Stripe::Customer.create(
     :email => params[:stripeEmail], 
     :source => params[:stripeToken], 
     :plan => "generator_access" 
    ) 

    subscription = Stripe::Subscription.create(
     :customer => customer.id, 
     :plan => "generator_access" 
    ) 

    if subscription 
     current_user.update_attributes(access_generator: true) 
     current_user.update_attributes(stripe_customer_id: subscription.customer) 
     current_user.update_attributes(stripe_sub_id_generator: subscription.id) 
     flash[:notice] = "You have been granted almighty powers of workout generation! Go forth and sweat!" 
     redirect_to controller: 'generators', action: 'new' 
    end 

    rescue Stripe::CardError => e 
    flash[:error] = e.message 
    redirect_to new_charge_path 
    end 

    def cancel_subscription 
    @user = current_user 
    customer = Stripe::Customer.retrieve(@user.stripe_customer_id) 
    subscription = Stripe::Subscription.retrieve(@user.stripe_sub_id_generator) 

    if customer.cancel_subscription(params[:customer_id]) 
     @user.update_attributes(stripe_customer_id: nil, access_generator: false, stripe_sub_id_generator: nil) 
     flash[:notice] = "Your subscription has been cancelled." 
     redirect_to user_path(@user) 
    else 
     flash[:error] = "There was an error canceling your subscription. Please notify us." 
     redirect_to user_path(@user) 
    end 
    end 

end 

cancel_subscription方法效果很好(有一次我手动删除通过条纹仪表盘复制订阅),所以它真的有什么东西在“创建”方法。我还检查了我的控制台,并且User属性的信息正在正确更新,以匹配正在创建的两个重复订阅中的第二个。

任何人都可以看到为什么这段代码产生两个订阅?

回答

0

当您使用计划创建客户时,会自动创建相应的订购。您不需要手动创建它。

+0

非常好!这解决了它。谢谢! – Liz