这是新手Ruby Rails程序员,请帮助我学习。我在Stripe中创建订阅很困难。这是一个学校将注册的应用程序。我已经在Stripe中创建了一个名为“reach”的ID计划,我可以创建一个条带客户令牌,但不能创建订阅。
在我的注册表单(在视图中)中,我有一个hidden_field_tag,其计划名称为“reach”,通过URL传递。我还有一个stripeToken形式的隐藏字段。
我有一个名为SchoolRegistration的类,下面的代码在这里:
attr_accessor :stripeToken
attr_accessor :plan
def save_with_subscription
if valid?
customer = Stripe::Customer.create(description: email, plan: plan, source: stripeToken)
self.stripe_customer_token = customer.id
save!
end
end
我最近发现的是我的观点中的<%= hidden_field_tag :plan, params[:plan] %>
没有保存到我的数据库中。当我点击提交时,我可以在我的控制台上看到它,但它永远不会保存到数据库中。如何将其保存在数据库中?
控制器:
class SchoolRegistrationsController < ApplicationController
def new
@register = SchoolRegistration.new
end
def create
@register = SchoolRegistration.new(register_params)
if @register.save_with_subscription
flash[:success] = "Congratulations! You have registered your school!
redirect_to new_user_registration_path
else
flash[:danger] = @register.errors.full_messages.join(", ")
redirect_to new_registration_path
end
end
private
def register_params
params.require(:school_registration).permit(:name_of_person_completing_form, :email, :role_in_school, :school_name, :grade_levels, :street_name, :city, :state, :zip_code)
end
end
params.require在我的代码中缩进...不确定为什么它不会在这里缩进。
JavaScript的:
/* global $ Stripe */
//Document ready.
$(document).on('turbolinks:load', function(){
//Set Stripe public key.
var stripe = Stripe($('meta[name="stripe-key"]').attr('content'));
var elements = stripe.elements();
// Custom styling can be passed to options when creating an Element.
var style = {
base: {
// Add your base input styles here. For example:
fontSize: '16px',
color: "#32325d",
}
};
// Create an instance of the card Element
var card = elements.create('card', {style: style});
// Add an instance of the card Element into the `card-element` <div>
card.mount('#card-element');
card.addEventListener('change', function(event) {
var displayError = document.getElementById('card-errors');
if (event.error) {
displayError.textContent = event.error.message;
} else {
displayError.textContent = '';
}
});
var form = document.getElementById('payment-form');
form.addEventListener('submit', function(event) {
event.preventDefault();
stripe.createToken(card).then(function(result) {
if (result.error) {
// Inform the customer that there was an error
var errorElement = document.getElementById('card-errors');
errorElement.textContent = result.error.message;
} else {
// Send the token to your server
stripeTokenHandler(result.token);
}
});
});
});
function stripeTokenHandler(token) {
// Insert the token ID into the form so it gets submitted to the server
var form = document.getElementById('payment-form');
var hiddenInput = document.createElement('input');
hiddenInput.setAttribute('type', 'hidden');
hiddenInput.setAttribute('name', 'stripeToken');
hiddenInput.setAttribute('value', token.id);
form.appendChild(hiddenInput);
// Submit the form
form.submit();
}
我知道这可能是显而易见的,我只是遇到了困难,我确实查看了文档。请帮助我学习,非常感谢大家!如果您需要更多信息或代码,请告诉我 - 使用Rails 5。
答案 0 :(得分:0)
通过将计划与您在条带
上创建客户时获得的客户ID相关联来创建订阅Stripe::Subscription.create(
:customer => "cus_4fdAW5ftNQow1a",
:items => [
{
:plan => "basic-monthly",
},
],
)
答案 1 :(得分:0)
好的,我尝试提供完整的条带化实施解决方案,您按照此步骤进行操作,所有代码都经过测试并转到实际网站进行测试here the site
此示例仅限条纹付款
在view/layouts/application.html.erb
<%= javascript_include_tag "https://js.stripe.com/v2/" %>
just above
<%= javascript_include_tag "application" %>
使用条带键创建环境变量
STRIPE_TEST_PUBLISHABLE_KEY: pk_test_xxxxxxxxxx
STRIPE_TEST_SECRET_KEY: sk_test_xxxxxxxxxxxxx
在注册文件中,将以下代码添加到文件顶部:
<script language="Javascript">
Stripe.setPublishableKey("<%= ENV['STRIPE_TEST_PUBLISHABLE_KEY'] %>");
</script>
在表单cc_form
使用引用
为payment
创建模型
rails g model Payment email:string token:string school_registration:references
将在db下生成一个文件,如belo
class CreatePayments < ActiveRecord::Migration[5.0]
def change
create_table :payments do |t|
t.string :email
t.string :token
t.references :school_registration, foreign_key: true
t.timestamps
end
end
end
然后
rake db:migrate
#=> model/SchoolRegistration.rb
#=> add these two lines
has_one :payment
accepts_nested_attributes_for :payment
在payment.rb
attr_accessor :card_number, :card_cvv, :card_expires_month, :card_expires_year
belongs_to :school_registration
def self.month_options
Date::MONTHNAMES.compact.each_with_index.map { |name, i| ["#{i+1} - #{name}", i+1]}
end
def self.year_options
(Date.today.year..(Date.today.year+10)).to_a
end
def process_payment
customer = Stripe::Customer.create email: email, card: token
Stripe::Charge.create customer: customer.id, amount: 1000, description: 'Premium', currency: 'usd'
#=> 1000 means 1000 cents that means 10 dollars
end
现在在您的表单上
<%= fields_for( :payment ) do |p| %>
<div class="row col-md-12">
<div class="form-group col-md-4 no-left-padding">
<%= p.label :card_number, "Card Number", data: {stripe: "label"} %>
<%= p.text_field :card_number, class: "form-control", required: true, data: {stripe: 'number'} %>
</div>
<div class="form-group col-md-2">
<%= p.label :card_cvv, "Card CVV", data: {stripe: "label"} %>
<%= p.text_field :card_cvv, class: "form-control", required: true, data: {stripe: 'cvv'} %>
</div>
<div class="form-group col-md-6">
<div class="col-md-12">
<%= p.label :card_expires, "Caed Expires", data: {stripe: "label" } %>
</div>
<div class="col-md-3">
<%= p.select :card_expires_month, options_for_select(Payment.month_options),
{ include_blank: 'Month' },
"data-stripe" => "exp-month",
class: "form-control", required: true %>
</div>
<div class="col-md-3">
<%= p.select :card_expires_year, options_for_select(Payment.year_options.push),
{ include_blank: 'Year' },
class: "form-control",
data: { stripe: "exp-year" }, required: true %>
</div>
</div>
</div>
<% end %>
现在在名为JS
的{{1}}文件夹下创建javascripts
个文件
stripe.js
最后,转到控制器并添加这些行
$(document).ready(function() {
var show_error, stripeResponseHandler, submitHandler;
submitHandler = function (event) {
var $form = $(event.target);
$form.find("input[type=submit]").prop("disabled", true);
//If Stripe was initialized correctly this will create a token using the credit card info
if(Stripe){
Stripe.card.createToken($form, stripeResponseHandler);
} else {
show_error("Failed to load credit card processing functionality. Please reload this page in your browser.")
}
return false;
};
$(".cc_form").on('submit', submitHandler);
stripeResponseHandler = function (status, response) {
var token, $form;
$form = $('.cc_form');
if (response.error) {
console.log(response.error.message);
show_error(response.error.message);
$form.find("input[type=submit]").prop("disabled", false);
} else {
token = response.id;
$form.append($("<input type=\"hidden\" name=\"payment[token]\" />").val(token));
$("[data-stripe=number]").remove();
$("[data-stripe=cvv]").remove();
$("[data-stripe=exp-year]").remove();
$("[data-stripe=exp-month]").remove();
$("[data-stripe=label]").remove();
$form.get(0).submit();
}
return false;
};
show_error = function (message) {
if($("#flash-messages").size() < 1){
$('div.container.main div:first').prepend("<div id='flash-messages'></div>")
}
$("#flash-messages").html('<div class="alert alert-warning"><a class="close" data-dismiss="alert">×</a><div id="flash_alert">' + message + '</div></div>');
$('.alert').delay(5000).fadeOut(3000);
return false;
};
});
这实际上是一次性订阅和Stripe基本实现,如果您仔细实施并成功,您可以随心所欲。
更多信息请转到Rails Checkout Guide
希望能提供帮助