Make a Stripe payment with Jquery AJAX? (Javascript ONLY) - javascript

I am trying to make a custom payment form for Stripe, and I want to make the AJAX call to Stripe manually. (instead of a submit event)
However, first off I am pretty sure I am posting it to the wrong place. But I can't figure out what URL I'm supposed to make this post request to.
If I am using the right url. I am getting a 405 not allowed response. With no information on what is wrong with my request.
Here's what I got:
Stripe.setPublishableKey('pk_test_12345');
Stripe.card.createToken({
number: ccNum,
cvc: ccCVC,
exp_month: ccMonth,
exp_year: ccYear
}, stripeResponseHandler);
This part works fine, gives me a 200 OK status and I got a token back from the server.
function stripeResponseHandler(status, response) {
console.log('card status: ', status);
console.log('token: ', response.id);
$.ajax({
type: 'POST',
url: 'https://checkout.stripe.com/checkout.js',
headers: {
stripeToken: response.id
},
data: {
number: ccNum,
cvc: ccCVC,
exp_month: ccMonth,
exp_year: ccYear
},
success: (response) => {
console.log('successful payment: ', response);
},
error: (response) => {
console.log('error payment: ', response);
}
})
}
This however, gives me the 405 Not Allowed. It seems a bit weird to me that the endpoint would be a .js file. Which is why I am assuming I got the wrong URL.
Can anyone help me figure out how to make a manual post request for a Stripe payment?

Disclaimer: This works, but it is TERRIBLE practice. Don't use this for a real project. I needed it for a front-end only testing environment. As other users on this page has pointed out, you should be doing this on the backend!
I finally found some useful documentation at: https://stripe.com/docs/api#create_charge
As I suspected the URL I was using was wrong.
after getting the right URL, the following ajax call works:
Hope That helps someone else as well! As most answers, are PHP or other backend languages.
$.ajax({
type: 'POST',
url: 'https://api.stripe.com/v1/charges',
headers: {
Authorization: 'Bearer sk_test_YourSecretKeyHere'
},
data: {
amount: 3000,
currency: 'usd',
source: response.id,
description: "Charge for madison.garcia#example.com"
},
success: (response) => {
console.log('successful payment: ', response);
},
error: (response) => {
console.log('error payment: ', response);
}
})

EDIT: This is insecure (and outdated)! You shouldn't send your user's card information directly to your own server. Instead, you should directly send it to Stripe. There's an up-to-date (using intents, etc) example here
You need to POST to a PHP file in your $.ajax() function:
$.ajax({
type: 'POST',
url: './stripe-payment.php',
headers: {
stripeToken: response.id
},
data: {
number: ccNum,
cvc: ccCVC,
exp_month: ccMonth,
exp_year: ccYear
},
success: (response) => {
console.log('successful payment: ', response);
},
error: (response) => {
console.log('error payment: ', response);
}
})
Your PHP should have something like the Stripe PHP bindings require()d to use the Stripe payment API, and that PHP file should look something like this, from this SO question:
<?php
require_once('Stripe.php');
// Set your secret key: remember to change this to your live secret key in production
// See your keys here https://manage.stripe.com/account
Stripe::setApiKey("sk_test_APIKEYREDACTED");
// Get the credit card details submitted by the form
$token = json_decode($_POST['chargeData']);
$tokenid = $token['id'];
// Create the charge on Stripe's servers - this will charge the user's card
try {
$charge = Stripe_Charge::create(array(
"amount" => 2000, // amount in cents, again
"currency" => "usd",
"card" => $tokenid,
"description" => "payinguser#example.com")
);
echo 'success';
} catch(Stripe_CardError $e) {
// The card has been declined
echo $tokenid;
}
?>
Refer to that Github's README for more, as well as the Stripe documentation.

Related

PayPal Smart Button Orders API Ignoring notify_url in purchase_units object

We are sending an order using the PayPal Smart Button with their latest JS SDK (February 2019). We have set the notify_url in the purchase_units object in the createOrder function as specified in the Orders API Documentation.
The transaction is still taking the IPN url from the account rather than the one we have provided upon creating the transaction.
We have tried different keys as suggested on stackoverflow such as 'NOTIFYURL', 'NOTIFY_URL', 'notifyurl' and 'notify_url'. None of which worked.
We have tried to remove the IPN from the account settings but this was not possible (notify_url should always override this anyway according to documentation).
paypal.Buttons({
createOrder: function (data, actions) {
return actions.order.create({
intent: "CAPTURE",
purchase_units: [{
amount: {
value: '#Model.Total.ToString("F")',
},
NOTIFYURL: "#notifyUrl"
}]
});
},
onApprove: function (data, actions) {
return actions.order.capture().then(function (details) {
return fetch('/umbraco/surface/PayPalPayment/process', {
method: 'post',
redirect: 'follow',
body: JSON.stringify({
OrderID: data.orderID,
PayerID: data.payerID,
}),
headers: {
'content-type': 'application/json'
}
}).then(function (response) {
response.json().then(function (data) {
window.location.href = data.redirect;
})
});
}).catch(function (error) {
window.location.href = '/umbraco/surface/PaymentFailed/PaymentFailed/?error=' + error;
});
}
}).render('#paypal-button-container');
Note: variables are added via Razor Syntax, I have confirmed that these values are being set correctly in Fiddler. Post is below but the IPN Url has been redacted.
{"intent":"CAPTURE","purchase_units":[{"amount":{"value":"0.01","currency_code":"GBP"},"NOTIFYURL":"https://<REDACTED>/umbraco/surface/paypalipn/receive"}],"application_context":{}}
We should be seeing the notify URL being set but when checking the message ID in the IPN history it is trying to use the IPN url found on the account rather than the notify_url that was provided.
Notify URL is not used with the REST APIs. They don't use IPN. They use Webhooks. You will need to register webhooks in your PayPal app and setup a listener for those hooks accordingly.

CORS error when trying to post message

I have an AngularJS Application I am trying to post a message through. I am successfully able to log the user in, get the access token, and I have ensured I have my domain in the JavaScript Origins within Yammer.
Whenever I try to post a message, however, I get the following error:
The strange thing is when it does the preflight it seems OK but as the error states I can't figure out why it isn't coming back in the CORS header as I have it registered within the Yammer Client area.
Here is the code for posting:
$scope.YammerPost = function (Yammer) {
var _token = Yammer.access_token.token;
var config = {
headers: {
'Authorization': 'Bearer ' + _token
}
};
$http.post('https://api.yammer.com/api/v1/messages.json', { body: 'blah blah', group_id: XXXXXXX }, config);
}
I call that scope variable in the view via a button click.
Here is the logic I use to sign the user in:
function checkYammerLogin() {
$scope.Yammer = {};
yam.getLoginStatus(
function (response) {
if (response.authResponse) {
$scope.Yammer = response;
console.dir(response); //print user information to the console
}
else {
yam.platform.login(function (response) {
if (response.authResponse) {
$scope.Yammer = response;
console.dir(response);
}
});
}
}
);
}
I ended up finding the issue.
For some odd reason, every time I would try to use an $http post it would include an Auth token from AD (app using Azure AD for authentication).
I ended up using jQuery inside of my Angular scope function on the button click and it works as I can control the headers for the request.
$.ajax({
url: 'https://api.yammer.com/api/v1/messages.json',
type: 'post',
data: {
body: 'this is a test from jQuery using AngularJS',
group_id: <group_id>
},
headers: {
'Authorization': _token
},
dataType: 'json',
success: function (data) {
console.info(data);
}
});
Fixed the issue and I can now post.
If anyone sees any issues with this practice please let me know, still a little new to angular

Trouble creating a folder in Box.com using jQuery?

