Skip to content

Instantly share code, notes, and snippets.

@gragland
Created May 14, 2020 18:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save gragland/4811f50f2f8637134d52199942632d9f to your computer and use it in GitHub Desktop.
Save gragland/4811f50f2f8637134d52199942632d9f to your computer and use it in GitHub Desktop.
const stripe = require("stripe")(process.env.STRIPE_SECRET_KEY);
const requireAuth = require("./_require-auth.js");
const { updateUser } = require("./_db.js");
export default requireAuth((req, res) => {
const user = req.user;
// If user already has a stripeCustomerId then return it in success response
if (user.stripeCustomerId) {
return res.send({
status: "success",
data: stripeCustomerId,
});
}
// Check if there's already a customer in Stripe with this email
// We use the email from the JWT token (decoded by requireAuth middleware)
return getExistingCustomer(user.email)
.then((existingCustomer) => {
// If there's an existing customer then return it in success response
if (existingCustomer) {
return res.send({
status: "success",
data: existingCustomer.id,
});
}
})
.then(() => {
// Create a new Stripe customer
return stripe.customers.create({
email: user.email,
});
})
.then((customer) => {
// Update user in database with Stripe customer.id and pass customer object to next step
return updateUser(user.uid, {
stripeCustomerId: customer.id,
}).then(() => customer);
})
.then((customer) => {
// Return success response
res.send({
status: "success",
data: customer.id,
});
})
.catch((error) => {
// Handle errors and return error response
res.send({
status: "error",
code: error.code,
message: error.message,
});
});
});
// Fetch a customer from Stripe by email
function getExistingCustomer(email) {
// Stripe allows multiple customers with the same email so we
// limit to 1 and then return first customer in response.
return stripe.customers
.list({
email: email,
limit: 1,
})
.then((response) => {
return response.data.length && response.data[0];
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment