|
| 1 | +import type { UserModel } from '../../../../orm/src/models/User' |
| 2 | +import { stripe } from '..' |
| 3 | + |
| 4 | +export const paymentIntent: any = (() => { |
| 5 | + function stripeId(user: any): string { |
| 6 | + return user.stripe_id |
| 7 | + } |
| 8 | + |
| 9 | + function hasStripeId(user: any): boolean { |
| 10 | + return user.stripe_id !== null || user.stripe_id !== undefined |
| 11 | + } |
| 12 | + |
| 13 | + function createStripeCustomer(user: any, options: any = {}): Promise<any> { |
| 14 | + if (hasStripeId(user)) { |
| 15 | + throw new Error('Customer already created') |
| 16 | + } |
| 17 | + |
| 18 | + if (!options.name && user.stripeName) { |
| 19 | + options.name = stripeName(user) |
| 20 | + } |
| 21 | + |
| 22 | + if (!options.email && user.stripeEmail) { |
| 23 | + options.email = stripeEmail(user) |
| 24 | + } |
| 25 | + |
| 26 | + if (!options.phone && user.stripePhone) { |
| 27 | + options.phone = stripePhone(user) |
| 28 | + } |
| 29 | + |
| 30 | + if (!options.address && user.stripeAddress) { |
| 31 | + options.address = stripeAddress(user) |
| 32 | + } |
| 33 | + |
| 34 | + if (!options.preferred_locales && user.stripePreferredLocales) { |
| 35 | + options.preferred_locales = stripePreferredLocales(user) |
| 36 | + } |
| 37 | + |
| 38 | + if (!options.metadata && user.stripeMetadata) { |
| 39 | + options.metadata = stripeMetadata(user) |
| 40 | + } |
| 41 | + |
| 42 | + // Here we will create the customer instance on Stripe and store the ID of the |
| 43 | + // user from Stripe. This ID will correspond with the Stripe user instances |
| 44 | + // and allow us to retrieve users from Stripe later when we need to work. |
| 45 | + return stripe.customer.create(options).then((customer: any) => { |
| 46 | + return user.update({ stripe_id: customer.id }) |
| 47 | + }) |
| 48 | + } |
| 49 | + |
| 50 | + function stripeName(user: any): string { |
| 51 | + return user.name || '' |
| 52 | + } |
| 53 | + |
| 54 | + function stripeEmail(user: any): string { |
| 55 | + return user.email || '' |
| 56 | + } |
| 57 | + |
| 58 | + function stripePhone(user: any): string { |
| 59 | + return user.phone || '' |
| 60 | + } |
| 61 | + |
| 62 | + function stripeAddress(user: any): string { |
| 63 | + return user.address || null |
| 64 | + } |
| 65 | + |
| 66 | + function stripePreferredLocales(user: any): string { |
| 67 | + return user.preferred_locales || [] |
| 68 | + } |
| 69 | + |
| 70 | + function stripeMetadata(user: any): string { |
| 71 | + return user.metadata || {} |
| 72 | + } |
| 73 | + |
| 74 | + return { stripeId, hasStripeId, createStripeCustomer } |
| 75 | +})() |
0 commit comments