Trouble creating Stripe Token: 402 (Payment Required) error - javascript

Good day everyone,
Below is the error code that is thrown in console:
(index):3 POST https://api.stripe.com/v1/tokens 402 (Payment Required)
(index):3 POST https://api.stripe.com/v1/tokens 402 (Payment Required)c # (index):3e # (index):3a # (index):3Stripe.isDoubleLoaded.Stripe.xhr # (index):3Stripe.a._rawRequest # (index):2Stripe.a.request # (index):2Stripe.token.a.create # (index):2Stripe.card.b.createToken # (index):2Stripe.a._channelListener # (index):2incoming # (index):2f # (index):2
Below is the javascript code
// Generate the user token
$(function() {
// Once the user has submited the form
$(".submit").click(function(e) {
// Prevent the form from submiting by default
e.preventDefault();
// Ensure that checkbox is checked
if($('#checkbox').is(":checked")) {
// Prevent the form from submiting by default
var $form = $('#payment-form');
// Request a token from Stripe:
Stripe.card.createToken($form, stripeResponseHandler);
// Prevent the form from being submitted:
return false;
}
else {
// Display an error message to the user by writting directly into the header error tag
document.getElementById('checkboxError').innerHTML = "You must kindly accept the terms and conditions to continue.";
}
});
// Ensure that checkbox is checked
if($('#checkbox').is(":checked")) {
var appendedStripeToken = false;
function stripeResponseHandler(status, response) {
// Grab the form:
var $form = $('#payment-form');
if (response.error) { // Problem!
// Scroll to the billing section
$("#billingError").scrollTop();
// 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;
handleCall(token);
}
// What to do after the token has been generated.
function handleCall(token) {
var $form = $('#payment-form');
if (!appendedStripeToken) {
// Insert the token into the form so it gets submitted to the server
appendedStripeToken = true;
phpCall();
}
}
// Post the package name, the token, and the user name information to the billing.php page
function phpCall() {
if( appendedStripeToken === true ){
$.ajax({
type: "POST",
data: {run: true, packageName: $('#packageName').val(), token: token, userName: $('#userName').val(),customerName: $('#customerName').val() },
url: '/app/functions/billing.php',
success: function (response) {//response is value returned from php (for your example it's "bye bye"
$('#payment-form').prop('disabled', true); // TODO: give your html-submit-input-tag an "id" attribute
window.location = response;
}
});
}
}
}
}
});
Below is the HTML code
<!-- Package name to be submitted to server -->
<input type="hidden" id="packageName" value="{{ packageName|capitalize }}">
<!-- Username to be submitted to server -->
<input type="hidden" id="userName" value="{{ userName }}">
<input type="hidden" id="customerName" value="{{ customerName }}">
<div class="form-row">
<label for="cardHolder">Cardholder Name</label><br>
<input type="text" id="cardHolder" size="20" data-stripe="name">
</label>
</div>
<br><br>
<div class="form-row">
<label for="cardNumber">Card Number </label><br>
<input type="text" id="cardNumber" size="20" data-stripe="number">
</label>
</div>
<br>
<img src="/public/images/credit-card/visa.png" class="card-visa">
<img src="/public/images/credit-card/mastercard.png" class="card-mastercard">
<img src="/public/images/credit-card/american-express.png" class="card-aexpress">
<br>
<div class="form-row">
<label for="cardExpiration"> Expiration (MM/YY)</label><br>
<input class="expirationNumber" type="text" size="2" id="cardExpiration" data-stripe="exp_month">
</label>
<span> / </span>
<input class="expirationNumber" type="text" size="2" data-stripe="exp_year">
</div>
<br><br>
<div class="form-row">
<label for="cardCVC">CVC</label><br>
<input type="text" id="cardCVC" size="4" data-stripe="cvc">
</label>
</div>
</div>
</div>
<input type="checkbox" id="checkbox">
<label for="checkbox">By purchasing this package you are agreeing to our Terms & Conditions</label><br><br>
<h4 id="checkboxError"></h4>
<button type="submit" class="submit btn-tangerine">Submit Payment</button>
</form>
Any help would be greatly appreciated!
I thnk that the main error lies in the following line:
Stripe.card.createToken($form, stripeResponseHandler);
What is suppose to happen is really simple. Token gets created when all proper information are given, and then the token along with other information are posted via ajax to the server where a PHP code will create the charge using these information.

I was facing same issue when I add test API KEYS for payment, then site was working fine and when I add live key then site shows same error on console.
But problem was, I was testing live key with test credit card number. May be you were doing same mistake
And sorry for bad English.

Related

