I am going through a bootcamp right now on learning web development using cloud 9 ide and Ruby on Rails. I have imported the gem for Stripe. And I have set up my JavaScript for taking the credit card information and sending it to Stripe then have Stripe send back a Customer token to Rails server for record with the email account used on signup. However when I go to test it out the payment never goes through. It processes the request and creates a new user for the site but when I go to stripe's webpage there are no transactions.
Here is my code:
/* global $, Stripe */
//Document ready.
$(document).on('turbolinks:load', function(){
var theForm = $('#pro_form');
var submitBtn = $('#form-signup-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("Sign Up");
} 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();
}
});
I do not receive any kind of error so I am unsure what the issue is. If you need to see my other files of code please let me know which ones and I will post them.
Thanks for all the help.
Related
I'm currently taking the upskill tutorial "The Essential Web Developer Course"(currently on lesson 162) where i try to connect Stripe with a payment for a premium membership. This tutorial is working with older versions of the gems and libraries, etc., thats why I'm telling you that.
The problem is that after Stripe sends me back a costumer token. It won't get stored in my db and it won't sign in to the membership. Instead my submit button will stay disabled and shows the string "Processing".
The dev-console shows the: "Uncaught TypeError: Cannot read property 'submit' of undefined" message.
What do I need to change? Has it sth. to do with my save_with_subscription method?
attr_accessor :stripe_card_token
def save_with_subscription
if valid?
customer = Stripe::Customer.create(description: email, plan: plan_id, card: stripe_card_token)
self.stripe_customer_token = customer.id
save!
end
The js file for it:
/* global $, Stripe */
//Document ready.
$(document).on('turbolinks:load', function(){
var theForm = $('#pro_form');
var submitBtn = $('#form-signup-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("Sign Up");
} 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();
}
});
All of my code can be found at https://github.com/JakkSwords/upskill_saas_tutorial/tree/user_memberships
I have a payment form that has the following JS to generate a stripe token.
var form = $( "#new_subscription" );
form.validate();
jQuery(function($) {
$('#new_subscription').submit(function(event) {
var $form = $(this);
$form.find('#formSubmit').prop('disabled', true);
Stripe.card.createToken($form, stripeResponseHandler);
return false;
});
});
function stripeResponseHandler(status, response) {
var $form = $('#new_subscription');
if (response.error) {
// Show the errors on the form
$form.find('.payment-errors').text(response.error.message);
$form.find('.payment-errors').removeClass('hidden');
$form.find('#formSubmit').prop('disabled', false);
} else {
$form.find('.payment-errors').addClass('hidden');
// response contains id and card, which contains additional card details
var token = response.id;
// Insert the token into the form so it gets submitted to the server
$form.append($('<input type="hidden" name="stripe_token" />').val(token));
// Remove Stripe cc fields
$("[data-stripe=number]").remove();
$("[data-stripe=cvc]").remove();
$("[data-stripe=exp-year]").remove();
$("[data-stripe=exp-month]").remove();
// and submit
$form.get(0).submit();
}
};
in my controller, I have:
if !#subscription.errors.blank?
#user = User.new(user_params)
#subscription_item = SubscriptionItem.new(subscription_item_params)
flash.now[:error] = #subscription.errors[:base][0]
render :new
When I use Stripe test cc number 4000000000000341, it renders the correct Payment Declined error message on the new subscription form. And in the Stripe dashboard, it shows a failed payment associated with this card.
However, if I then enter a test card number that should successfully charge (4000000000000077) and submit, I get the same error as before. The test charges in the dashboard show that it is still trying to use the same card.
It's only after a page refresh that the form will send the correct card.
I'm not understanding why my page is sending the card number from the first submission when I enter a new card.
I am getting a error 402 after a customer has enter their card parameters and submits the order. Note: there is no capture, the card parameters are records in the customer's account in Stripe to be captured at a later time. It was working then, not working one day. Not sure if Stripe has changed anything but here is the javascript code, I think it has to do with the status console:
Stripe.setPublishableKey('pk_live_xxxxrTZawxjutHNRrXbJJ9c');
var show_error, stripeResponseHandler;
$("#card_code").on('change',function (event) {
var $form;
$form = $(this);
$('.continue').attr("disabled", true);
processcard()
return false;
});
var processcard = function(){
Stripe.card.createToken({
number: $('#card_number').val(),
cvc: $('#card_code').val(),
exp_month: $('#expires').val().slice(0,2),
exp_year: $('#expires').val().slice(2,4)
},stripeResponseHandler);
function stripeResponseHandler(status, response){
console.log(status);
if(status == 200){
$("#user_card_token").val(response.id);
$('.continue').removeAttr("disabled");
}else{
$('.continue').attr("disabled", true);
return false
}
}
I am using Stripe and "custom forms" from the API. The following code is throwing errors if something is wrong, in English, but I want to translate some of the error messages into Norwegian to make it more user friendly for my customers. For example "invalid_expiry_year" and "invalid_expiry_month" which is currently in English.
Is it possible to achieve and if so, how?
<script type="text/javascript" src="https://js.stripe.com/v2/"></script>
<script type="text/javascript">
Stripe.setPublishableKey('pk_test_2iA9ERjj5lVuUgvOS9W5fNtV');
$(function() {
var $form = $('#payment-form');
$form.submit(function(event) {
// Disable the submit button to prevent repeated clicks:
$form.find('.submit').prop('disabled', true);
// Request a token from Stripe:
Stripe.card.createToken($form, stripeResponseHandler);
// Prevent the form from being submitted:
return false;
});
});
function stripeResponseHandler(status, response) {
function stripeHandler( status, response ){
if ( response.error && response.error.type == 'card_error' ){
$( '.errors' ).text( errorMessages[ response.error.code ] );
}
else {
// do other stuff (and handle api/request errors)
}
}
// Grab the form:
var $form = $('#payment-form');
if (response.error) { // Problem
// Show the errors on the form:
$form.find('.payment-errors').text(response.error.message);
$form.find('.submit').prop('disabled', false); // Re-enable submission
} else { // Token was created!
// Get the token ID:
var token = response.id;
// Insert the token ID into the form so it gets submitted to the server:
$form.append($('<input type="hidden" name="stripeToken">').val(token));
// Submit the form:
$form.get(0).submit();
}
};
</script>
There is an option for you to set up the stripe form in a different language than English, but only for a few other languages Stripe supports. For a custom integration, you will have to pass locale: 'auto' when calling StripeCheckout.configure() so the language will be detected automatically. There’s more info in the docs.
However, since Norwegian isn't supported yet, what I am suggesting is mapping the response codes and providing your own translations for the errors.
var errorMessages = {
incorrect_number: "The card number is incorrect.",
....
};
You can find a complete list with all error codes here
I'm using Stripe to handle payments on my website. But, when I try to make a payment I'm getting a 'The users credit card failed' error. I've used this code on different sites and they work but, for some reason it isn't working here. Does anyone know what the problem might be? There definitely is money on the card:
function stripeResponseHandler(status, response)
{
if (response.error)
{
// Stripe.js failed to generate a token. The error message will explain why.
// Usually, it's because the customer mistyped their card info.
// You should customize this to present the message in a pretty manner:
alert(response.error.message);
}
else
{
// Stripe.js generated a token successfully. We're ready to charge the card!
var token = response.id;
var email = $("#email").val();
var price = $("#price").val();
var id = $("id").val();
// Make the call to the server-script to process the order.
// Pass the token and non-sensitive form information.
var request = $.ajax ({
type: "POST",
url: "pay.php",
dataType: "json",
data: {
"stripeToken" : token,
"email" : email,
"price" : price,
"id" : id
}
});
request.done(function(msg)
{
if (msg.result === 0)
{
// Customize this section to present a success message and display whatever
// should be displayed to the user.
window.location.replace("http://foo.com");
}
else
{
// The card was NOT charged successfully, but we interfaced with Stripe
// just fine. There's likely an issue with the user's credit card.
// Customize this section to present an error explanation
alert("The user's credit card failed.");
}
});
request.fail(function(jqXHR, textStatus)
{
// We failed to make the AJAX call to pay.php. Something's wrong on our end.
// This should not normally happen, but we need to handle it if it does.
alert("error");
});
}
}
function showErrorDialogWithMessage(message)
{
// For the tutorial, we'll just do an alert. You should customize this function to
// present "pretty" error messages on your page.
alert(message);
// Re-enable the order button so the user can try again
$('#buy-submit-button').removeAttr("disabled");
}
$(document).ready(function()
{
$('#buy-form').submit(function(event)
{
// immediately disable the submit button to prevent double submits
$('#buy-submit-button').attr("disabled", "disabled");
var fName = $('#first-name').val();
var lName = $('#last-name').val();
var email = $('#email').val();
var cardNumber = $('#card-number').val();
var cardCVC = $('#card-security-code').val();
// First and last name fields: make sure they're not blank
if (fName === "") {
showErrorDialogWithMessage("Please enter your first name.");
return;
}
if (lName === "") {
showErrorDialogWithMessage("Please enter your last name.");
return;
}
// Validate the email address:
var emailFilter = /^([a-zA-Z0-9_\.\-])+\#(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
if (email === "") {
showErrorDialogWithMessage("Please enter your email address.");
return;
} else if (!emailFilter.test(email)) {
showErrorDialogWithMessage("Your email address is not valid.");
return;
}
// Stripe will validate the card number and CVC for us, so just make sure they're not blank
if (cardNumber === "") {
showErrorDialogWithMessage("Please enter your card number.");
return;
}
if (cardCVC === "") {
showErrorDialogWithMessage("Please enter your card security code.");
return;
}
Stripe.createToken({
number: cardNumber,
cvc: cardCVC,
exp_month: $('#expiration-month').val(),
exp_year: $('#expiration-year').val()
}, stripeResponseHandler);
// Prevent the default submit action on the form
return false;
});
});
Thanks in advance