Retrieve Customer ID Stripe
I am working on a website with a server in nodeJS.
I implemented stripe API to make people pay every month.
I need to get their email / custumer_ID in my database (along with other informations) but I can't manage to get those informations.
here is my code :
app.post("/charge", (req, res) => {
stripe.customers.create({
email: req.body.stripeEmail,
source: req.body.stripeToken
})
.then(customer =>
stripe.subscriptions.create({
plan: 'plan_EQoygL3d1jnHM2',
customer: customer.id
}))
.then(charge => res.render("charge.pug"));
var sql = "INSERT INTO authentification (customerID, email, discord_key, datePayement) values ?";
var datenow = new Date();
var values = [
[customer.id, email, generateKey(), datenow]
];
DB.query(sql, values, function (err, result) {
if (err) throw err;
console.log(result);
});
});
This is the error I get :
ReferenceError: customer is not defined.
Customer not defined on this part :
var values = [
[customer.id, email, generateKey(), datenow]
];
I also wanted to know if the way I did it was secured or if there were other ways to do it?
Thank you very much for your help !
I am new to node JS.
Answer
The customer variable only exists within the scope of this function
customer => stripe.subscriptions.create({
plan: 'plan_EQoygL3d1jnHM2',
customer: customer.id
})
it is the short hand form of writing
function(customer) {
stripe.subscriptions.create({
plan: 'plan_EQoygL3d1jnHM2',
customer: customer.id
})
}
and it is called when stripe.customers.create finishes running. It is asynchronous, and I'm not going to go into much detail about it, but it simply means it doesn't block the execution thread but instead it all moves on to the next line of code, and calls the above function whenever the Stripe API replies back.
Accounting for this, it means that what happens right now is that
var values = [
[customer.id, email, generateKey(), datenow]
];
MUST be throwing an error along the lines of ReferenceError: customer is not defined
You have multiple options to solve this.
The easiest to understand and read is, provided that you're using a node version higher than 7.6 (type node -v
in your terminal/cmd), using async/await to deal with the asynchronous call as such
app.post("/charge", async (req, res) => {
try {
var customer = await stripe.customers.create({
email: req.body.stripeEmail,
source: req.body.stripeToken
})
await stripe.subscriptions.create({ // no point in awaiting here
plan: 'plan_EQoygL3d1jnHM2',
customer: customer.id
}))
res.render("charge.pug")
var sql = "INSERT INTO authentification (customerID, email, discord_key, datePayement) values ?";
var datenow = new Date();
var values = [
[customer.id, customer.email, generateKey(), datenow]
];
DB.query(sql, values, function (err, result) {
if (err) throw err;
console.log(result);
});
} catch (ex) {
console.error('/charge encountered exception', exception) // the try/catch block is optional, but should help you figure out further problems along the way
res.sendStatus(503)
}
});
If, however, you're constrained to a lower version of Node, you can keep using Promises (briefly, the .then
pattern you see) as such
app.post("/charge", (req, res) => {
stripe.customers.create({
email: req.body.stripeEmail,
source: req.body.stripeToken
}).then(customer => {
var sql = "INSERT INTO authentification (customerID, email, discord_key, datePayement) values ?";
var datenow = new Date();
var values = [
[customer.id, customer.email, generateKey(), datenow]
];
DB.query(sql, values, function (err, result) {
if (err) throw err;
console.log(result);
});
return stripe.subscriptions.create({ // returning a Promise here means the next .then will wait for it to solve, before rendering 'charge.pug'
plan: 'plan_EQoygL3d1jnHM2',
customer: customer.id
})
})
.then(charge => res.render("charge.pug"));
.catch(exception => {
console.error('/charge encountered exception', exception) // the .catch is optional, but should help you figure out further problems along the way
res.sendStatus(503)
})
});
Hope this helps!
Related Questions
- → I can't do a foreign key, constraint error
- → How to implement DbDongle::convertTimestamps as workaround of invalid timestamps with MySql strict
- → MySQL error "Foreign key constraint is incorrectly formed"
- → Eloquent Multitable query
- → "Laravel 5.1" add user and project with userId
- → Database backup with custom code in laravel 5 and get the data upto 10 rows from per table in database
- → Laravel 5.1 QueryException when trying to delete a project
- → Using Array in '->where()' for Laravel Query Building
- → Chaining "Count of Columns" of a Method to Single Query Builder
- → Laravel Eloquent Joining Strange query
- → convert time using mysql laravel 5
- → How to update a column after an expiration date in MySQL?
- → Foreign key constraint fails on existing key