-
Notifications
You must be signed in to change notification settings - Fork 3.7k
Expand file tree
/
Copy pathinitiatePayment.ts
More file actions
341 lines (312 loc) · 8.78 KB
/
initiatePayment.ts
File metadata and controls
341 lines (312 loc) · 8.78 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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
import { addDataAndFileToRequest, type DefaultDocumentIDType, type Endpoint } from 'payload'
import type {
CurrenciesConfig,
PaymentAdapter,
ProductsValidation,
SanitizedEcommercePluginConfig,
} from '../types/index.js'
import { defaultProductsValidation } from '../utilities/defaultProductsValidation.js'
type Args = {
/**
* The slug of the carts collection, defaults to 'carts'.
*/
cartsSlug?: string
currenciesConfig: CurrenciesConfig
/**
* The slug of the customers collection, defaults to 'users'.
*/
customersSlug?: string
/**
* Track inventory stock for the products and variants.
* Accepts an object to override the default field name.
*/
inventory?: SanitizedEcommercePluginConfig['inventory']
paymentMethod: PaymentAdapter
/**
* The slug of the products collection, defaults to 'products'.
*/
productsSlug?: string
/**
* Customise the validation used for checking products or variants before a transaction is created.
*/
productsValidation?: ProductsValidation
/**
* The slug of the transactions collection, defaults to 'transactions'.
*/
transactionsSlug?: string
/**
* The slug of the variants collection, defaults to 'variants'.
*/
variantsSlug?: string
}
type InitiatePayment = (args: Args) => Endpoint['handler']
/**
* Handles the endpoint for initiating payments. We will handle checking the amount and product and variant prices here before it is sent to the payment provider.
* This is the first step in the payment process.
*/
export const initiatePaymentHandler: InitiatePayment =
({
cartsSlug = 'carts',
currenciesConfig,
customersSlug = 'users',
paymentMethod,
productsSlug = 'products',
productsValidation,
transactionsSlug = 'transactions',
variantsSlug = 'variants',
}) =>
async (req) => {
await addDataAndFileToRequest(req)
const data = req.data
const payload = req.payload
const user = req.user?.collection === customersSlug ? req.user : undefined
let currency: string = currenciesConfig.defaultCurrency
let cartID: DefaultDocumentIDType = data?.cartID
let cart = undefined
const billingAddress = data?.billingAddress
const shippingAddress = data?.shippingAddress
const cartSecret = data?.secret
let customerEmail: string = user?.email ?? ''
if (user) {
if (user.cart?.docs && Array.isArray(user.cart.docs) && user.cart.docs.length > 0) {
if (!cartID && user.cart.docs[0]) {
// Use the user's cart instead
if (typeof user.cart.docs[0] === 'object') {
cartID = user.cart.docs[0].id
cart = user.cart.docs[0]
} else {
cartID = user.cart.docs[0]
}
}
}
} else {
// Get the email from the data if user is not available
if (data?.customerEmail && typeof data.customerEmail === 'string') {
customerEmail = data.customerEmail
} else {
return Response.json(
{
message: 'A customer email is required to make a purchase.',
},
{
status: 400,
},
)
}
}
if (!cart) {
if (cartID) {
// Add cart secret to query for guest cart access control
if (cartSecret && typeof cartSecret === 'string') {
req.query = req.query || {}
req.query.secret = cartSecret
}
cart = await payload.findByID({
id: cartID,
collection: cartsSlug,
depth: 2,
overrideAccess: false,
req,
select: {
id: true,
currency: true,
customerEmail: true,
items: true,
subtotal: true,
},
})
if (!cart) {
return Response.json(
{
message: `Cart with ID ${cartID} not found.`,
},
{
status: 404,
},
)
}
} else {
return Response.json(
{
message: 'Cart ID is required.',
},
{
status: 400,
},
)
}
}
if (cart.currency && typeof cart.currency === 'string') {
currency = cart.currency
}
// Ensure the currency is provided or inferred in some way
if (!currency) {
return Response.json(
{
message: 'Currency is required.',
},
{
status: 400,
},
)
}
// Ensure the selected currency is supported
if (
!currenciesConfig.supportedCurrencies.find(
(c) => c.code.toLocaleLowerCase() === currency.toLocaleLowerCase(),
)
) {
return Response.json(
{
message: `Currency ${currency} is not supported.`,
},
{
status: 400,
},
)
}
// Verify the cart is available and items are present in an array
if (!cart || !cart.items || !Array.isArray(cart.items) || cart.items.length === 0) {
return Response.json(
{
message: 'Cart is required and must contain at least one item.',
},
{
status: 400,
},
)
}
for (const item of cart.items) {
// Target field to check the price based on the currency so we can validate the total
const priceField = `priceIn${currency.toUpperCase()}`
const quantity = item.quantity || 1
// If the item has a product but no variant, we assume the product has a price in the specified currency
if (item.product && !item.variant) {
const id = typeof item.product === 'object' ? item.product.id : item.product
const product = await payload.findByID({
id,
collection: productsSlug,
depth: 0,
select: {
inventory: true,
[priceField]: true,
},
})
if (!product) {
return Response.json(
{
message: `Product with ID ${item.product} not found.`,
},
{
status: 404,
},
)
}
try {
if (productsValidation) {
await productsValidation({ currenciesConfig, currency, product, quantity })
} else {
await defaultProductsValidation({
currenciesConfig,
currency,
product,
quantity,
})
}
} catch (error) {
payload.logger.error(
error,
'Error validating product or variant during payment initiation.',
)
return Response.json(
{
message: error,
...(error instanceof Error ? { cause: error.cause } : {}),
},
{
status: 400,
},
)
}
if (item.variant) {
const id = typeof item.variant === 'object' ? item.variant.id : item.variant
const variant = await payload.findByID({
id,
collection: variantsSlug,
depth: 0,
select: {
inventory: true,
[priceField]: true,
},
})
if (!variant) {
return Response.json(
{
message: `Variant with ID ${item.variant} not found.`,
},
{
status: 404,
},
)
}
try {
if (productsValidation) {
await productsValidation({
currenciesConfig,
currency,
product: item.product,
quantity,
variant,
})
} else {
await defaultProductsValidation({
currenciesConfig,
currency,
product: item.product,
quantity,
variant,
})
}
} catch (error) {
payload.logger.error(
error,
'Error validating product or variant during payment initiation.',
)
return Response.json(
{
message: error,
},
{
status: 400,
},
)
}
}
}
}
try {
const paymentResponse = await paymentMethod.initiatePayment({
customersSlug,
data: {
billingAddress,
cart,
currency,
customerEmail,
shippingAddress,
},
req,
transactionsSlug,
})
return Response.json(paymentResponse)
} catch (error) {
payload.logger.error(error, 'Error initiating payment.')
return Response.json(
{
message: 'Error initiating payment.',
},
{
status: 500,
},
)
}
}