-
-
Notifications
You must be signed in to change notification settings - Fork 186
Expand file tree
/
Copy pathpaymentRequestBuilds.ts
More file actions
80 lines (67 loc) · 2 KB
/
Copy pathpaymentRequestBuilds.ts
File metadata and controls
80 lines (67 loc) · 2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
import Models from '../../models'
import createStripe from '../../client/payment/stripe'
import PaymentRequestMail from '../mail/paymentRequest'
const db = Models as any
type PaymentRequestParams = {
id?: number | string
userId?: number | string
title: string
description?: string
amount?: number
currency?: string
custom_amount?: boolean
}
const stripe = createStripe()
export async function paymentRequestBuilds(
paymentRequestParams: PaymentRequestParams
): Promise<any> {
const currency = paymentRequestParams.currency ?? 'usd'
const { id, userId, title, description, amount, custom_amount } = paymentRequestParams
const product = await stripe.products.create({
name: title,
description,
metadata: {
payment_request_id: id ?? null,
user_id: userId ?? null
}
})
const finalAmount = amount ? Math.round(amount * 100) : 0
const finalPriceData = custom_amount
? { custom_unit_amount: { enabled: true } }
: { unit_amount: finalAmount }
const price = await stripe.prices.create({
...finalPriceData,
currency,
product: product.id,
metadata: {
payment_request_id: id ?? null,
user_id: userId ?? null
}
})
const paymentLink = await stripe.paymentLinks.create({
line_items: [{ price: price.id, quantity: 1 }]
})
const createPaymentRequest = await db.PaymentRequest.create({
...paymentRequestParams,
payment_link_id: paymentLink.id,
payment_url: paymentLink.url,
currency,
amount,
custom_amount: custom_amount ?? false,
title,
description
})
await stripe.paymentLinks.update(paymentLink.id, {
metadata: {
payment_request_id: createPaymentRequest.id,
user_id: createPaymentRequest.userId
}
})
const paymentRequest = await db.PaymentRequest.findByPk(createPaymentRequest.id, {
include: [{ model: db.User }]
})
if (createPaymentRequest?.id) {
await PaymentRequestMail.paymentRequestInitiated(paymentRequest.User, paymentRequest)
}
return createPaymentRequest
}