import Stripe from 'stripe' import { User } from 'nexus-plugin-prisma/client' const stripe = new Stripe(process.env.STRIPE_SECRET_KEY, { apiVersion: '2020-08-27', }) // Update the default card so we can charge the customer with the good card const updateDefaultSourceOfCustomer = (customerId: string, sourceId: string) => { return stripe.customers.update(customerId, { default_source: sourceId, }) } const createSource = async (customerId: string, token: string) => { const source = await stripe.customers.createSource(customerId, { source: token, }) await updateDefaultSourceOfCustomer(customerId, source.id) return source } const createStripeCustomer = async (user: User, token: string) => { let customer = user.stripeCustomerId ? await stripe.customers.retrieve(user.stripeCustomerId) : null if (!customer) { customer = await stripe.customers.create({ email: user.email, source: token, }) } else { await createSource(customer.id, token) } return customer } const chargeCustomer = ({ customerId, customerEmail, amount, description = '', destinationAccountId, applicationFeeAmount, }: { customerId: string customerEmail: string amount: number description: string destinationAccountId: string applicationFeeAmount: number }) => { return stripe.paymentIntents.create({ description, amount: Math.floor(amount), confirm: true, customer: customerId, currency: 'cad', application_fee_amount: Math.floor(applicationFeeAmount), on_behalf_of: destinationAccountId, transfer_data: { destination: destinationAccountId, }, ...(customerEmail && { receipt_email: customerEmail, }), }) } // Delete card const deleteStripeSource = (customerId: string, sourceId: string) => { return stripe.customers.deleteSource(customerId, sourceId) } function deleteConnectedAccount(accountId: string) { return stripe.accounts.del(accountId).then((deleteAccount) => { console.log('Stripe account deleted:', deleteAccount.id) }) } export default { createSource, createStripeCustomer, chargeCustomer, updateDefaultSourceOfCustomer, deleteStripeSource, deleteConnectedAccount, }