I am building a web app using the Box API, but I'm having trouble simply creating a folder in the root directory. The token is set to a developer token which should be active.
The error I'm receiving now is Bad Request. What is wrong with this code? I'm also having trouble receiving authentication for the user, but I decided to tackle this first.
function createTestFolder() {
$.ajax('https://api.box.com/2.0/folders',
{
data: { name: 'CreatedFolderFromjQuery', parent: { id: '0' } },
type: 'POST',
beforeSend: function(xhr) {
xhr.setRequestHeader('Authorization', 'Bearer ' + window.token);
},
contentType: 'json',
success: function(data, status, xhr) {
alert(status);
},
error: function(xhr, status, error) { alert(error); }
});
}
EDIT : When I change the URL to https://box.com/api/1.0/folders, I seem to get a successful response. That is, the success function gets called, rather than the error function. However, the folder is still not uploaded to my account.
EDIT 2 : Using the curl command line and following the API documentation, I still receive the same error message. Here are the details:
{"type":"error", "status":400, "code":"bad_request", "context_info":{"errors":[{"reason":"invalid_parameter", "name":"entity_body", "message":"Invalid value ''{name:New Folder,'. Entity body should be a correctly nested resource attribute name/value pair"}]}, "help_url":"http://developers.box.com/docs/#errors", "message":"Bad Request", "request_id":"128521198353f4fc831c7e6"}
curl: (6) Could not resolve host: parent
curl: (3) [globbing] unmatched brace in column 1
curl: (3) [globbing] unmatched close brace/bracket in column 2
Ah, I have solved my own question. I am not familiar with jQuery, and here was my mistake:
data: { name: 'CreatedFolderFromjQuery', parent: { id: '0' } },
With jQuery's AJAX API, data needs to be a string. I needed to serialize my POST data into JSON:
data: JSON.stringify({ name: 'CreatedFolderFromjQuery', parent: { id: '0' } }),
Once I realized this, and added the JSON.stringify() the request was sent properly.

how to post object to facebook user wall?

I am using Facebook JavaScript SDK, this code is for log in and post an object to user's wall, which returns an error,
{"error":{"message":"(#200) You do not have sufficient to permissions to perform this action","type":"OAuthException","code":200}}
FB.login(function(data){
if(data.authResponse){
facebookGetDetails();
}else{
console.log("Login operation aborted");
}
},{scope: 'email,publish_actions,read_stream'});
FB.api(
'/me',
'post',
{
app_id: xxxxxxxxxxxx,
type: "business.business",
url: url,
title: title,
image: picUrl,
contact_data: "Bangalore, India",
location: "17.024522",
description: desc
},
function(response) {
console.log(JSON.stringify(response));
// handle the response
});
the following code works, but it only posts to activity stream, not to wall.
FB.api(
'me/namespace:review',
'post',
{
business: "http://samples.ogp.me/616004095080596"
},
function(response) {
// handle the response
}
);
I guess you're using a incomplete endpoint URL here
FB.api(
'/me',
...
);
You should call /me/feed with a post request as described here: https://developers.facebook.com/docs/graph-api/reference/user/feed/#publish

ReferenceError: stripeResponseHandler is not defined - FireFox

I am having an issue with using my Stripe connection in only Firefox, Chrome works perfect.
When I try to send card information to Stripe in Firefox (most recent) it tells me:
ReferenceError: stripeResponseHandler is not defined
Code:
<script type="text/javascript" src="../js/v2"></script>
.....
.....
// set publish key for stripe
Stripe.setPublishableKey('myToken');
// validate information
Stripe.card.createToken({
number: $('.cardnumber').val(),
cvc: $('.cw').val(),
exp_month: $('.expmonth option:selected').val(),
exp_year: $('.expyear option:selected').val(),
name: $(".cardholderfullname").val(),
address_line1: $(".address").val(),
address_city: $(".city").val(),
address_state: $("#state option:selected").val(),
address_zip: $(".zipcode").val()
}, stripeResponseHandler);
// error handling and success sending
function stripeResponseHandler(status, response) {
if (response.error) {
$("#message").fadeIn();
$("#message").html("The card information you entered was not valid, please check to make sure all information is correct.");
} else {
sendArray.token = response['id'];
$(sendArray).serialize();
//console.log(sendArray);
$.ajax({
type: "POST",
dataType: "JSON",
url: '../member/functions/stripeAcc/makeCustomer.php',
data: sendArray ,
success: function(response) {
}
});
closeDialogBox();
}
}
..... more
Suggestions and thoughts?

Categories

Resources