I've been trying to integrate Stripe with Node JS, but I can't get Stripe to return the error. I pass malformed data on purpose, but I still can not get the error back.
I'm new to Node JS.
Here is Stripe's official doc:
https://stripe.com/docs/api/charges/create
Here is my code:
Parse.Cloud.define("addCredit", (request) => {
// Use stripe API and your own 'secret key'
var stripe = require('stripe')('xdsewew');
// Charge user's card
stripe.charges.create({
amount: request.params.amount,
currency: 'usd',
source: request.params.token,
description: request.params.userId,
}, function(error, charge) {
return(error);
});
});
Maybe I'm not doing it right when I try to return the error?
I tried the same and I'm able to log the error
var stripe = require("stripe")("sk_test_4eC39HqLyjWDarjtT1zdp7d");
stripe.charges.create(
{
amount: 2000,
currency: "usd",
source: "tok_mastercard",
description: "My First Test Charge (created for API docs)",
},
function (err, charge) {
if (err) {
// different ways to log error
console.log("error message -> ", err.message);
console.log("error type - >", err.type);
console.log("eror raw -> ", err.raw);
return err;
}
console.log(charge);
}
);
Hope this works for you :)
Related
I'm trying to add a token to create a bank account with stripe.
tokenAccount: async (req, res) => {
Serveur.findOne({ _id: req.user._id }, async (err, user) => {
try {
await stripe.tokens.create({
bank_account: {
country: req.body.country,
currency: req.body.currency,
account_number: req.body.account_number,
routing_number: req.body.routing_number,
},
});
} catch (error) {
return res.status("402").send({ error: { message: error.message } });
}
});
},
and when i test the back end with postman with a "test" bank details from stripe i have this error :
{
"error": {
"message": "You cannot use a live bank account number when making transfers or debits in test mode"
}
}
Which is weird because i used the test stripe's bank details. Do you have any idea what the problem could be ???
Each Stripe account offers both live and test keys. When you use their fake test accounts (for banks, MasterCards, and the like) you must also use their test keys. Don't try to use the live keys for testing; and, honestly, be happy they caught this for you.
I am trying to implement Stripe in my backend which is in node js. While calling it from front end I am getting this error:
You did not provide an API key, though you did set your Authorization header to "null". Using Bearer auth, your Authorization header should look something like 'Authorization: Bearer YOUR_SECRET_KEY'. See https://stripe.com/docs/api#authentication for details, or we can help at https://support.stripe.com/.
Here is my code:
const stripe = require("stripe")(process.env.keySecret);
if(req.body.type == 'stripe') {
const token = req.body.token;
const amount = req.body.amount;
let charge = stripe.charges.create({
amount: amount,
source: token,
currency: 'USD'
},(err, chargeData) => {
if(err) {
console.log('error in buy premium api error... ', err);
return;
}
let payment = [];
payment.push({
amount: chargeData.amount,
address: chargeData.billing_details.address,
email: chargeData.billing_details.email,
payment_method_details: chargeData.payment_method_details.card
})
console.log('charge... ', charge);
if(charge) {
register.findByIdAndUpdate({ _id: therapist._id },
{
$set:
{
payment_details: payment
}
}, {new:true}, (e1, updatedUser) => {
if(e1) {
return;
}
resolve(updatedUser);
})
}
})
}
else {
let err = 'No payment type define..';
return reject(err);
}
My req.body is:
{
"token": "tok_1F2XPBG04BYg8nGtLoWnQwRU", // coming from front end
"amount": "250",
"type":"stripe"
}
The secret key is test secret key which is like sk_test_xxxxxxxxxxxxxxxx.
My front end is in Angular 6 and from front end I am passing my test publishable key i.e. pk_test_xxxxxxxxxxxxxxxxx. I am passing proper data to the both front end as well as backend. Where am I mistaken?
Since you are calling .env file, you have to include the following line before requiring stripe:
require ("dotenv").config();
const stripe = require("stripe")(process.env.keySecret);
Working on integrating stipe. Everything seems to work on the front end but on the server side code the token is empty and it is not successfully charging to Stripe. Can't seem to figure out where I'm going wrong.
app.post('/apple-pay', function(req, res, next) {
// Set your secret key: remember to change this to your live secret key in production
// See your keys here: https://dashboard.stripe.com/account/apikeys
var stripe = require("stripe")("sk_test_XXX");
// Token is created using Checkout or Elements!
// Get the payment token ID submitted by the form:
const token = req.body.stripeToken;
console.log(token)
const charge = stripe.charges.create({
amount: 999,
currency: 'usd',
description: 'Example charge',
source: token,
}, function(err, charge) {
if(err){
req.flash("error", err.message);
res.redirect("back");
} else {
}
});
});
Before Creating charge, You should create Customer. After Charge Works.
Sample Code. (ES6)
let customer = await payStripe.customers.create({
email: req.body.stripeEmail,
source: req.body.stripeToken
});
//After Created Customer...
if(customer){
let charge = await payStripe.charges.create({
amount: req.body.amount,
description: req.body.description,
currency: 'usd',
customer: customer.id
});
}
I hope it's work fine.
In your frontend code from the other question you passed the POST body as
JSON.stringify({token: ev.token.id})
which means that the Stripe token is actually in the token POST parameter, not stripeToken. So you need to do
const token = req.body.token;
instead.
When attempting to begin a Subscription for a newly created Customer, I receive the following error from Stripe:
invalid_request_error
Error: This customer has no attached payment source
The customer seems to be created just fine. I am using Stripe Checkout to collect the card token. For testing, I am using Stripe's 4242 4242 4242 4242 card number with random information. The token seems to be getting created and passed to my server just fine. Below is my server side code:
stripe.plans.retrieve(
"basic-monthly",
function(err, plan) {
if (err) {
console.error(err)
res.sendStatus(500)
} else {
stripe.customers.create({
email: owner,
source: token.id,
}, function(err, customer) {
if (err) {
console.error(err)
res.sendStatus(500)
} else {
stripe.subscriptions.create({
customer: customer.id,
items: [
{
plan: "basic-monthly",
quantity: 1
},
],
}, function(err, subscription) {
if (err) {
console.error(err)
console.log('##### UNABLE TO CREATE SUBSCRIPTION ####')
res.sendStatus(500)
} else {
console.log('Subscription created.')
console.dir(subscription)
res.sendStatus(200);
}
});
}
});
}
});
##### UNABLE TO CREATE SUBSCRIPTION #### is logged, along with the errors described above. I understand what the error means, but I am not sure how it is occurring. As you can see above, I am passing in the Token Id when creating a customer, source: token.id,.
What is the issue here?
The most likely cause here is that token.id is empty, so the Customer is being created without a Source. I'd suggest logging the contents of token and see what you get.
I'm trying to make charges on connected standalone acount. I'm using parse cloud code for that...it gives me following error:
Error Domain=Parse Code=141 "ReferenceError: stripe is not defined
Below is my code..
var Stripe = require('stripe');
Stripe.initialize('**************************');
Parse.Cloud.define("hello", function(request, response) {
var token = request.params.stripeToken;
var userid = request.params.userId;
stripe.charges.create(
{
amount: 1000,
currency: "usd",
source: token,
description: "Example charge",
application_fee: 123
},
{stripe_account: userid},{
success: function(httpResponse) {
response.success("Purchase made!");
},
error: function(httpResponse) {
response.error(error);
}
});
});