Multiple stripe payment buttons on one page of rails 4 app - javascript

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.
}
});
});

Related

How to call a javascript function in a rails form?

I have a rails form that looks like this :
= form_for :location, :url=>'/welcome' do |f|
= f.text_field '', placeholder: 'Enter your zip code', id:'input_id'
= f.button "Continue", class: 'button-test'
So when the button continue is clicked upon , rails get the controller and execute the method /welcome
so what i am trying to do is to actually execute a simple javascript function like :
function wawa() {
alert('it works')
};
when the button continue is cliked instead of rails getting to execute the method /welcome.
How can I approach this problem using Javascript only and no library ?
You can use submit() function of jquery.
= form_for :location, :url=>'/welcome', html: {id: "id_form_location"} do |f|
= f.text_field '', placeholder: 'Enter your zip code', id:'input_id'
= f.button "Continue", class: 'button-test'
In javascript file:
$("#id_form_location").submit(function(event) {
alert('it works');
});
You need to add some JavaScript On submit Listener I suppose you need it before form is submit. If you want only on click then have a look at on click Listener also have a look at event prevent as it will help you to prevent from default behaviour of button.
Try this code
<%= form_for :location, :url=>'/welcome' do |f| %>
<%= f.text_field '', placeholder: 'Enter your zip code', id:'input_id' %>
<%= f.button "Continue", class: 'button-test', id: 'demo' %>
<% end %>
<script type="text/javascript">
document.getElementById("demo").addEventListener("click", function(event){
event.preventDefault()
alert('Hello')
});
</script>

Submit stops working after first successful submit

I have a simple form in a rails app that is rendered within a partial called roster_panel:
<div id = 'active_admin_content'>
<%= semantic_form_for #roster_item do |form| %>
<h3>Add a counselor</h3>
<div id="counselor_status_message"><%= #status_message %></div>
<%= form.inputs do %>
<%= form.input :first_name, input_html: {id: 'counselor_first_name'} %>
<%= form.input :last_name, input_html: {id: 'counselor_last_name'} %>
<%= form.input :email, input_html: {id: 'counselor_email'} %>
<div class="button_container" >
<input id="submit_counselor_add" type="button" value = "Send forms packet" class = "button" >
</div>
<% end %>
<% end %>
</div>
In my jquery code, I tie the submit click to this:
$( document ).on('turbolinks:load', function() {
$("#submit_counselor_add").click(function(){
$.get("add_counselor_info" , { id: $("#roster_id").text(), first_name: $("#counselor_first_name").val(),
last_name: $("#counselor_last_name").val(), counselor_email: $("#counselor_email").val() },
function(data){ $("#roster_panel").html(data);
}
)
});
});
This routes to this controller method:
def add_counselor_info
#roster = Roster.find(params[:id])
#group = ScheduledGroup.find(#roster.group_id)
#liaison = Liaison.find(#group.liaison_id)
#items = RosterItem.where(roster_id: #roster.id)
#roster_item = RosterItem.new(group_id: #group.id, roster_id: #roster.id,
first_name: params[:first_name], last_name: params[:last_name],
email: params[:counselor_email], youth: false, item_status: 'Unconfirmed' )
if #roster_item.save
#error_count = 0
#status_message = 'This counselor has been added and the forms package has been emailed. You may enter another counselor.'
#items = RosterItem.where(roster_id: #roster.id)
#roster_item = RosterItem.new
else
#error_count = #roster_item.errors.size
#status_message = "#{#error_count} errors prevented saving this information: "
#roster_item.errors.full_messages.each { | message | #status_message << message << ' '}
#items = RosterItem.where(roster_id: #roster.id)
end
render partial: 'roster_panel'
end
After a fresh page load, this process works fine and redisplays the form as expected. However, at that point the submit button no longer triggers the action in jquery. Other jquery functions on the page still work, however. This may have something to do with turbolinks, which I am not very familiar with.
Any help would be appreciated!
After submitting the form, the DOM is replaced by the new one, so on click event binding is being lost.
Try to bind this event through the parent element, which won't be overridden by javascript (e.g. body):
$( document ).on('turbolinks:load', function() {
$("body").on('click', '#submit_counselor_add', function() {
$.get("add_counselor_info", {
id: $("#roster_id").text(),
first_name: $("#counselor_first_name").val(),
last_name: $("#counselor_last_name").val(),
counselor_email: $("#counselor_email").val()
},function(data) {
$("#roster_panel").html(data);
});
});
});

