I am trying to implement Stripe Checkout using the custom integration in a rails app - my checkout form shows a green checkmark saying it submitted but the payment is not being processed. The simple integration works well, as do subscription payments on other parts of my site.
Like the simple integration, I am trying to place the custom integration script inside of a form_tag - I followed the Rails Checkout guide, which unfortunately is only written for the simple integration. Like the guide, I have a charges controller, with new and create actions to show the form and create the charges.
Charges Controller:
class ChargesController < ApplicationController
def new
end
def create
# Amount in cents
#amount = 500
customer = Stripe::Customer.create(
:email => params[:stripeEmail],
:card => params[:stripeToken]
)
charge = Stripe::Charge.create(
:customer => customer.id,
:amount => #amount,
:description => 'Rails Stripe customer',
:currency => 'usd'
)
rescue Stripe::CardError => e
flash[:error] = e.message
redirect_to charges_path
end
end
And in my new view, the form is setup as follows:
<%= form_tag charges_path do %>
<script src="https://checkout.stripe.com/checkout.js"></script>
<button id="customButton" class="btn btn-large btn-primary">Buy Now</button>
<script>
var handler = StripeCheckout.configure({
key: '<%= ENV["STRIPE_PUBLIC_KEY"] %>',
image: '/assets/my_logo.png',
token: function(token, args) {
// Use the token to create the charge with a server-side script.
}
});
document.getElementById('customButton').addEventListener('click', function(e) {
// Open Checkout with further options
handler.open({
name: 'My Company',
description: 'Product ($60.00)',
amount: 60*100,
shippingAddress: true
});
e.preventDefault();
});
</script>
<% end %>
I have tried just about everything I can think of, but the form will not be submitted to trigger the create action. I see the note to use a server side script, but can anyone point me in the right direction on what I may be missing?
Any help is much appreciated!! Thanks!
You need to finish the token callback function.
First pass in the response from the Stripe handler as an argument and then append the token id and email as inputs to the form before submitting it: (untested)
token: function(response) {
var tokenInput = $("<input type=hidden name=stripeToken />").val(response.id);
var emailInput = $("<input type=hidden name=stripeEmail />").val(response.email);
$("form").append(tokenInput).append(emailInput).submit();
}
Here is a working solution. Add an id to your form tag. Add a stripeToken and stripeEmail hidden field to your form tag. Then when we receive the token from Stripe we will use JavaScript to set the values of the hidden fields and submit the form by referencing their id's:
<%= form_tag charges_path, id: 'chargeForm' do %>
<script src="https://checkout.stripe.com/checkout.js"></script>
<%= hidden_field_tag 'stripeToken' %>
<%= hidden_field_tag 'stripeEmail' %>
<button id="customButton" class="btn btn-large btn-primary">Buy Now</button>
<script>
var handler = StripeCheckout.configure({
key: '<%= ENV["STRIPE_PUBLIC_KEY"] %>',
image: '/assets/my_logo.png',
token: function(token, args) {
document.getElementById("stripeToken").value = token.id;
document.getElementById("stripeEmail").value = token.email;
document.getElementById("chargeForm").submit();
}
});
document.getElementById('customButton').addEventListener('click', function(e) {
// Open Checkout with further options
handler.open({
name: 'My Company',
description: 'Product ($60.00)',
amount: 60*100,
shippingAddress: true
});
e.preventDefault();
});
</script>
<% end %>
This can be solved many ways but bare in mind this is a JavaScript problem nothing to do with Rails or Stripe really. Stripe are simply giving us the token we can do whatever we want with it with JavaScript.
I think you don't want to preventDefault here, because that prevents your form from being submitted to the server. Does it submit the form to the create action when you take out e.preventDefault(); ?
With the "simple integration" you can still change the text in the default blue button with the data-label attribute(eg data-label='Buy now') using the configuration options. But yeh you have to use "custom integration" to fully style the button yourself
Related
Rails newbie here, working with Stripe's API. I have a model in my rails app called pieces. Each piece has an integer called status. I only want people to be able to purchase the piece if the piece has a status of 1. In my current code, I have hid the buy button on the pieces unless the piece of the status is 1. This works most of the time, but, if two people view the piece at the same time, then they can both buy them. This is because the status of the piece on the other page does not update until the page is reloaded.
My request: I want to find a way to check that the piece's status is 1, right before someone buys it. If it is not 1, I want there to be a rails flash message saying that the piece has already been bought. This should prevent the user from being charged and prevent a charge from being created.
Here is my charges controller:
class ChargesController < ApplicationController
def create
piece = Piece.find(params[:piece_id])
customer = Stripe::Customer.create(
:email => params[:stripeEmail],
:source => params[:stripeToken]
)
charge = Stripe::Charge.create(
:customer => customer.id,
:amount => piece.total_price_in_cents,
:description => piece.title,
:currency => 'usd'
)
purchase = Purchase.create(
customer_email: params[:stripeEmail],
total_transaction: piece.total_price,
stripe_fee: piece.stripe_fee,
taxes: piece.taxes,
artist_cut: piece.artist_cut,
charity_cut: piece.charity_cut,
our_cut: piece.our_cut,
currency: charge.currency,
card: params[:stripeToken],
description: charge.description,
customer_id: customer.id,
piece_id: piece.id,
customer_name: params[:stripeShippingName],
customer_address_line_1: params[:stripeShippingAddressLine1],
customer_city: params[:stripeShippingAddressCity],
customer_state: params[:stripeShippingAddressState],
customer_zip_code: params[:stripeShippingAddressZip],
customer_country: params[:stripeShippingAddressCountry],
seller_name: piece.user.name,
seller_email: piece.user.email,
seller_address_line_1: piece.user.address_line_1,
seller_address_line_2: piece.user.address_line_2,
seller_city: piece.user.city,
seller_state: piece.user.state,
seller_zip_code: piece.user.zip_code
)
purchase.ship_by = purchase.created_at + 7.days
purchase.arrive_by = purchase.created_at + 21.days
purchase.save!
piece.status = 3
piece.save!
redirect_to pieces_path, notice: "Thanks for buying #{piece.title} for $#{'%.2f' % piece.total_price}. You should get an email shortly."
rescue Stripe::CardError => e
flash[:error] = e.message
redirect_to new_charge_path
end
end
And here is my show page for the pieces, which has the stripe buy button on it:
<div class="container">
<div class="row">
<div class="col-md-offset-2 col-md-8">
<div class="panel panel-default">
<div class="panel-body">
<!-- Stripe Form -->
<% if current_user != #piece.user && #piece.status == 1 %>
<%= form_tag charges_path, id: 'chargeForm' do %>
<script src="https://checkout.stripe.com/checkout.js"></script>
<%= hidden_field_tag 'stripeToken' %>
<%= hidden_field_tag 'stripeEmail' %>
<button id="btn-buy-show" type="button" class="btn btn-success btn-lg btn-block">Buy for $<%= number_with_precision(#piece.total_price, :precision => 2, :delimiter => ',')%></button>
<script>
var handler = StripeCheckout.configure({
key: '<%= Rails.configuration.stripe[:publishable_key] %>',
shippingAddress: true,
token: function(token, arg) {
document.getElementById("stripeToken").value = token.id;
document.getElementById("stripeEmail").value = token.email;
document.getElementById("chargeForm").submit();
}
});
document.getElementById('btn-buy-show').addEventListener('click', function(e) {
handler.open({
name: 'Metallic Palette',
description: '<%= #piece.title %> ($<%= number_with_precision(#piece.total_price, :precision => 2, :delimiter => ',')%>)',
amount: document.getElementById("amount").value
});
e.preventDefault();
})
</script>
<% end %>
<% end %>
<% if #piece.status == 3 %>
<p>This piece has already been bought.
<% if current_user == #piece.user || admin_user_signed_in? %>
<%= render 'pieces/purchase_details' %>
<% end %>
</p>
<% end %>
</div>
</div>
</div>
Thank you guys so much.
You just need to check it :)
def create
piece = Piece.find(params[:piece_id])
if piece.status != 1
flash[:error] = 'Piece is not available :('
return redirect_to peaces_path # or whatever
end
...
end
However, few suggests for you:
1) Don't use numbers in your code. Make constants (like Piece::AVAILABLE) and methods (piece.available?) or use enum. You will have lots of problems in future, if you will just use your numbers
2) Extract form object - you don't want to have so large methods in your controller. If you extract it to separate service - it will be much more testable, predictable and updatable.
3) Extract Piece.find and piece status check into before_filters.
I have deployed a custom Stripe payment form in our app, and 97% of the time it works just fine. Occasionally, I see Stripe report an error on an attempted payment.
POST /v1/customers
error:
type: "invalid_request_error"
message: "You passed an empty string for 'card'. We assume empty values are an attempt to unset a parameter; however 'card' cannot be unset. You should remove 'card' from your request or supply a non-empty value"
param: "card"
This is raised when creating a customer with the Stripe token that should've been generated from the javascript:
sale = current_user.sales.create(
plan_id: plan.id,
amount: plan.price_in_cents,
stripe_token: params[:stripeToken]
)
After much troubleshooting I've confirmed that this is happening because Stripe is not getting called in the first place to create the token. In other words, this is not an issue of passing params, where the token is generated but simply not passed to the controller. For some reason, something in the javascript is not running, so the form simply submits without it calling Stripe.
Again remember that 97% of the time this issue does not occur. When it does occur it happens to the same user over and over again. I have not found any pattern with browsers (it has happened on Chrome, IE, Firefox). Also, eventually users facing this problem have been able to successfully pay using the same browser and without any settings adjustments. This makes me think there's something potentially with my server environment and not the client.
Here is my full javascript:
subscription.js
var stripeResponseHandler = function(status, response) {
var $form = $('#paid_subscription');
if (response.error) {
// Show the errors on the form
$form.find('.payment-errors').text(response.error.message);
$form.find('button').prop('disabled', false);
} else {
// token contains id, last4, and card type
var token = response.id;
// Insert the token into the form so it gets submitted to the server
$('#stripe_card_token').val(token);
//$form.append($('<input type="hidden" name="stripeToken" />').val(token));
// and submit
$form.get(0).submit();
}
};
jQuery(function($) {
$('#card_number').payment('formatCardNumber')
$('#paid_subscription').submit(function(event) {
// var expiration = $("#card-expiry").payment("cardExpiryVal")
// $('#card-exp-month').val(expiration.month);
// $('#card-exp-year').val(expiration.year);
var $form = $(this);
// Disable the submit button to prevent repeated clicks
$form.find('button').prop('disabled', true);
Stripe.card.createToken($form, stripeResponseHandler);
// Prevent the form from submitting with the default action
return false;
});
});
And here is the controller code, just in case:
charges#create
def create
token = params[:stripeToken]
bundle = Bundle.find_by_id(params[:bundle_id])
if bundle
process_bundle_sale(bundle, token)
else
plan = Plan.find(params[:plan_id])
begin
sale = current_user.sales.create(
plan_id: plan.id,
amount: plan.price_in_cents,
stripe_token: params[:stripeToken]
)
sale.process!
if sale.finished?
if current_user.subscribe_with_referer({plan_id: plan.id}, session[:http_referer])
TrackSubscriptions.track_paid_subscription(cookies, plan, sale)
flash[:success] = "Success! You now have full access to \"#{plan.title}\""
redirect_to plan_path(plan)
else
flash[:alert] = "Oops something went wrong. Please contact support and we'll get to the bottom of it."
redirect_to plan_path(plan)
end
else
flash[:alert] = sale.error
redirect_to new_plan_subscription_path(plan.slug)
#redirect_to plan_path(plan)
end
end
end
end
Finally here's the form code:
<%= simple_form_for #charge = Sale.new, :url => charges_path, :method => :post, html: { id: :paid_subscription } do |f| %>
<fieldset class = "inputWrapper">
<h2 class="sub-header">Payment</h2>
<span class="payment-errors"></span>
<%= hidden_field_tag :plan_id, #plan.id %>
<%= hidden_field_tag :stripeToken, nil,id: :stripe_card_token %>
<div class="payment-fields">
<div class="field card-number-field">
<label class="control-label">Card Number</label>
<%= text_field_tag :card_number, nil, name: nil, placeholder: "4444 1234 1234 1234",:data => {:stripe => 'number' } %>
</div>
<div class="field security-code-field">
<label class="control-label">Security Code</label>
<%= text_field_tag :card_code, nil, name: nil, placeholder: "123", :data => {:stripe => 'cvc' } %>
</div>
<div class="field expiry-field">
<label class="control-label">Exp (MM/YYYY)</label>
<div class="month-field">
<%= text_field_tag :exp_month, nil, name: nil, placeholder: "10", id: "card-exp-month", maxlength: 2, data: { stripe: "exp-month" } %>
<span class="slash"> / </span>
</div>
<div class="year-field">
<%= text_field_tag :exp_year, nil, name: nil, placeholder: "2016", id: "card-exp-year", maxlength: 4, data: { stripe: "exp-year" } %>
</div>
</div>
<div style="clear:both"></div>
</div>
<%= render 'end_form', :plan => #plan %>
<div class="submit-button">
<%= f.submit 'Register for Course', :class => "button greenButton", :error => false %>
</div>
</fieldset>
<% end %>
I'm building a payment page that lists three different subscription options and am using Stripe's checkout to manage the payments.
The page is rendering properly, and all 3 subscription options have the "buy now" button that should be linked to Stripe.
My issue is that the first button is the only one that is properly pulling up the Stripe checkout flow. Buttons 2 and 3 throw the following error:
Unknown action
The action 'index' could not be found for ChargesController
The relevant part of my payment page is:
<% #plans.each do |plan| %>
<li class="col-md-3 plan <%= 'plan-primary' if plan.highlight? %>">
<div class="img-thumbnail">
<div class="caption">
<h3><%= plan.name %></h3>
<h4><%= plan_price(plan) %></h4>
<div class="call-to-action">
<% if #subscription.nil? %>
<% if plan.highlight? %>
<%= form_tag main_app.charges_path do %>
<script src="https://checkout.stripe.com/checkout.js"></script>
<button id="customButton" class="btn btn-success">Buy Now</button>
<script>
var handler = StripeCheckout.configure({
key: '<%= 'pk_test_my_pk' %>',
image: '/assets/my_logo.png',
token: function(response) {
var tokenInput = $("<input type=hidden name=stripeToken />").val(response.id);
var emailInput = $("<input type=hidden name=stripeEmail />").val(response.email);
$("form").append(tokenInput).append(emailInput).submit();
}
});
document.getElementById('customButton').addEventListener('click', function(e) {
handler.open({
name: 'My Co',
description: 'Listing subsctiption ($50.00)',
amount: 50*100,
shippingAddress: false
});
e.preventDefault();
});
</script>
<% end %>
<% else %>
<%= form_tag main_app.charges_path do %>
<script src="https://checkout.stripe.com/checkout.js"></script>
<button id="customButton" class="btn btn-large btn-primary">Buy Now</button>
<script>
var handler = StripeCheckout.configure({
key: '<%= 'pk_test_my_pk' %>',
image: '/assets/my_logo.png',
token: function(response) {
var tokenInput = $("<input type=hidden name=stripeToken />").val(response.id);
var emailInput = $("<input type=hidden name=stripeEmail />").val(response.email);
$("form").append(tokenInput).append(emailInput).submit();
}
});
document.getElementById('customButton').addEventListener('click', function(e) {
// Open Checkout with further options
handler.open({
name: 'My Co',
description: 'Listing subsctiption ($40.00)',
amount: 40*100,
shippingAddress: false
});
e.preventDefault();
});
</script>
<% end %>
<% end %>
Ideas on why only one of the 3 buttons is working properly?
Thanks!
You can get it to seem to work by having unique button ids, e.g.
<button id="<%= dom_id(pricing, 'btn') %>
but there is another problem, with the stripe js. If you execute StripeCheckout.configure multiple times it will create multiple iframes with the same name attribute. Unfortunately this means whatever your customer tries to buy, they will always be sold the last thing you inserted, even if the stripe popup said it was selling them something else.
We used this solution: one form, and dynamically inserting the price and times:
<%= form_tag charges_path, id: 'stripe-payment-form' do %>
<%= hidden_field_tag 'amount', nil, id: 'payment_amount' %>
<%= hidden_field_tag 'name', nil, id: 'payment_name' %>
<%= hidden_field_tag 'days', nil, id: 'payment_days' %>
<% Pricing.all.each do |pricing| %>
<p>
<button id="<%= dom_id(pricing, 'btn') %>">
Buy <%= pricing.name %> for <%= number_to_currency(pricing.pounds, unit: '£') %>
</button>
</p>
<% end %>
<%= javascript_tag do %>
var handler = StripeCheckout.configure({
key: "<%= Rails.configuration.stripe[:publishable_key] %>",
image: "<%= image_path('/images/apple-icons/apple-touch-icon-144x144-precomposed.png') %>",
token: function(token, args) {
var form = $('#stripe-payment-form');
// Use the token to create the charge with a server-side script.
// You can access the token ID with `token.id`
form.append($('<input type="hidden" name="stripeToken" />').val(token.id));
form.submit();
}
});
<% Pricing.all.each do |pricing| %>
document.getElementById('<%= dom_id(pricing, 'btn') %>').addEventListener('click', function(e) {
e.preventDefault();
var form = $('#stripe-payment-form');
// set the price etc for the button clicked
$('#payment_amount').val("<%= pricing.pence %>");
$('#payment_name').val("<%= pricing.name %>");
$('#payment_days').val("<%= pricing.days %>");
// Open Checkout with further options
handler.open({
name: 'Company name',
currency: 'GBP',
description: '<%= pricing.name %>',
amount: '<%= pricing.pence %>',
email: '<%= member.email %>',
});
});
<% end %>
<% end %>
<% end %>
I came across the same problem in my own app recently.
All three of your buttons have the same ID.
I know this is old, but I resolved this issue by changing the name of the handler variables (each one should have a different name) instead of changing the HTML ID's.
I recently encountered this problem and wanted to leave an alternative solution. In our app, we have two buttons on the page using stripe.js: "Buy Item" or "Pro Subscription". This method uses jQuery to just remove the second button from the DOM when the first one is clicked. If the user cancels the payment, the button is rendered back into the DOM. This is how the handler might look:
$('#firstButton').on('click', function() {
$('#secondButton').html(""); // Remove the second stripe script from the dom
handler.open({
// handler stuff
closed: function(){
$('#secondButton').html('<%= j render partial: "second_button" %>'); // Renders button back to the DOM if payment is cancelled.
}
});
});
I'm developing autocomplete for a particular form in my rails app; for this purpose I'm using typeahead.js with custom controller method. So far, it works but I need using those values within the form again so that I can press the submit button and the form will be posted and processed by rails normally. How can I do this? Here's the code right now
.page-header
%h1
= #org.name
%small= t('.title')
= form_for #org_admin, |
url: organization_organization_admins_path(#organization) do |f|
.form-group
= f.label t('.user')
= f.hidden_field :user, id: 'user_id'
%input.typeahead{ :type => "text", :autocomplete => "off"}
= f.submit t('.submit'), class: 'btn btn-primary'
= link_to t('.back'), organization_organization_admins_path(#organization)
:javascript
$(document).ready(function() {
$('input.typeahead').typeahead({
name: 'names',
remote: "#{search_organization_organization_admins_path(#organization)}?term=%QUERY",
engine: Hogan,
template: '<p><strong>{{username}}</strong></p>',
limit: 10
}).on('typeahead:selected', function(e, data){
$('#user_id').value = data.id
});
});
So, I would like to populate the :user attribute in the form with the json object returned by the controller
Nevermind, I figured out... the above code is in the right path, except for the call to this line
$('#user_id').value = data.id
Since I'm using jQuery to select the hidden element I had to use the jQuery val function instead
$('#user_id').val(data.id)
I stuck here need help
Ruby on rails
I have one Pop-up for login it is coming when i click on link "Sign in" using jquery
Now i want to validate username and password entered by user from database
Login popup is a partial page sign in.html.erb
any solutions. plz
depends on which validation framework you are using.
the key is to keep the dialog not closed once server responses.
(NOT RECOMMENDED) if you are not using any javascript validation framework, you have to make the "form" a "remote form", then submit it, then display the error messages if validation failed.
(MY EXPERIENCE) if you are using an javascript validation framework such as RSV(really simple validation), just define the validation rules, then implement 2 ajax methods: 1 is used for validating the form, another is a callback function used to process the response from remote and display it in the dialog.
anyway, dealing with the error message for a dialog is not very easy and straightforward than dealing with it for a regular page. Anyway, I hope you got my idea.
Here is my login partial which i have render and also validate it.
<div class="clost_holder"> <%= link_to image_tag("/assets/close-new.png"), "javascript:;", :onclick => "close_popup()" %>
</div>
<%= form_for(#user, :as => #user, :url => session_path(#user), :html => {:id => 'sign_in_form', :onsubmit => "return false;"}) do |f| %>
<div class="login_input_holder mtop20 flt">
<label>Email</label>
<p><%= link_to 'dont have an account ?', :controller => 'devise/registrations', :action => 'new' %></p>
<%= f.email_field :email %>
</div>
<div class="login_input_holder mtop10 flt">
<label>Password</label>
<%= f.password_field :password %>
</div>
<div class="fogot_password "><%= link_to 'forgot password ?', :controller => 'devise/passwords', :action => 'new' %></div>
<div class="login_btn frt"><input type="submit" value="signin" id='sign_in_btn'></div>
<% end %>
And then validate it.But you need to add jquery.validate and jquery.form files also.
<script type="text/javascript">
$("#sign_in_btn").click(function() {
if (!jQuery("#sign_in_form").valid()) {
return false;
}
else {
var container = $("#home1_content");
$("#sign_in_form").submit(function() {
$(this).unbind('submit').ajaxSubmit({
success: function(data) {
container.html(data);
window.location.reload();
}
})
});
}
});
$(document).ready(function() {
$("#sign_in_form").validate({
rules:{
"user[email]":
{
required: true ,
email: true
},
"user[password]":
{
required: true
},
messages: {
"user[email]": "This field is required",
"user[password]": "This field is required"
}
}
});
});
</script>