2017-02-08 6 views
0

Попытка взимать плату с клиента за регистрацию продукта. Я слежу за этим уроком upskillcourses.com. Какая настройка подписки. Я просто пытаюсь создать плату за продукт.Rails Stripe integration no active card error

Я получаю это error:
Stripe::CardError in Roadregistrations::RegistrationsController#create Cannot charge a customer that has no active card

Я настроить stripe.js файл:

приложение/активы/JavaScripts/

/* global $, Stripe */ 
//Document ready. 
$(document).on('turbolinks:load', function(){ 
var theForm = $('#payment-form'); 
var submitBtn = $('#form-submit-btn'); 

//Set Stripe public key. 
Stripe.setPublishableKey($('meta[name="stripe-key"]').attr('content')); 
//When user clicks form submit btn, 
submitBtn.click(function(event){ 
//prevent default submission behavior. 
event.preventDefault(); 
submitBtn.val("Processing").prop('disabled', true); 
//Collect the credit card fields. 
var ccNum = $('#card_number').val(), 
    cvcNum = $('#card_code').val(), 
    expMonth = $('#card_month').val(), 
    expYear = $('#card_year').val(); 
//Use Stripe JS library to check for card errors. 
var error = false; 
//Validate card number. 
if(!Stripe.card.validateCardNumber(ccNum)) { 
    error = true; 
    alert('The credit card number appears to be invalid'); 
} 
//Validate CVC number. 
if(!Stripe.card.validateCVC(cvcNum)) { 
    error = true; 
    alert('The CVC number appears to be invalid'); 
} 
//Validate expiration date. 
if(!Stripe.card.validateExpiry(expMonth, expYear)) { 
    error = true; 
    alert('The expiration date appears to be invalid'); 
} 
if (error) { 
    //If there are card errors, don't send to Stripe. 
    submitBtn.prop('disabled', false).val("Register and Pay"); 
} else { 
    //Send the card info to Stripe. 
    Stripe.createToken({ 
    number: ccNum, 
    cvc: cvcNum, 
    exp_month: expMonth, 
    exp_year: expYear 
    }, stripeResponseHandler); 
} 
return false; 
}); 

//Stripe will return a card token. 
function stripeResponseHandler(status, response) { 
//Get the token from the response. 
var token = response.id; 
//Inject the card token in a hidden field. 
theForm.append($('<input type="hidden" name="user[stripe_card_token]">').val(token)); 
//Submit form to our Rails app. 

theForm.get(0).submit(); 
} 
}); 

Что это походит на token не представляются с формой.

Не уверен, что если мне нужно оба эти в моем users_controller.rb:

# Only allow a trusted parameter "white list" through. 
def roadregistration_params 
    params.require(:user).permit(:first_name, :last_name, :company, :street, :city, :state, :zip, :email, :phone, :roadshowcity, :stripe_card_token, :comments) 
end 

protected 
    def configure_permitted_parameters 
    devise_parameter_sanitizer.permit(:sign_up) { |u| u.permit(:stripe_card_token, :password, :password_confirmation, :email, :first_name, :last_name, :company, :street, :city, :state, :zip, :phone, :roadshowcity, :comments) } 
    end 

Тогда у меня есть это в моем user model:

attr_accessor :stripe_card_token 
# If user passes validations (email, pass, etc.), 
# Call stripe and tell stripe to set up a subscription 
def save_with_registration 
    if valid? 
    @product_price = Objective.find(objective_id) 
     customer = Stripe::Customer.create(email: email, card: stripe_card_token, description: stripe_card_token.to_s) 

     charge = Stripe::Charge.create(
     :customer => customer.id, 
     :amount => 9500, 
     :currency => "usd", 
     :description => "Roadshow Registration" 
    ) 
     self.stripe_customer_token = customer.id 
     save! 
    end 
    end 

customer = Stripe::Customer.create(email: '[email protected]') => #<Stripe::Customer:0x3ffd3a10e024 id=cus_A5CWbyto5ugmju> JSON: { "id": "cus_A5CWbyto5ugmju", "object": "customer", "account_balance": 0, "created": 1486585998, "currency": null, "default_source": null, "delinquent": false, "description": null, "discount": null, "email": "[email protected]", "livemode": false, "metadata": {}, "shipping": null, "sources": {"object":"list","data":[],"has_more":false,"total_count":0,"url":"/v1/customers/cus_A5CWbyto5ugmju/sources"}, "subscriptions": {"object":"list","data":[],"has_more":false,"total_count":0,"url":"/v1/customers/cus_A5CWbyto5ugmju/subscriptions"} }

ответ

0

Вы просто должны связать карту клиент после создания клиента на полосе и перед его зарядкой:

customer = Stripe::Customer.create(email: email) 
customer.sources.create(card: stripe_card_token) # <-- this 
charge = Stripe::Charge.create(.. 

И я бы посоветовал не отправлять stripe_card_token в объект клиента.

Если вы используете версию старше 2015-02-18 версии API, замените sources на cards.

+0

Благодарим вас за ответ, но это просто дает мне ошибку: 'undefined method' cards 'для # Corey

+0

Можете ли вы опубликовать результат 'customer = Stripe :: Customer.create (email: '[email protected]')' на вашей консоли rails. –

+0

Я добавил вывод к моему вопросу о стеке. – Corey

0

Turbolinks не загружается в файл app/assets/javascripts/application.js. Исправление этой проблемы позволило запустить java-скрипт и передать stripe_card_token.