Created
May 14, 2020 19:04
-
-
Save HEYGUL/f61c0125591fef23ff31aeda6e10b099 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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, | |
}); | |
} | |
// 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