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
Related
I am trying to write a JS function which blocks users from submitting a personal email. Here is the code. When I remove the "alert" line, the user is blocked from a successful form submission. But there is no alert that prompts them to enter a business email.
$("form").submit(function(){
// Get the email value from the input with an id="Email-2"
var email_addr = $('#Email-2').val();
// The regex to check it against
var re = '[a-zA-Z_\\.-]+#((hotmail)|(yahoo)|(gmail))\\.[a-z]{2,4}';
// Check if the email matches
if(email_addr.match(re)){
// Email is on the filter list
// Return false and don't submit the form, or do whatever
window.alert("Enter Business Email");
return false;
} else {
// Email ok
// Allow the form to be submitted
return true;
}});
Below is where there error is occuring. I'm new to Javascript so it very likely could be a syntax issue.
window.alert("Enter Business Email");
return false;
I found a solution that worked, changed the code to the following:
$('#wf-form-Book-Demo-Form').submit(function(){
var email = $('#Email-2').val();
var reg = /^([\w-\.]+#(?!gmail.com)(?!yahoo.com)(?!hotmail.com)(?!yahoo.co.in)(?!aol.com)(?!abc.com)(?!xyz.com)(?!pqr.com)(?!rediffmail.com)(?!live.com)(?!outlook.com)(?!me.com)(?!msn.com)(?!ymail.com)([\w-]+\.)+[\w-]{2,4})?$/;
if (reg.test(email)){
return 0;
}
else{
alert('Please Enter Business Email Address');
return false;
}
});
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.
The javascript is supposed to handle form submission. However, even if called with
script src="js/registerform.js"> Uncaught ReferenceError: sendreg is not defined .
The function is called onclick. Can be reproduced on www.r4ge.ro while trying to register as well as live edited. Tried jshint.com but no clue.
I will edit with any snips required.
function sendreg() {
var nameie = $("#fname").val();
var passwordie = $("#fpass").val();
var emailie = $("#fmail").val();
if (nameie == '' || passwordie == '' || emailie == '') {
alert("Please fill all the forms before submitting!");
} else {
// Returns successful data submission message when the entered information is stored in database.
$.post("http://r4ge.ro/php/register.php", {
numeleluii: nameie,
pass: passwordie,
mail: emailie
}, function(data) {
alert(data);
$('#form')[0].reset(); // To reset form fields
setTimeout(fillhome, 1000);
});
}
}
function sendpass() {
var oldpassw = $("#oldpass").val();
var newpassw = $("#newpass").val();
if (oldpassw == '' || newpassw == '') {
alert("Please fill all the forms before submitting!");
} else {
// Returns successful data submission message when the entered information is stored in database.
$.post("http://r4ge.ro/php/security.php", {
xoldpass: oldpassw,
xnewpass: newpassw
}, function(data2) {
alert(data2);
$('#passform')[0].reset(); // To reset form fields
});
}
}
function sendmail()
{
var curpass = $("#curpass").val();
var newmail = $("#newmail").val();
if (curpass == '' || newmail == '')
{
alert("Please fill all the forms before submitting!");
}
else
{
// Returns successful data submission message when the entered information is stored in database.
$.post("http://r4ge.ro/php/security.php", {
curpass: curpass,
newmail: newmail
}, function(data3) {
alert(data3);
$('#mailform')[0].reset(); // To reset form fields
});
}
}
I'm guessing here but... I imagine you are doing something like
...<button onclick="sendreg">...
And you have your <script> in the bottom on the code. Just put them on top or use $("#mybtn").click(sendreg)
Try using $("#mybtn").click(sendreg) instead of inline onclick.
The script wasn't called in the html. sorry for wasting time. A simple
<script src="js/registerform.js"></script> Fixed it.
There is no syntax error there, and I don't see any such error when trying the page.
The error that you get is that you can't make a cross domain call. Do the request to the same domain:
$.post("http://www.r4ge.ro/php/register.php", {
or:
$.post("/php/register.php", {
I have been programming a registration form with ajax validation. The way I have it set up is in my js file, I have listeners that fire when the content of the field is changed. They send the data to the server, and the server makes sure it's valid and sends back its response in the form of a JSON object. I then read the values of the JSON object to output potential error messages.
I won't copy and paste the entire files, just one example:
$(document).ready(function() {
// USERNAME VALIDATION LISTENER
$("#regUsername").change(checkName);
}
and then the checkName function looks like this, it sends my ajax request:
function checkName() {
$.ajax({
type: "POST",
url: "./ajax_register.php",
data: {
request: "nameAvail",
username: $("#regUsername").val()
},
success: function(data) { // execute on success
var json = jQuery.parseJSON(data);
if (json.success) { // if usernames do match
$("#usernameAvailiability").removeClass().addClass('match');
$("#usernameAvailiability").text(json.msg);
} else { // if the user has failed to match names
$("#usernameAvailiability").removeClass().addClass('nomatch');
$("#usernameAvailiability").text(json.msg);
}
}
});
}
And depending on the response, it updates a span that tells the user if the input they wrote is valid or not.
The server validates with this part of the php file:
if(!isset($_POST['request'])) { // do nothing if no request was provided
print("no request provided");
} else { //ELSE request has been provided
if ($_POST['request'] == "nameAvail") { // if the request is to check if the username is valid
$response = array("success" => false, "msg" => " ", "request" => "nameAvail");
// CHECK USER NAME AVAILIABILITY CODE
if (!isset($_POST['username']) || empty($_POST['username'])) { // if no username is entered
$response['success'] = false;
$response['msg'] = "No username provided";
} else { // if a username has been entered
$username = $dbConn->real_escape_string($_POST['username']);
if (!ctype_alnum($username)) { // Make sure it's alpha/numeric
$response['success'] = false;
$response['msg'] = "username may only contain alpha numeric characters";
} elseif (strlen($username) < 4) { // make sure it's greater than 3 characters
$response['success'] = false;
$response['msg'] = "username must be at least 4 characters long.";
} elseif (strlen($username) > 20) { // make sure it's less than 26 characters
$response['success'] = false;
$response['msg'] = "username can be up to 20 characters long.";
} else { // make sure it's not already in use
$query = $dbConn->query("SELECT `id`, `username` FROM `users` WHERE `username` = '"
. $username . "' LIMIT 1");
if ($query->num_rows) { // if the query returned a row, the username is taken
$response['success'] = false;
$response['msg'] = "That username is already taken.";
} else { // No one has that username!
$response['success'] = true;
$response['msg'] = "That username is availiable!";
}
}
}
print(json_encode($response));
}
What I'd like to do now is create a function in my javascript for the register button. But I need to make sure all the forms are validated first.
I'm not sure what my options are. What I'd LIKE to do is somehow be able to recycle the code I've already written in my PHP file. I don't want to write out an entirely new if($_POST['request'] == "register") clause and then copy and paste all the validation code to make sure the input is valid before I insert the registrant's data into the database. It seems really repetitive!
I know I could check to see if all the spans on the page were set to 'match', but that could easily be tampered with and blank forms could be submitted.
so far, my register button function looks like this:
function register() {
if ( NEED SOME KIND OF CLAUSE HERE TO CHECK IF ALL THE FIELDS ARE VALID) {
$.ajax({
type: "POST",
url: "./ajax_register.php",
data: {
request: "register",
username: $("#regUsername").val(),
password: $("#regPassword").val(),
email: $("#email").val(),
dob: $("#dob").val(),
sQuest: $("#securityQuestion").val(),
sAns: $("#securityAnswer").val(),
ref: $("#referred").val()
}, success: function(data) {
var json = jQuery.parseJSON(data);
console.log(json);
$("#regValid").removeClass();
$("#regValid").text("");
}
}); //AJAX req done
} else {
$("#regValid").removeClass().addClass('nomatch');
$("#regValid").text("One or more fields are not entered correctly");
}
return false;// so that it wont submit form / refresh page
}
I would really appreciate some help, I've spent the last few hours scouring StackOverflow for an answer, but I can't seem to get anything to work. Will I have to duplicate code in my PHP file or is there a more elegant way to handle this?