Only allow Stripe Purchases on certain model parameters

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.

ajax auto form submit with rails4

I'm using rails4.2.0
in my e-commerce site, when a user submit his payment type, I want to redirect outside website. The flow is below.
a user choose payment type
use click submit button
-- ajax (format js) --
redirect to outside website using post method
source of 2 and 3 are like ,
create.html.erb
<%= form_for(:user,:url => { controller: "settlements", action: "settlement"}, remote: true, html: {class: :settlement_form}) do |f| %>
<%= f.radio_button :settlement_type, 0 %>paypal
<%= f.radio_button :settlement_type, 1 %>credit card
<%= f.hidden_field :email, :value => #user.email %>
<%= f.hidden_field :fee_type, :value => #user.fee_type %>
<%= f.submit "Submit", data: { disable_with: "Please wait..." }, class: "btn btn-warning" %>
settlement_controller
def settlement
user = User.new(user_params)
if user.save
# parameters for outside website
#payment_params
else
render "new"
end
end
settlement.js.erb
var form = $('<form></form>',{id:"pay",action:'http://outside_ec_site_url/hoge',method:'POST'}).hide();
var body = $('redirect');
body.append(form);
form.append($('<input/>', {type: 'hidden', name: 'something', value: <%= #payment_params[:something] %>}));
form.append($('<input/>', {type: 'hidden', name: 'something', value: <%= #payment_params[:something] %>}))
form.submit();
I fixed this problem, but I want to know better method.
changed settlement.js.erb like,
$("#redirect").html("<%= escape_javascript(render :partial => 'pay' ) %>");
and created new file _pay.html.erb
<script>
$('<form/>', {id: 'paygent',action: "outside_website_url", method: "POST"})
.append($('<input/>', {type: 'hidden', name: 'something1', value: "<%= #payment_params[:somthing1] %>"}))
.append($('<input/>', {type: 'hidden', name: 'something2', value: "<%= #paygent_params[:something2] %>"}))
.appendTo(document.body)
.submit();
</script>
then, it works.
Do you know any other method? Any idea is appriciated.

Completely Stuck on AJAX Form Submission With Stripe

I am so frustrated. I'm working with Stripe to create a form submission system for payments. Basically, the form makes an AJAX call to Stripe, which gives me a token on success, which I then use to resubmit the form, also through AJAX. If the form is successful, it redirects to a new page, if not, it populates the form with error messages without re-navigation. Here's my form:
<%= form_for([#issue, #issue_order]) do |f| %>
<% if #issue_order.errors.any? %>
<div class="error_messages">
<h2><%= pluralize(#issue_order.errors.count, "error") %> occurred. </h2>
<ul>
<% #issue_order.errors.full_messages.each do |msg| %>
<li><%= msg %></li>
<% end %>
</ul>
</div>
<% end %>
<% f.hidden_field :issue_id %>
<%= f.hidden_field :stripe_card_token %>
<div class="field">
<%= f.label :email %>
<%= f.text_field :email %>
</div>
<div class="field">
<%= label_tag :card_number, "Credit Card Number " %>
<%= text_field_tag :card_number, nil, name: nil %>
</div>
<div class="field">
<%= label_tag :card_code, "Security Code on Card (CVV) " %>
<%= text_field_tag :card_code, nil, name: nil %>
</div>
<div class="field">
<%= label_tag :card_month, "Card Expiration " %>
<%= select_month nil, {add_month_numbers_true: true}, {name: nil, id: "card_month"} %>
<%= select_year nil, {start_year: Date.today.year, end_year: Date.today.year + 15}, {name: nil, id: "card_year"} %>
</div>
<div id="stripe_error"></div>
<div class="actions"><%= f.submit "Purchase Issue", id: "submit_issue_order" %></div>
<% end %>
<div class="errors"></div>
Here is the javascript that handles the form and sets up the stripe information:
var issueOrder;
$(function() {
Stripe.setPublishableKey($('meta[name="stripe-key"]').attr('content'));
issueOrder.setupForm();
});
var issueOrder = {
setupForm: function() {
$('#new_issue_order').submit(function(e) {
e.preventDefault();
$('#submit_issue_order').attr('disabled', true);
issueOrder.processCard();
return false;
});
},
processCard: function() {
var card;
card = {
number: $('#card_number').val(),
cvc: $('#card_code').val(),
expMonth: $('#card_month').val(),
expYear: $('#card_year').val()
};
Stripe.createToken(card, issueOrder.handleStripeResponse)
},
handleStripeResponse: function(status, response) {
if (status == 200) {
$('#issue_order_stripe_card_token').val(response.id);
// $('#new_issue_order')[0].submit();
$.ajax({
type: "POST",
url: $('#new_issue_order').attr('action'),
data: { "issue_order": {
"stripe_card_token": $('#issue_order_stripe_card_token').val(),
"email": $('issue_order_email').val(),
},
"issue_id": $('#issue_order_issue_id').val()
},
dataType: "script"
}, issueOrder.processOrder);
}
else {
$('#stripe_error').text(response.error.message);
$('input[type=submit]').attr('disabled', false)
}
}
And here is my controller:
def create
charge = Stripe::Charge.create(
:amount => 400,
:currency => "usd",
:card => params['issue_order']['stripe_card_token']
)
if charge['paid'] == true
#issue_order = IssueOrder.new(email: params['issue_order']['email'], issue_id: params['issue_id'])
if #issue_order.save
#pdf_token = #issue_order.pdf_token
PdfMailer.pdf_email(params['issue_order']['email'], #issue_order).deliver
else·
flash[:error] = []
flash[:error].push("Your card was charged, but sadly we were unable to create·
a record in the database. Please contact us for your copy of the issue.")
respond_to do |format|
format.js
end
end
else
# run checks for errors and return error messages
flash[:error] = []
flash[:error].push("There was an error in processing your payment.")
render :json => {success: false}
end
end
Typical stripe setup stuff. Works fine when the stripe order is successfully processed. Well, it did before I hand-rolled the AJAX call, I'm assuming it'd be fine if I threw a respond_to |format| in the success case in the controller that redirected to the success page. However, for the error cases, my controller renders create.js.erb, which looks like this:
console.log('yo');
$('.errors').empty();
errors = xhr.getResponseHeader('X-Flash-Error').split(',');
<% flash[:error].each do |error| %>
$('.errors').append($('<p>' + <%= error %> + '</p>'));
<% end %>
setTimeout(function() {
$('.errors').empty();
}, 3500);
The controller clearly reaches the file and renders it, as evidenced by the logs:
Started POST "/issues/1/issue_orders" for 127.0.0.1 at 2013-11-12 23:33:17 -0500
Processing by IssueOrdersController#create as JS
Parameters: {"issue_order"=>{"stripe_card_token"=>"tok_102vmu2pSkyWUgPAToj334Oa"}, "issue_id"=>"1"}
(0.4ms) BEGIN
(0.4ms) ROLLBACK
Rendered issue_orders/create.js.erb (0.1ms)
["Your card was charged, but sadly we were unable to create \n a record in the database. Please contact us for your copy of the issue."]
Completed 200 OK in 1363ms (Views: 3.9ms | ActiveRecord: 0.8ms)
But NOTHING happens on my page, including the console log! If I don't hand roll the AJAX and use remote: true, it gets even worse -- it recognizes my submit() call as HTML and doesn't know what to do with the format, rendering an Unknown Format error.
Help!

Categories