【发布时间】:2021-04-04 23:15:35
【问题描述】:
我刚刚将功能模型从使用 Stripe 创建 charge 转换为创建 subscription 并且由于某种原因现在它创建了两个订阅而不是一个。我的new 视图上的代码自从它工作以来没有改变,所以问题不在这里(在我看来),但由于this SO post 的 js 有问题,我还是想展示它:
<%= 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 属性的信息正在正确更新,以匹配正在创建的两个重复订阅中的第二个。
谁能明白为什么这段代码会产生两个订阅?
【问题讨论】:
标签: ruby-on-rails stripe-payments