Created
November 25, 2024 10:47
-
-
Save tosipaulo/74f58776cbbbccc3e4f8c1a2d44f093e to your computer and use it in GitHub Desktop.
Stripe.js
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 { PrismaClient } = require('@prisma/client'); | |
const prisma = new PrismaClient(); | |
const { stripe } = require('../utils/stripe'); | |
const createCheckoutSession = async (priceId, userId, userEmail) => { | |
try { | |
let customer = await createStripeCustomer(userEmail); | |
const session = await stripe.checkout.sessions.create({ | |
payment_method_types: ['card'], | |
line_items: [{ | |
price: priceId, | |
quantity: 1 | |
}], | |
mode: 'subscription', | |
client_reference_id: userId, | |
customer: customer.id, | |
success_url: 'http://localhost:3000/success.html', | |
cancel_url: 'http://localhost:3000/cancel.html' | |
}) | |
return { | |
customer, | |
url: session.url | |
} | |
} catch (error) { | |
console.log(error) | |
} | |
} | |
const createCheckout = async (req, res) => { | |
const userId = req.headers['x-user-id']; | |
try { | |
if(!userId) { | |
return res.status(400).send({ | |
error: true, | |
message: 'Ops! Parece que não está autorizado!' | |
}); | |
} | |
const user = await prisma.user.findUnique({ | |
where: {id: userId} | |
}); | |
if(!user) { | |
return res.status(400).send({ | |
error: true, | |
message: 'Ops! Parece que não está autorizado!' | |
}); | |
} | |
const checkout = await createCheckoutSession(process.env.SRIPE_PRICE_TRI, user.id, user.email); | |
await prisma.user.update({ | |
where: {id: user.id}, | |
data: { | |
customerId: checkout.customer.id | |
} | |
}) | |
return res.status(200).send({ | |
error: false, | |
checkout | |
}); | |
} catch (error) { | |
return res.status(422).send({ error: 'Ops! Erro ao fazer login' }); | |
} | |
} | |
module.exports = {createCheckout} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment