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
}
}
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 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.
In the following code, I have a problem where Stripe is not processing the payment. I'm getting all the values from the form correctly, however in the stripeResponseHandler function nothing is logging. I'm using the test credit cards available on their website and I successfully used it a couple of times prior to this error.
I loaded the https://js.stripe.com/v2/stripe-debug.js into my javascript and it was logging in the chrome console that "It looks like Stripe.js was loaded more than one time. Please only load it once per page.", however I only setPublishableKey here within this JS file and load
Stripe.setPublishableKey('pk_test_TK18ZwUnK2CT1Wmof8WsQl8S');
var payMeal = function(){
console.log("inside the paymeals function");
var x = document.getElementsByClassName("form-payment");
console.log("Number is " + x[0].value)
console.log("CVC is " + x[1].value)
console.log("Exp_Month is " + x[2].value)
console.log("Exp_Year is " + x[3].value)
console.log("The Stripe Object is",Stripe)
Stripe.card.createToken({
number: x[0].value,
cvc: x[1].value,
exp_month: x[2].value,
exp_year: x[3].value
}, stripeResponseHandler)
window.location.href = "../../meals"
};
var stripeResponseHandler = function(status, response){
console.log("IM IN THE RESPONSE HANDLER!!!!+++++***")
if(response.error){
console.log("THERE IS AN ERROR!!***")
console.log(response);
}
else{
console.log("submitting ajax to server with token");
token = response.id;
ajaxToServer(token);
}
}
I am working on a card processing API with ASP.NET , HTML , AngularJS and Stripe.NET. I am pretty new to all of them.
I followed the documentation on the Stripe website for sending the Stripe token to the server (here): https://stripe.com/docs/stripe.js#card-validateCardNumber
It worked! However, instead of JQuery I want to use AngularJS. I want to convert from JQuery to AngularJS this part of the JQuery code:
Stripe.card.createToken({
number: $('.card-number').val(),
cvc: $('.card-cvc').val(),
exp_month: $('.card-expiry-month').val(),
exp_year: $('.card-expiry-year').val(),
address_zip: $('.address_zip').val()
}, stripeResponseHandler);
function stripeResponseHandler(status, response) {
// 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('button').prop('disabled', false); // Re-enable submission
} else { // Token was created!
// Get the token ID:
var token = response.id;
// Insert the token 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();
}
}
If someone can help, I will appreciate it a lot. Thanks. :)
I was able to answer my question (a while ago, just finding some time to answer it in here).
Firstly, here are the tips:
Use "angular-payments.js". You can find it here: https://github.com/laurihy/angular-payments
You have to use the html syntax for the card details as in the documentation of the repository.
It is not the same as in the Stripe documentation. I have used AngularJS service so that I can pass my token to my ASP.NET application.
Thirdly, I had problems with the verification token - here is a nice post for how to handle it: http://blog.novanet.no/anti-forgery-tokens-using-mvc-web-api-and-angularjs/
Here is (part of) my (AngularJS) code:
(function () {
var app = angular.module("myApp", ["angularPayments"]);
app.service('Service', function ($http) {
this.AddCard = function (stripeToken, stripeEmail) {
var tokenData = {
"stripeToken": stripeToken,
"stripeEmail": stripeEmail
};
$http.post("http://localhost:48484/payment/card", tokenData).success(function (response) {
window.location = '/cardprocess/confirmation';
})
};
});
app.directive('ncgRequestVerificationToken', ['$http', function ($http) {
return function (scope, element, attrs) {
$http.defaults.headers.common['RequestVerificationToken'] = attrs.ncgRequestVerificationToken || "no request verification token";
};
}]);
app.controller("myCtrl", ['$scope', myCtrl]);
app.controller("buyCtrl", function ($scope, CardService) {
$scope.submit = function () {
$scope.processing = true;
}
$scope.stripeFormSubmit = function (code, result) {
$scope.processing = false;
$scope.hideAlerts();
if (result.error) {
$scope.stripeError = result.error.message;
} else {
//$scope.stripeToken = result.id;
$scope.stripeToken = result.id;
CardService.AddCard($scope.stripeToken, $scope.stripeEmail);
}
};
$scope.hideAlerts = function () {
$scope.stripeError = null;
$scope.stripeToken = null;
};
});
}());
(The html page is quite big so I decided not to put in here. It should be straight forward - I have a form, which calls AngularJS model "stripeFormSubmit".)
Finally, you can see the "CardService", which is talking to my api - the service is initialised at the begining of the paste code.
That is the main idea. I decided not to go in a lot of detail. But I will try to answer questions (if any).
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