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!