How to submit form and have data stay in input field? Using AJAX and nodejs

I am trying to create a user settings page where a user inputs his/her information, clicks "save", then the page saves the data without clearing the inputted fields or reloading the page. The best example I can think of is the user account settings page on Udemy.
A LOT of the similar questions I've looked at are using php or renders data in a div below the form. I want the data to remain IN the form inputs. I'm using nodejs, express, bodyparser.
<form id="updateAccSettings" action="/account" method="POST">
<div class="form-group">
<label for="address">Address* </label>
<input class="form-control" type="text" name="address" placeholder="Address" required/>
</div>
<div class="form-group">
<label for="address2">Address 2 </label>
<input class="form-control" type="text" name="address2" placeholder=""/>
</div>
<div class="form-group">
<label for="city">City* </label>
<input class="form-control" type="text" name="city" placeholder="City" />
</div>
<div class="form-group">
<input type="submit" name="save" class="btn btn-lg btn-primary btn-block" value="Save"/>
</div>
</form>
I've tried this with AJAX
$(document).ready(function() {
$("#updateAccSettings").on("submit", function(e){
e.preventDefault();
var details = $("#updateAccSettings").serialize();
$.post("/account", details, function(data){
$("#updateAccSettings").html(data);
});
});
});
and this
$(document).ready(function () {
$("#updateAccSettings").bind("submit", function(e){
e.preventDefault();
$.ajax({
type: "POST",
url: "/account",
data: $("#updateAccSettings").serialize(),
success: function(){
alert("You've successfully updated your account settings.")
}
});
});
});
And I have this for my app.js
app.post("/account", function(req, res) {
var address = req.body.address;
var address2 = req.body.address2;
var city = req.body.city;
var updateAccount = {address: address, address2: address2, city: city};
account.push(updateAccount);
console.log("Updated data");
res.redirect("/settings/account");
});
When I clicked save, I get a Cannot read property of 'push' undefined. I tried deleting the var address, var address2, etc and keeping only the console.log which logs whenever I click save but doesn't keep the data in the input. I tried adding onsubmit="return false" as an attribute on the form tag but the console.log doesn't run when I click save so I assume it's not doing anything with the data.
Not sure how to proceed from here. All my other forms use modals or render results in another page.
You're getting the error because you're trying to push onto an undefined variable. Namely in the last section when posted this app.post:
app.post("/account", function(req, res) {
var address = req.body.address;
var address2 = req.body.address2;
var city = req.body.city;
var updateAccount = {address: address, address2: address2, city: city};
account.push(updateAccount); // error is being thrown here
console.log("Updated data");
res.redirect("/settings/account");
});
Once you have a dummy variable for account, you can send back to the frontend a json response to be read in the form success handler.
Example code: (I haven't tested it)
Backend:
app.post("/account", function(req, res) {
var account = [];
var address = req.body.address;
var address2 = req.body.address2;
var city = req.body.city;
var updateAccount = { address, address2, city };
account.push(updateAccount); // error is being thrown here
console.log("Updated data");
res.json(updateAccount);
});
Frontend:
$(document).ready(function () {
$("#updateAccSettings").bind("submit", function(e){
e.preventDefault();
$.ajax({
type: "POST",
url: "/account",
data: $("#updateAccSettings").serialize(),
success: function(data){
$('#address').value(data.address);
$('#address2').value(data.address2);
$('#city').value(data.city);
}
});
});
});
You could give each of your form input fields an id (e.g the same as their "name" property)and get their values individually when doing the ajax request as follows (that way you can reinsert the values after the form is submitted):
HTML
<form id="updateAccSettings" action="" method="POST">
<div class="form-group">
<label for="address">Address* </label>
<input class="form-control" type="text" name="address" id="address" placeholder="Address" required/>
</div>
<div class="form-group">
<label for="address2">Address 2 </label>
<input class="form-control" type="text" name="address2" id="address2" placeholder=""/>
</div>
<div class="form-group">
<label for="city">City* </label>
<input class="form-control" type="text" name="city" id="city" placeholder="City" />
</div>
<div class="form-group">
<input type="submit" name="save" class="btn btn-lg btn-primary btn-block" value="Save"/>
</div>
</form>
JQuery
$(document).ready(function() {
$("#updateAccSettings").on("submit", function(e){
e.preventDefault();
//get the values of our input fields and store them in local variables
var address = $("#address").val();
var address2 = $("#address2").val();
var city = $("#city").val();
//prepare the data object to send in the ajax request
var params = {"address": address, "address2": address2, "city" : city};
$.ajax({
type: "POST",
url: "/account",
data: JSON.stringify(params),
dataType: "json",
success: function(data){
//the ajax request was successful
//We can do something with the data we get back here.
//Also we can reinsert the values (that were submitted) to the form
$("#address").val(address);
$("#address2").val(address2);
$("#city").val(city);
},
error: function(xhr, status, error) {
//an error occured in the request so handle it here
}
});
});
});

Parsing problems during JSON response using AngularJS

I am new using Angularjs and I am having an issue parsing a JSON response. I have login credentials like Username and password and I am trying to parse it , when user clicks on the login button(). If the name and password matched in the following server , I should get success message. This is the HTML code I am using:
<form ng-submit="loginform()" name="logform"><br/><br>
<tr ng-repeat="logcred in signinfo"></tr>
<div>
<label form="emailinput"><b>Email</b></label>
<input type="email" class="form-control" name="uname" id="emailinput" placeholder="you#example.com" ng-model="logcred.username" >
</div>
<div>
<label form="pwdinput"><b>Password</b></label>
<input type="password" class="form-control" name="pwd" id="pwdinput" placeholder="*******" ng-model="logcred.password">
</div>
<a ng-click="reloadPage()" class="navbar-brand" ></a>
<div>
<button type="cancel" class="btn" ng-click="toggle_cancel()">Cancel</button>
<button class="btn btn-primary" ng-click="submit()" >Login</button>
</div>
</form>
This is the Javascript code using AngularJS:
app.controller('credientials', function($scope,$http) {
$scope.loginform = function (username, password){
$http.get('http://localhost:3000/loginfo')
.then(
function successCallback(data){
$scope.response = data;
if($scope.username === 'response.username' && $scope.password === 'response.password'){
$scope.signinfo = data.loginfo;
}
else{
console.log("Error");
}
})
});
The HTML is showing the variable $scope.response with the JSON returned by the server, but I don't know how to authentication it properly.
What am I doing wrong?
Any help / advice would be greatly appreciated.
EDIT
Check updated snippet of authentication at client side.
if(userData.username == response.data.username && userData.password === response.data.password){
$scope.signinfo = response.data
}
You will get userData variable from form submit button .. see how i am passing
username and pasword to controller using ng-submit="loginform(logcred)"
var myApp = angular.module('myApp', []);
myApp.controller('credientials', function($scope, $http) {
$scope.loginform = function(userData) {
console.log(userData);
$http.post('https://reqres.in/api/users', userData) // here in post rew i am passing username and password to mock api
.then(function(response) {
//as suggested by you in response u will get username = admin#evol.com password = admin;
console.log(response)
if(userData.username == response.data.username && userData.password === response.data.password){
$scope.signinfo = response.data
}
});
}
});
//**NOTE** in above HTTP call you use your url `http://localhost:3000/loginfo` and in your serverside get the username from the request and check password for that username in your database. If password matches with what you have entered then send success message or user details back to client side.
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.0/angular.min.js"></script>
<div ng-app="myApp" ng-controller="credientials">
<form ng-submit="loginform(logcred)" name="logform">
<br/>
<br>
{{signinfo}}
<div>
<label form="emailinput"><b>Email</b></label>
<input type="email" class="form-control" name="uname" id="emailinput" placeholder="you#example.com" ng-model="logcred.username">
</div>
<div>
<label form="pwdinput"><b>Password</b></label>
<input type="password" class="form-control" name="pwd" id="pwdinput" placeholder="*******" ng-model="logcred.password">
</div>
<a ng-click="reloadPage()" class="navbar-brand"></a>
<div>
<button type="cancel" class="btn" ng-click="toggle_cancel()">Cancel</button>
<button class="btn btn-primary">Login</button>
</div>
</form>
</div>
in above HTTP call you use your url http://localhost:3000/loginfo and in your serverside get the username from the request and check password for that username in your database. If password matches with what you have entered then send success message or user details back to client side.
where should i apply if condition, to match the usercredentials?
You need to check if condition in the server side logic where u fetch data from database. like in your server (i.e. in /loginfo)
if(userpassword == passwordfromDB){
//send success message to client side
}

angular payments returns invalid card with test data

I'm trying to congifure stripe in angular js using the angular-payments app found here
https://github.com/laurihy/angular-payments
the problem is that it seems to be returning invalid_card errors even with the test data.
Here is the error:
POST https://api.stripe.com/v1/tokens 402 (Payment Required)
Stripe.isDoubleLoaded.c(index):3 Stripe.isDoubleLoaded.e(index):3 Stripe.isDoubleLoaded.a(index):3 Stripe.isDoubleLoaded.Stripe.xhr(index):2 Stripe.a._rawRequest(index):2 Stripe.a.request(index):2 Stripe.token.a.create(index):2 Stripe.card.b.createToken(index):2 Stripe.a._channelListener(index):2 Stripe.isDoubleLoaded.H.Socket.t.concat.incoming(index):2
I'm setting my publishable key and including Stripe.js without a problem, and I know that the call is completed, as I'm picking up the error in the ResponsHandler
any thoughts what may be causing this?
here is the code:
form
<form name="myform" id="signup-form" stripe-handler="saveCustomer">
<div class="form-group">
<label for="card_number">Card Number</label>
<input type="text" class="form-control" size="20" ng-model="number" payments-validate="card" payments-format="card" payments-type-model="type" ng-class="myform.number.$card.type"/>
</div>
<div class="form-row">
<label for="CVC"> CVC</label>
<input type="text" class="form-control" size="4" ng-model="cvc" payments-validate="cvc" payments-format="cvc" payments-type-model="type"/>
</div>
<div class="form-row">
<label for="expiry"> Expiry</label>
<input type="text" class="form-control" size="2" ng-model="expiry" payments-validate="expiry" payments-format="expiry" />
</div>
<div class="text-center">
<span class="glyphicon glyphicon-heart"></span>
<h3>Thanks For Your Money!</h3>
<button type="submit" class="btn">Submit</button>
</div>
here is the contoller function:
// function to process the form
$scope.saveCustomer = function(status, response) {
if (response.error) {
// Show the errors on the form
console.log(response);
console.log(response.error);
} else {
// response contains id and card, which contains additional card details
var token = response.id;
console.log(token);
formData.token = token;
}
}
and my index.html header includes...
<script type="text/javascript" src="https://js.stripe.com/v2/"></script>
<script type="text/javascript">
// This identifies your website in the createToken call below
Stripe.setPublishableKey('my-key-here');
// ...
</script>
The wierd thing is that it was working with stripe-angluar which is another repo for processing stripe - any ideas what am i doing wrong?
You might be creating the token incorrectly. I was having the same problem. What worked for me was setting the card like this:
Stripe.card.createToken({
"number": '4242424242424242',
"exp_month": 12,
"exp_year": 2016,
"cvc": '123'
}, function(status, response) {
stripeResponseHandler(status, response);
});
Instead of this (notice how the card object is created twice - thus the "Stripe.isDoubleLoaded" error, I believe ):
Stripe.card.createToken({
card: {
"number": '4242424242424242',
"exp_month": 12,
"exp_year": 2016,
"cvc": '123'
}
}, function(status, response) {
stripeResponseHandler
});

Validate form, check if user exists, register them. All with Ajax

My javascript is inside an html file called register.html.
The user submits the form. This should then trigger the $('input[name="createacc"]').click(function (e) AJAX then sends those 4 variables to checkuser.php. Checkuser.php should then check to see if the username exists. If it does exist, it should echo 0. If it does not exists, it should echo 1. Register.html then checks to see what checkuser.php echoed. If the echo was "0" then, then an alert box should appear saying username unavailable. If the echo was "1" or anything else, register.html should run $("#registerform").submit(); which then does the php script. This should all happen without leaving the register.html page.
I check chrome's built in debugger and I see that if the account exists checkuser.php writes back 0 and if the account doesn't it writes back 1. But for some reason nothing else happens. The account does not register nor do I get an alert box saying the username is unavailable
here is my register.html
<form ata-parsley-validate name="registerform" id="registerform" action="register.php" method="post">
<p>
<label for="firstname">First Name:</label>
<input name="firstname" id="firstname" maxlength="32" type="text" placeholder="Optional" />
</p>
<p>
<label for="username" id="usernameText">Username:</label>
<input data-parsley-pattern="^[A-Za-z0-9_]{3,15}$" data-parsley-length="[3, 15]" name="username" id="username" maxlength="32" type="text" data-parsley-error-message="Username needs to be between 3 and 15 characters. Case sensitive. No special characters allowed." required/>
</p>
<p>
<label for="password1">Password:</label>
<input name="password1" id="password1" data-parsley-pattern="^[A-Za-z0-9_-]{5,25}$" data-parsley-length="[5, 25]" type="password" data-parsley-equalto="#password2" data-parsley-error-message="Passwords must match. Needs to be between 5 and 25 characters. Case sensitive. No special characters allowed." required/>
</p>
<p>
<label for="password2">Confirm Your Password:</label>
<input name="password2" id="password2" data-parsley-length="[5, 25]" data-parsley-error-message="Passwords must match. Needs to be between 5 and 25 characters. Case sensitive. No special characters allowed." data-parsley-pattern="^[A-Za-z0-9_-]{5,25}$" type="password" data-parsley-equalto="#password1" required/>
</p>
<p>
<label for="email">E-Mail:</label>
<input data-parsley-trigger="change" name="email" id="email" maxlength="1024" type="email" required/>
</p>
<p>
<input type="submit" id="submit" class="submit" name="createacc" value="Register" />
</p>
</form>
Here is my javascript
<script>
$(document).ready(function () {
$('input[name="createacc"]').click(function (e) {
var username = $('input[name="username"]').val();
var firstname = $('input[name="firstname"]').val();
var password1 = $('input[name="password1"]').val();
var email = $('input[name="email"]').val();
e.preventDefault();
$.ajax({
type: 'POST',
data: {
username: username,
firstname: firstname,
password1: password1,
email: email
},
url: 'checkuser.php',
success: function (data) { //Receives the data from the php code
if (data === "0") {
alert("Username Unavailable");
} else {
$("#registerform").submit();
alert("Account successfuly created");
}
},
error: function (xhr, err) {
console.log("readyState: " + xhr.readyState + "\nstatus: " + xhr.status);
console.log("responseText: " + xhr.responseText);
}
});
});
});
</script>
Update - I have fixed parts of my code through the help of others below me. My only issue now is that $("#registerform").submit(); doesn't do anything
You are trying to return and JSON not setting
header('Content-type: application/json');
Decide whether you want to pass plaintext or json. Your string might be now "0", not 0
Try
if (data === '"0"') {
I think the problem is in your success.you have written If it does exist, it should echo 0. If it does not exists, it should echo 1.you should use:
success: function (data) { //Receives the data from the php code
if (data == '"0"') { //register if user exists.
$("#registerform").submit();
} else {
alert("Username Unavailable");
}

Sending form data to Parse.com

I have a form that I created and I want to send that form information to a backend database called Parse.com. I create the table in Parse with the same names as the fields on the form, but I'm not sure how to send it to Parse using js.
<form id="contact-form" class="contact-form" method="post" action="" onSubmit="return checkMail()" name="validation">
<div class="form-group row" id="price">
<div class="col-lg-4">
<input type="text" name="fname" class="form-control" id="name" placeholder="First *" required >
</div>
<div class="col-lg-4">
<input type="text" name="lname" class="form-control" id="name" placeholder="Last *" required>
</div>
<div class="col-lg-4">
<input type="text" name="email" class="form-control" id="name" placeholder="E-mail *" required>
</div>
</div>
</div>
<div class="form-group row" align="center">
<div class="col-lg-12" align="center">
<button type="submit" class="button default">SEND <i class="glyphicon glyphicon-send"></i></button>
</div>
</div>
Attach your parse object save function to the form submit. This can be achieved with ease by using JQuery.
Next you have to capture the form input data, then save it to your Parse object.
This script assumes you have created a class in parse with the [string] columns of fname, lname and email.
<script>
Parse.initialize("API KEY", "JAVASCRIPT KEY");
var ParseObj = Parse.Object.extend('myClass'); //create local parse object from your Parse class
$('#contact-form').submit(function(e) {
//on form submit
e.preventDefault();
//get data from form
var data = {
fname: $("#fname").val(),
lname: $("#lname").val(),
email: $("#email").val()
};
//create new Parse object
parseObj = new ParseObj();
//match the key values from the form, to your parse class, then save it
parseObj.save(data, {
//if successful
success: function(parseObj) {
alert(parseObj.get('fname') + " " + parseObj.get('lname') + " " + parseObj.get('email') + " saved to Parse.")
}
,
error: function(parseObj, error) {
console.log(parseObj);
console.log(error);
}
}
);
});
</script>
This is a typical "too broad" question, as you're not really having a specific problem but just asking us to write the code for you. Best I can do is point you to the parse.com user guide which shows you how you can do this. Check it out, try it for yourself and then ask here again if you have specific issues with the code.
Example snipped from the user guide found here: https://parse.com/docs/js_guide#objects-saving
var GameScore = Parse.Object.extend("GameScore");
var gameScore = new GameScore();
gameScore.set("score", 1337);
gameScore.set("playerName", "Sean Plott");
gameScore.set("cheatMode", false);
gameScore.save(null, {
success: function(gameScore) {
// Execute any logic that should take place after the object is saved.
alert('New object created with objectId: ' + gameScore.id);
},
error: function(gameScore, error) {
// Execute any logic that should take place if the save fails.
// error is a Parse.Error with an error code and description.
alert('Failed to create new object, with error code: ' + error.description);
}
});

Categories

Resources