|
1
|
import { |
|
2
|
AccountHolderDTO, |
|
3
|
BigNumberInput, |
|
4
|
CaptureDTO, |
|
5
|
Context, |
|
6
|
CreateAccountHolderDTO, |
|
7
|
CreateAccountHolderOutput, |
|
8
|
CreateCaptureDTO, |
|
9
|
CreatePaymentCollectionDTO, |
|
10
|
CreatePaymentMethodDTO, |
|
11
|
CreatePaymentSessionDTO, |
|
12
|
CreateRefundDTO, |
|
13
|
DAL, |
|
14
|
DeletePaymentMethodDTO, |
|
15
|
FilterablePaymentCollectionProps, |
|
16
|
FilterablePaymentMethodProps, |
|
17
|
FilterablePaymentProviderProps, |
|
18
|
FindConfig, |
|
19
|
InferEntityType, |
|
20
|
InitiatePaymentOutput, |
|
21
|
InternalModuleDeclaration, |
|
22
|
IPaymentModuleService, |
|
23
|
Logger, |
|
24
|
ModuleJoinerConfig, |
|
25
|
ModulesSdkTypes, |
|
26
|
PaymentCollectionDTO, |
|
27
|
PaymentCollectionUpdatableFields, |
|
28
|
PaymentDTO, |
|
29
|
PaymentMethodDTO, |
|
30
|
PaymentProviderDTO, |
|
31
|
PaymentSessionDTO, |
|
32
|
ProviderWebhookPayload, |
|
33
|
RefundDTO, |
|
34
|
RefundReasonDTO, |
|
35
|
UpdateAccountHolderDTO, |
|
36
|
UpdateAccountHolderOutput, |
|
37
|
UpdatePaymentCollectionDTO, |
|
38
|
UpdatePaymentDTO, |
|
39
|
UpdatePaymentSessionDTO, |
|
40
|
UpsertPaymentCollectionDTO, |
|
41
|
WebhookActionResult, |
|
42
|
} from "@medusajs/framework/types" |
|
43
|
import { |
|
44
|
BigNumber, |
|
45
|
defaultCurrencies, |
|
46
|
EmitEvents, |
|
47
|
getEpsilonFromDecimalPrecision, |
|
48
|
InjectManager, |
|
49
|
InjectTransactionManager, |
|
50
|
isPresent, |
|
51
|
isString, |
|
52
|
MathBN, |
|
53
|
MedusaContext, |
|
54
|
MedusaError, |
|
55
|
ModulesSdkUtils, |
|
56
|
normalizeCurrencyCode, |
|
57
|
PaymentCollectionStatus, |
|
58
|
PaymentSessionStatus, |
|
59
|
promiseAll, |
|
60
|
RefundStatus, |
|
61
|
SoftDeletableFilterKey, |
|
62
|
} from "@medusajs/framework/utils" |
|
63
|
import { SqlEntityManager } from "@medusajs/framework/mikro-orm/postgresql" |
|
64
|
import { |
|
65
|
AccountHolder, |
|
66
|
Capture, |
|
67
|
Payment, |
|
68
|
PaymentCollection, |
|
69
|
PaymentSession, |
|
70
|
Refund, |
|
71
|
RefundReason, |
|
72
|
} from "@models" |
|
73
|
import { joinerConfig } from "../joiner-config" |
|
74
|
import PaymentProviderService from "./payment-provider" |
|
75
|
|
|
76
|
type InjectedDependencies = { |
|
77
|
logger?: Logger |
|
78
|
baseRepository: DAL.RepositoryService |
|
79
|
paymentService: ModulesSdkTypes.IMedusaInternalService<any> |
|
80
|
captureService: ModulesSdkTypes.IMedusaInternalService<any> |
|
81
|
refundService: ModulesSdkTypes.IMedusaInternalService<any> |
|
82
|
paymentSessionService: ModulesSdkTypes.IMedusaInternalService<any> |
|
83
|
paymentCollectionService: ModulesSdkTypes.IMedusaInternalService<any> |
|
84
|
accountHolderService: ModulesSdkTypes.IMedusaInternalService<any> |
|
85
|
paymentProviderService: PaymentProviderService |
|
86
|
} |
|
87
|
|
|
88
|
/** |
|
89
|
* How long a refund may sit in `pending` before a retry with the same |
|
90
|
* idempotency key is allowed to take it over. It has to comfortably exceed the |
|
91
|
* slowest provider call, since a retry inside this window is treated as a |
|
92
|
* conflict rather than a recovery. |
|
93
|
*/ |
|
94
|
const PENDING_REFUND_RECOVERY_MS = 15 * 60 * 1000 |
|
95
|
|
|
96
|
const generateMethodForModels = { |
|
97
|
PaymentCollection, |
|
98
|
PaymentSession, |
|
99
|
Payment, |
|
100
|
Capture, |
|
101
|
Refund, |
|
102
|
RefundReason, |
|
103
|
AccountHolder, |
|
104
|
} |
|
105
|
|
|
106
|
export default class PaymentModuleService |
|
107
|
extends ModulesSdkUtils.MedusaService<{ |
|
108
|
PaymentCollection: { dto: PaymentCollectionDTO } |
|
109
|
PaymentSession: { dto: PaymentSessionDTO } |
|
110
|
Payment: { dto: PaymentDTO } |
|
111
|
Capture: { dto: CaptureDTO } |
|
112
|
Refund: { dto: RefundDTO } |
|
113
|
RefundReason: { dto: RefundReasonDTO } |
|
114
|
AccountHolder: { dto: AccountHolderDTO } |
|
115
|
}>(generateMethodForModels) |
|
116
|
implements IPaymentModuleService |
|
117
|
{ |
|
118
|
protected baseRepository_: DAL.RepositoryService |
|
119
|
|
|
120
|
protected paymentService_: ModulesSdkTypes.IMedusaInternalService< |
|
121
|
typeof Payment |
|
122
|
> |
|
123
|
protected captureService_: ModulesSdkTypes.IMedusaInternalService< |
|
124
|
typeof Capture |
|
125
|
> |
|
126
|
protected refundService_: ModulesSdkTypes.IMedusaInternalService< |
|
127
|
typeof Refund |
|
128
|
> |
|
129
|
protected paymentSessionService_: ModulesSdkTypes.IMedusaInternalService< |
|
130
|
typeof PaymentSession |
|
131
|
> |
|
132
|
protected paymentCollectionService_: ModulesSdkTypes.IMedusaInternalService< |
|
133
|
typeof PaymentCollection |
|
134
|
> |
|
135
|
protected paymentProviderService_: PaymentProviderService |
|
136
|
protected accountHolderService_: ModulesSdkTypes.IMedusaInternalService< |
|
137
|
typeof AccountHolder |
|
138
|
> |
|
139
|
|
|
140
|
constructor( |
|
141
|
{ |
|
142
|
baseRepository, |
|
143
|
paymentService, |
|
144
|
captureService, |
|
145
|
refundService, |
|
146
|
paymentSessionService, |
|
147
|
paymentProviderService, |
|
148
|
paymentCollectionService, |
|
149
|
accountHolderService, |
|
150
|
}: InjectedDependencies, |
|
151
|
protected readonly moduleDeclaration: InternalModuleDeclaration |
|
152
|
) { |
|
153
|
// @ts-ignore |
|
154
|
super(...arguments) |
|
155
|
|
|
156
|
this.baseRepository_ = baseRepository |
|
157
|
|
|
158
|
this.refundService_ = refundService |
|
159
|
this.captureService_ = captureService |
|
160
|
this.paymentService_ = paymentService |
|
161
|
this.paymentSessionService_ = paymentSessionService |
|
162
|
this.paymentProviderService_ = paymentProviderService |
|
163
|
this.paymentCollectionService_ = paymentCollectionService |
|
164
|
this.accountHolderService_ = accountHolderService |
|
165
|
} |
|
166
|
|
|
167
|
__joinerConfig(): ModuleJoinerConfig { |
|
168
|
return joinerConfig |
|
169
|
} |
|
170
|
|
|
171
|
protected roundToCurrencyPrecision( |
|
172
|
amount: BigNumberInput, |
|
173
|
currencyCode: string |
|
174
|
): BigNumberInput { |
|
175
|
let precision: number | undefined = undefined |
|
176
|
try { |
|
177
|
const formatted = Intl.NumberFormat(undefined, { |
|
178
|
style: "currency", |
|
179
|
currency: currencyCode, |
|
180
|
}).format(0.1111111) |
|
181
|
|
|
182
|
precision = formatted.split(".")[1].length |
|
183
|
} catch { |
|
184
|
// Unknown currency, keep the full precision |
|
185
|
} |
|
186
|
|
|
187
|
return MathBN.convert(amount, precision) |
|
188
|
} |
|
189
|
|
|
190
|
// @ts-expect-error |
|
191
|
createPaymentCollections( |
|
192
|
data: CreatePaymentCollectionDTO, |
|
193
|
sharedContext?: Context |
|
194
|
): Promise<PaymentCollectionDTO> |
|
195
|
|
|
196
|
// @ts-expect-error |
|
197
|
createPaymentCollections( |
|
198
|
data: CreatePaymentCollectionDTO[], |
|
199
|
sharedContext?: Context |
|
200
|
): Promise<PaymentCollectionDTO[]> |
|
201
|
|
|
202
|
@InjectManager() |
|
203
|
@EmitEvents() |
|
204
|
// @ts-expect-error |
|
205
|
async createPaymentCollections( |
|
206
|
data: CreatePaymentCollectionDTO | CreatePaymentCollectionDTO[], |
|
207
|
@MedusaContext() sharedContext?: Context |
|
208
|
): Promise<PaymentCollectionDTO | PaymentCollectionDTO[]> { |
|
209
|
const input = Array.isArray(data) ? data : [data] |
|
210
|
|
|
211
|
const collections = await this.createPaymentCollections_( |
|
212
|
input, |
|
213
|
sharedContext |
|
214
|
) |
|
215
|
|
|
216
|
return await this.baseRepository_.serialize<PaymentCollectionDTO[]>( |
|
217
|
Array.isArray(data) ? collections : collections[0] |
|
218
|
) |
|
219
|
} |
|
220
|
|
|
221
|
@InjectTransactionManager() |
|
222
|
async createPaymentCollections_( |
|
223
|
data: CreatePaymentCollectionDTO[], |
|
224
|
@MedusaContext() sharedContext?: Context |
|
225
|
): Promise<InferEntityType<typeof PaymentCollection>[]> { |
|
226
|
const normalizedData = data.map((d) => ({ |
|
227
|
...d, |
|
228
|
currency_code: d.currency_code |
|
229
|
? normalizeCurrencyCode(d.currency_code) |
|
230
|
: d.currency_code, |
|
231
|
})) |
|
232
|
return await this.paymentCollectionService_.create( |
|
233
|
normalizedData, |
|
234
|
sharedContext |
|
235
|
) |
|
236
|
} |
|
237
|
|
|
238
|
// @ts-expect-error |
|
239
|
updatePaymentCollections( |
|
240
|
paymentCollectionId: string, |
|
241
|
data: PaymentCollectionUpdatableFields, |
|
242
|
sharedContext?: Context |
|
243
|
): Promise<PaymentCollectionDTO> |
|
244
|
// @ts-expect-error |
|
245
|
updatePaymentCollections( |
|
246
|
selector: FilterablePaymentCollectionProps, |
|
247
|
data: PaymentCollectionUpdatableFields, |
|
248
|
sharedContext?: Context |
|
249
|
): Promise<PaymentCollectionDTO[]> |
|
250
|
|
|
251
|
@InjectManager() |
|
252
|
@EmitEvents() |
|
253
|
// @ts-expect-error |
|
254
|
async updatePaymentCollections( |
|
255
|
idOrSelector: string | FilterablePaymentCollectionProps, |
|
256
|
data: PaymentCollectionUpdatableFields, |
|
257
|
@MedusaContext() sharedContext?: Context |
|
258
|
): Promise<PaymentCollectionDTO | PaymentCollectionDTO[]> { |
|
259
|
let updateData: UpdatePaymentCollectionDTO[] = [] |
|
260
|
|
|
261
|
if (isString(idOrSelector)) { |
|
262
|
updateData = [ |
|
263
|
{ |
|
264
|
id: idOrSelector, |
|
265
|
...data, |
|
266
|
...(data.currency_code ? |
|
267
|
{ currency_code: normalizeCurrencyCode(data.currency_code) } : |
|
268
|
{}), |
|
269
|
}, |
|
270
|
] |
|
271
|
} else { |
|
272
|
const collections = await this.paymentCollectionService_.list( |
|
273
|
idOrSelector, |
|
274
|
{}, |
|
275
|
sharedContext |
|
276
|
) |
|
277
|
|
|
278
|
updateData = collections.map((c) => ({ |
|
279
|
id: c.id, |
|
280
|
...data, |
|
281
|
...(data.currency_code ? |
|
282
|
{ currency_code: normalizeCurrencyCode(data.currency_code) } : |
|
283
|
{} |
|
284
|
), |
|
285
|
})) |
|
286
|
} |
|
287
|
|
|
288
|
const result = await this.updatePaymentCollections_( |
|
289
|
updateData, |
|
290
|
sharedContext |
|
291
|
) |
|
292
|
|
|
293
|
return await this.baseRepository_.serialize<PaymentCollectionDTO[]>( |
|
294
|
Array.isArray(data) ? result : result[0] |
|
295
|
) |
|
296
|
} |
|
297
|
|
|
298
|
@InjectTransactionManager() |
|
299
|
async updatePaymentCollections_( |
|
300
|
data: UpdatePaymentCollectionDTO[], |
|
301
|
@MedusaContext() sharedContext?: Context |
|
302
|
): Promise<InferEntityType<typeof PaymentCollection>[]> { |
|
303
|
return await this.paymentCollectionService_.update(data, sharedContext) |
|
304
|
} |
|
305
|
|
|
306
|
upsertPaymentCollections( |
|
307
|
data: UpsertPaymentCollectionDTO[], |
|
308
|
sharedContext?: Context |
|
309
|
): Promise<PaymentCollectionDTO[]> |
|
310
|
upsertPaymentCollections( |
|
311
|
data: UpsertPaymentCollectionDTO, |
|
312
|
sharedContext?: Context |
|
313
|
): Promise<PaymentCollectionDTO> |
|
314
|
|
|
315
|
@InjectManager() |
|
316
|
@EmitEvents() |
|
317
|
async upsertPaymentCollections( |
|
318
|
data: UpsertPaymentCollectionDTO | UpsertPaymentCollectionDTO[], |
|
319
|
@MedusaContext() sharedContext?: Context |
|
320
|
): Promise<PaymentCollectionDTO | PaymentCollectionDTO[]> { |
|
321
|
const result = await this.upsertPaymentCollections_(data, sharedContext) |
|
322
|
|
|
323
|
return await this.baseRepository_.serialize< |
|
324
|
PaymentCollectionDTO[] | PaymentCollectionDTO |
|
325
|
>(Array.isArray(data) ? result : result[0]) |
|
326
|
} |
|
327
|
|
|
328
|
@InjectTransactionManager() |
|
329
|
protected async upsertPaymentCollections_( |
|
330
|
data: UpsertPaymentCollectionDTO | UpsertPaymentCollectionDTO[], |
|
331
|
@MedusaContext() sharedContext?: Context |
|
332
|
): Promise<InferEntityType<typeof PaymentCollection>[]> { |
|
333
|
const input = Array.isArray(data) ? data : [data] |
|
334
|
const forUpdate = input |
|
335
|
.filter( |
|
336
|
(collection): collection is UpdatePaymentCollectionDTO => |
|
337
|
!!collection.id |
|
338
|
) |
|
339
|
.map((element) => ({ |
|
340
|
...element, |
|
341
|
...(element.currency_code ? |
|
342
|
{ currency_code: normalizeCurrencyCode(element.currency_code) } : |
|
343
|
{} |
|
344
|
) |
|
345
|
})) |
|
346
|
const forCreate = input |
|
347
|
.filter( |
|
348
|
(collection): collection is CreatePaymentCollectionDTO => !collection.id |
|
349
|
) |
|
350
|
.map((element) => ({ |
|
351
|
...element, |
|
352
|
...(element.currency_code ? |
|
353
|
{ currency_code: normalizeCurrencyCode(element.currency_code) } : |
|
354
|
{} |
|
355
|
) |
|
356
|
})) |
|
357
|
|
|
358
|
const operations: Promise<InferEntityType<typeof PaymentCollection>[]>[] = |
|
359
|
[] |
|
360
|
|
|
361
|
if (forCreate.length) { |
|
362
|
operations.push(this.createPaymentCollections_(forCreate, sharedContext)) |
|
363
|
} |
|
364
|
if (forUpdate.length) { |
|
365
|
operations.push(this.updatePaymentCollections_(forUpdate, sharedContext)) |
|
366
|
} |
|
367
|
|
|
368
|
const result = (await promiseAll(operations)).flat() |
|
369
|
|
|
370
|
return result |
|
371
|
} |
|
372
|
|
|
373
|
completePaymentCollections( |
|
374
|
paymentCollectionId: string, |
|
375
|
sharedContext?: Context |
|
376
|
): Promise<PaymentCollectionDTO> |
|
377
|
completePaymentCollections( |
|
378
|
paymentCollectionId: string[], |
|
379
|
sharedContext?: Context |
|
380
|
): Promise<PaymentCollectionDTO[]> |
|
381
|
|
|
382
|
// Should we remove this and use `updatePaymentCollections` instead? |
|
383
|
@InjectManager() |
|
384
|
@EmitEvents() |
|
385
|
async completePaymentCollections( |
|
386
|
paymentCollectionId: string | string[], |
|
387
|
@MedusaContext() sharedContext?: Context |
|
388
|
): Promise<PaymentCollectionDTO | PaymentCollectionDTO[]> { |
|
389
|
const input = Array.isArray(paymentCollectionId) |
|
390
|
? paymentCollectionId.map((id) => ({ |
|
391
|
id, |
|
392
|
completed_at: new Date(), |
|
393
|
})) |
|
394
|
: [{ id: paymentCollectionId, completed_at: new Date() }] |
|
395
|
|
|
396
|
// TODO: what checks should be done here? e.g. captured_amount === amount? |
|
397
|
|
|
398
|
const updated = await this.paymentCollectionService_.update( |
|
399
|
input, |
|
400
|
sharedContext |
|
401
|
) |
|
402
|
|
|
403
|
return await this.baseRepository_.serialize( |
|
404
|
Array.isArray(paymentCollectionId) ? updated : updated[0] |
|
405
|
) |
|
406
|
} |
|
407
|
|
|
408
|
@InjectManager() |
|
409
|
@EmitEvents() |
|
410
|
async createPaymentSession( |
|
411
|
paymentCollectionId: string, |
|
412
|
input: CreatePaymentSessionDTO, |
|
413
|
@MedusaContext() sharedContext?: Context |
|
414
|
): Promise<PaymentSessionDTO> { |
|
415
|
let paymentSession: InferEntityType<typeof PaymentSession> | undefined |
|
416
|
let providerPaymentSession: InitiatePaymentOutput | undefined |
|
417
|
|
|
418
|
try { |
|
419
|
paymentSession = await this.createPaymentSession_( |
|
420
|
paymentCollectionId, |
|
421
|
input, |
|
422
|
sharedContext |
|
423
|
) |
|
424
|
|
|
425
|
providerPaymentSession = await this.paymentProviderService_.createSession( |
|
426
|
input.provider_id, |
|
427
|
{ |
|
428
|
context: { |
|
429
|
idempotency_key: paymentSession!.id, |
|
430
|
...input.context, |
|
431
|
}, |
|
432
|
data: { ...input.data, session_id: paymentSession!.id }, |
|
433
|
amount: input.amount, |
|
434
|
currency_code: normalizeCurrencyCode(input.currency_code), |
|
435
|
} |
|
436
|
) |
|
437
|
|
|
438
|
paymentSession = await this.paymentSessionService_.update( |
|
439
|
{ |
|
440
|
id: paymentSession!.id, |
|
441
|
data: { ...input.data, ...providerPaymentSession.data }, |
|
442
|
status: providerPaymentSession.status ?? PaymentSessionStatus.PENDING, |
|
443
|
}, |
|
444
|
sharedContext |
|
445
|
) |
|
446
|
} catch (error) { |
|
447
|
if (providerPaymentSession) { |
|
448
|
await this.paymentProviderService_.deleteSession(input.provider_id, { |
|
449
|
data: input.data, |
|
450
|
}) |
|
451
|
} |
|
452
|
|
|
453
|
if (paymentSession) { |
|
454
|
await this.paymentSessionService_.delete( |
|
455
|
paymentSession.id, |
|
456
|
sharedContext |
|
457
|
) |
|
458
|
} |
|
459
|
|
|
460
|
throw error |
|
461
|
} |
|
462
|
|
|
463
|
return await this.baseRepository_.serialize(paymentSession) |
|
464
|
} |
|
465
|
|
|
466
|
@InjectTransactionManager() |
|
467
|
async createPaymentSession_( |
|
468
|
paymentCollectionId: string, |
|
469
|
data: CreatePaymentSessionDTO, |
|
470
|
@MedusaContext() sharedContext?: Context |
|
471
|
): Promise<InferEntityType<typeof PaymentSession>> { |
|
472
|
const paymentSession = await this.paymentSessionService_.create( |
|
473
|
{ |
|
474
|
payment_collection_id: paymentCollectionId, |
|
475
|
provider_id: data.provider_id, |
|
476
|
amount: data.amount, |
|
477
|
currency_code: normalizeCurrencyCode(data.currency_code), |
|
478
|
context: data.context, |
|
479
|
data: data.data, |
|
480
|
metadata: data.metadata, |
|
481
|
}, |
|
482
|
sharedContext |
|
483
|
) |
|
484
|
|
|
485
|
return paymentSession |
|
486
|
} |
|
487
|
|
|
488
|
@InjectManager() |
|
489
|
@EmitEvents() |
|
490
|
async updatePaymentSession( |
|
491
|
data: UpdatePaymentSessionDTO, |
|
492
|
@MedusaContext() sharedContext?: Context |
|
493
|
): Promise<PaymentSessionDTO> { |
|
494
|
const session = await this.paymentSessionService_.retrieve( |
|
495
|
data.id, |
|
496
|
{ select: ["id", "status", "data", "provider_id"] }, |
|
497
|
sharedContext |
|
498
|
) |
|
499
|
|
|
500
|
const providerData = await this.paymentProviderService_.updateSession( |
|
501
|
session.provider_id, |
|
502
|
{ |
|
503
|
data: data.data, |
|
504
|
amount: data.amount, |
|
505
|
currency_code: normalizeCurrencyCode(data.currency_code), |
|
506
|
context: data.context, |
|
507
|
} |
|
508
|
) |
|
509
|
|
|
510
|
const updated = await this.paymentSessionService_.update( |
|
511
|
{ |
|
512
|
id: session.id, |
|
513
|
amount: data.amount, |
|
514
|
currency_code: normalizeCurrencyCode(data.currency_code), |
|
515
|
data: providerData.data, |
|
516
|
// Allow the caller to explicitly set the status (eg. due to a webhook), fallback to the update response, and finally to the existing status. |
|
517
|
status: data.status ?? providerData.status ?? session.status, |
|
518
|
metadata: data.metadata, |
|
519
|
}, |
|
520
|
sharedContext |
|
521
|
) |
|
522
|
|
|
523
|
return await this.baseRepository_.serialize(updated) |
|
524
|
} |
|
525
|
|
|
526
|
@InjectManager() |
|
527
|
@EmitEvents() |
|
528
|
async deletePaymentSession( |
|
529
|
id: string, |
|
530
|
@MedusaContext() sharedContext?: Context |
|
531
|
): Promise<void> { |
|
532
|
const session = await this.paymentSessionService_.retrieve( |
|
533
|
id, |
|
534
|
{ select: ["id", "data", "provider_id"] }, |
|
535
|
sharedContext |
|
536
|
) |
|
537
|
|
|
538
|
await this.paymentProviderService_.deleteSession(session.provider_id, { |
|
539
|
data: session.data, |
|
540
|
}) |
|
541
|
|
|
542
|
await this.paymentSessionService_.delete(id, sharedContext) |
|
543
|
} |
|
544
|
|
|
545
|
@InjectManager() |
|
546
|
@EmitEvents() |
|
547
|
async authorizePaymentSession( |
|
548
|
id: string, |
|
549
|
context: Record<string, unknown>, |
|
550
|
@MedusaContext() sharedContext?: Context |
|
551
|
): Promise<PaymentDTO | null> { |
|
552
|
const session = await this.paymentSessionService_.retrieve( |
|
553
|
id, |
|
554
|
{ |
|
555
|
select: [ |
|
556
|
"id", |
|
557
|
"data", |
|
558
|
"provider_id", |
|
559
|
"amount", |
|
560
|
"raw_amount", |
|
561
|
"currency_code", |
|
562
|
"authorized_at", |
|
563
|
"payment_collection_id", |
|
564
|
], |
|
565
|
relations: ["payment", "payment_collection"], |
|
566
|
}, |
|
567
|
sharedContext |
|
568
|
) |
|
569
|
|
|
570
|
// this method needs to be idempotent |
|
571
|
if (session.payment && session.authorized_at) { |
|
572
|
return await this.baseRepository_.serialize<PaymentDTO>(session.payment) |
|
573
|
} |
|
574
|
|
|
575
|
let { data, status } = await this.paymentProviderService_.authorizePayment( |
|
576
|
session.provider_id, |
|
577
|
{ |
|
578
|
data: session.data, |
|
579
|
context: { idempotency_key: session.id, ...context }, |
|
580
|
} |
|
581
|
) |
|
582
|
|
|
583
|
if (status === PaymentSessionStatus.PENDING_AUTHORIZATION) { |
|
584
|
await this.paymentSessionService_.update( |
|
585
|
{ |
|
586
|
id: session.id, |
|
587
|
status, |
|
588
|
data, |
|
589
|
}, |
|
590
|
sharedContext |
|
591
|
) |
|
592
|
|
|
593
|
await this.maybeUpdatePaymentCollection_( |
|
594
|
session.payment_collection_id, |
|
595
|
sharedContext |
|
596
|
) |
|
597
|
|
|
598
|
return null |
|
599
|
} |
|
600
|
|
|
601
|
if ( |
|
602
|
status !== PaymentSessionStatus.AUTHORIZED && |
|
603
|
status !== PaymentSessionStatus.CAPTURED |
|
604
|
) { |
|
605
|
await this.paymentSessionService_.update( |
|
606
|
{ |
|
607
|
id: session.id, |
|
608
|
status, |
|
609
|
data, |
|
610
|
}, |
|
611
|
sharedContext |
|
612
|
) |
|
613
|
throw new MedusaError( |
|
614
|
MedusaError.Types.NOT_ALLOWED, |
|
615
|
`Session: ${session.id} was not authorized with the provider.` |
|
616
|
) |
|
617
|
} |
|
618
|
|
|
619
|
let payment |
|
620
|
try { |
|
621
|
payment = await this.authorizePaymentSession_( |
|
622
|
session, |
|
623
|
data, |
|
624
|
status as PaymentSessionStatus, |
|
625
|
sharedContext |
|
626
|
) |
|
627
|
} catch (error) { |
|
628
|
await this.paymentProviderService_.cancelPayment(session.provider_id, { |
|
629
|
data, |
|
630
|
context: { |
|
631
|
idempotency_key: payment?.id, |
|
632
|
...context, |
|
633
|
}, |
|
634
|
}) |
|
635
|
|
|
636
|
throw error |
|
637
|
} |
|
638
|
|
|
639
|
await this.maybeUpdatePaymentCollection_( |
|
640
|
session.payment_collection_id, |
|
641
|
sharedContext |
|
642
|
) |
|
643
|
|
|
644
|
return await this.baseRepository_.serialize<PaymentDTO>(payment) |
|
645
|
} |
|
646
|
|
|
647
|
@InjectTransactionManager() |
|
648
|
protected async authorizePaymentSession_( |
|
649
|
session: InferEntityType<typeof PaymentSession>, |
|
650
|
data: Record<string, unknown> | undefined, |
|
651
|
status: PaymentSessionStatus, |
|
652
|
@MedusaContext() sharedContext?: Context |
|
653
|
): Promise<InferEntityType<typeof Payment>> { |
|
654
|
let isCaptured = false |
|
655
|
if (status === PaymentSessionStatus.CAPTURED) { |
|
656
|
status = PaymentSessionStatus.AUTHORIZED |
|
657
|
isCaptured = true |
|
658
|
} |
|
659
|
|
|
660
|
await this.paymentSessionService_.update( |
|
661
|
{ |
|
662
|
id: session.id, |
|
663
|
data, |
|
664
|
status, |
|
665
|
...(session.authorized_at === null |
|
666
|
? { |
|
667
|
authorized_at: new Date(), |
|
668
|
} |
|
669
|
: {}), |
|
670
|
}, |
|
671
|
sharedContext |
|
672
|
) |
|
673
|
|
|
674
|
const payment = await this.paymentService_.create( |
|
675
|
{ |
|
676
|
amount: session.amount, |
|
677
|
currency_code: normalizeCurrencyCode(session.currency_code), |
|
678
|
payment_session: session.id, |
|
679
|
payment_collection_id: session.payment_collection_id, |
|
680
|
provider_id: session.provider_id, |
|
681
|
data, |
|
682
|
}, |
|
683
|
sharedContext |
|
684
|
) |
|
685
|
|
|
686
|
if (isCaptured) { |
|
687
|
await this.capturePayment( |
|
688
|
{ |
|
689
|
payment_id: payment.id, |
|
690
|
amount: session.amount as BigNumberInput, |
|
691
|
is_captured: isCaptured, |
|
692
|
}, |
|
693
|
sharedContext |
|
694
|
) |
|
695
|
} |
|
696
|
|
|
697
|
return payment |
|
698
|
} |
|
699
|
|
|
700
|
@InjectManager() |
|
701
|
@EmitEvents() |
|
702
|
async updatePayment( |
|
703
|
data: UpdatePaymentDTO, |
|
704
|
@MedusaContext() sharedContext?: Context |
|
705
|
): Promise<PaymentDTO> { |
|
706
|
// NOTE: currently there is no update with the provider but maybe data could be updated |
|
707
|
const result = await this.paymentService_.update(data, sharedContext) |
|
708
|
|
|
709
|
return await this.baseRepository_.serialize<PaymentDTO>(result) |
|
710
|
} |
|
711
|
|
|
712
|
// TODO: This method should return a capture, not a payment |
|
713
|
@InjectManager() |
|
714
|
@EmitEvents() |
|
715
|
async capturePayment( |
|
716
|
data: CreateCaptureDTO, |
|
717
|
@MedusaContext() sharedContext: Context = {} |
|
718
|
): Promise<PaymentDTO> { |
|
719
|
let { is_captured, ...data_ } = data |
|
720
|
const payment = await this.paymentService_.retrieve( |
|
721
|
data_.payment_id, |
|
722
|
{ |
|
723
|
select: [ |
|
724
|
"id", |
|
725
|
"data", |
|
726
|
"provider_id", |
|
727
|
"payment_collection_id", |
|
728
|
"amount", |
|
729
|
"raw_amount", |
|
730
|
"currency_code", |
|
731
|
"captured_at", |
|
732
|
"canceled_at", |
|
733
|
], |
|
734
|
relations: ["captures.raw_amount"], |
|
735
|
}, |
|
736
|
sharedContext |
|
737
|
) |
|
738
|
|
|
739
|
let isCaptured = is_captured |
|
740
|
if (!isCaptured) { |
|
741
|
const isAutoCaptured = !!payment?.captured_at |
|
742
|
isCaptured = isAutoCaptured |
|
743
|
} |
|
744
|
|
|
745
|
const { isFullyCaptured, capture } = await this.capturePayment_( |
|
746
|
data_, |
|
747
|
payment, |
|
748
|
sharedContext |
|
749
|
) |
|
750
|
|
|
751
|
try { |
|
752
|
await this.capturePaymentFromProvider_( |
|
753
|
payment, |
|
754
|
capture, |
|
755
|
{ isFullyCaptured, isCaptured }, |
|
756
|
sharedContext |
|
757
|
) |
|
758
|
} catch (error) { |
|
759
|
if (capture?.id) { |
|
760
|
await super.deleteCaptures({ id: capture.id }, sharedContext) |
|
761
|
} |
|
762
|
throw error |
|
763
|
} |
|
764
|
|
|
765
|
await this.maybeUpdatePaymentCollection_( |
|
766
|
payment.payment_collection_id, |
|
767
|
sharedContext |
|
768
|
) |
|
769
|
|
|
770
|
// Re-fetch the payment so the freshly created capture is reflected in the |
|
771
|
// returned payload. `refresh` is required because, under the select-in load |
|
772
|
// strategy, the capture created above is not automatically re-populated on |
|
773
|
// the managed payment entity within the same context. |
|
774
|
const capturedPayment = await this.paymentService_.retrieve( |
|
775
|
payment.id, |
|
776
|
{ relations: ["captures"], options: { refresh: true } }, |
|
777
|
sharedContext |
|
778
|
) |
|
779
|
|
|
780
|
return await this.baseRepository_.serialize(capturedPayment) |
|
781
|
} |
|
782
|
|
|
783
|
@InjectTransactionManager() |
|
784
|
protected async capturePayment_( |
|
785
|
data: CreateCaptureDTO, |
|
786
|
payment: InferEntityType<typeof Payment>, |
|
787
|
@MedusaContext() sharedContext: Context = {} |
|
788
|
): Promise<{ |
|
789
|
isFullyCaptured: boolean |
|
790
|
capture?: InferEntityType<typeof Capture> |
|
791
|
}> { |
|
792
|
if (payment.canceled_at) { |
|
793
|
throw new MedusaError( |
|
794
|
MedusaError.Types.INVALID_DATA, |
|
795
|
`The payment: ${payment.id} has been canceled.` |
|
796
|
) |
|
797
|
} |
|
798
|
|
|
799
|
if (payment.captured_at) { |
|
800
|
return { isFullyCaptured: true } |
|
801
|
} |
|
802
|
|
|
803
|
// If no custom amount is passed, we assume the full amount needs to be |
|
804
|
// captured. An explicit amount, however, must be strictly positive. |
|
805
|
if (data.amount == null) { |
|
806
|
data.amount = payment.amount as number |
|
807
|
} else if (MathBN.lte(data.amount, 0)) { |
|
808
|
throw new MedusaError( |
|
809
|
MedusaError.Types.INVALID_DATA, |
|
810
|
`Capture amount must be greater than 0.` |
|
811
|
) |
|
812
|
} |
|
813
|
|
|
814
|
// Serialize concurrent captures on the same payment: lock the payment row |
|
815
|
// for the remainder of this transaction so the read-check-write below runs |
|
816
|
// as a critical section, then re-read the captures under the lock so the |
|
817
|
// guard sees the committed total. Without this, two concurrent captures both |
|
818
|
// read a stale total and each pass the guard, over-capturing the payment. |
|
819
|
// The provider is called afterwards from `capturePaymentFromProvider_` in a |
|
820
|
// separate context, so the lock is never held across the provider call. |
|
821
|
// The transaction context is required: a FOR UPDATE issued on a pooled |
|
822
|
// (autocommit) connection would release the lock immediately and silently |
|
823
|
// stop serializing, so fail explicitly instead of falling back. |
|
824
|
const manager = sharedContext.transactionManager as SqlEntityManager |
|
825
|
const knex = manager?.getTransactionContext() |
|
826
|
if (!knex) { |
|
827
|
throw new MedusaError( |
|
828
|
MedusaError.Types.UNEXPECTED_STATE, |
|
829
|
"capturePayment_ must run inside a transaction to serialize concurrent captures." |
|
830
|
) |
|
831
|
} |
|
832
|
// Bound the wait for the row lock so a contended capture fails fast instead |
|
833
|
// of hanging: `SET LOCAL` scopes the timeout to this transaction. |
|
834
|
await knex.raw("SET LOCAL lock_timeout = '3s'") |
|
835
|
await knex("payment").where("id", payment.id).forUpdate().select("id") |
|
836
|
|
|
837
|
const lockedPayment = await this.paymentService_.retrieve( |
|
838
|
data.payment_id, |
|
839
|
{ select: ["id"], relations: ["captures.raw_amount"] }, |
|
840
|
sharedContext |
|
841
|
) |
|
842
|
const capturedAmount = lockedPayment.captures.reduce((captureAmount, next) => { |
|
843
|
return MathBN.add(captureAmount, next.raw_amount as BigNumberInput) |
|
844
|
}, MathBN.convert(0)) |
|
845
|
|
|
846
|
const authorizedAmount = new BigNumber(payment.raw_amount as BigNumberInput) |
|
847
|
const newCaptureAmount = new BigNumber(data.amount) |
|
848
|
const remainingToCapture = MathBN.sub(authorizedAmount, capturedAmount) |
|
849
|
|
|
850
|
if ( |
|
851
|
MathBN.gt( |
|
852
|
this.roundToCurrencyPrecision(newCaptureAmount, payment.currency_code), |
|
853
|
this.roundToCurrencyPrecision(remainingToCapture, payment.currency_code) |
|
854
|
) |
|
855
|
) { |
|
856
|
throw new MedusaError( |
|
857
|
MedusaError.Types.INVALID_DATA, |
|
858
|
`You cannot capture more than the authorized amount substracted by what is already captured.` |
|
859
|
) |
|
860
|
} |
|
861
|
|
|
862
|
// When the entire authorized amount has been captured, we return it as complete |
|
863
|
const totalCaptured = MathBN.convert( |
|
864
|
MathBN.add(capturedAmount, newCaptureAmount) |
|
865
|
) |
|
866
|
const isFullyCaptured = MathBN.gte( |
|
867
|
this.roundToCurrencyPrecision(totalCaptured, payment.currency_code), |
|
868
|
this.roundToCurrencyPrecision(authorizedAmount, payment.currency_code) |
|
869
|
) |
|
870
|
|
|
871
|
const capture = await this.captureService_.create( |
|
872
|
{ |
|
873
|
payment: data.payment_id, |
|
874
|
amount: data.amount, |
|
875
|
created_by: data.captured_by, |
|
876
|
}, |
|
877
|
sharedContext |
|
878
|
) |
|
879
|
|
|
880
|
return { isFullyCaptured, capture } |
|
881
|
} |
|
882
|
|
|
883
|
@InjectManager() |
|
884
|
protected async capturePaymentFromProvider_( |
|
885
|
payment: InferEntityType<typeof Payment>, |
|
886
|
capture: InferEntityType<typeof Capture> | undefined, |
|
887
|
options: { |
|
888
|
isFullyCaptured?: boolean |
|
889
|
isCaptured?: boolean |
|
890
|
} = {}, |
|
891
|
@MedusaContext() sharedContext: Context = {} |
|
892
|
) { |
|
893
|
if (!options.isCaptured) { |
|
894
|
const paymentData = await this.paymentProviderService_.capturePayment( |
|
895
|
payment.provider_id, |
|
896
|
{ |
|
897
|
data: payment.data!, |
|
898
|
context: { |
|
899
|
idempotency_key: capture?.id, |
|
900
|
}, |
|
901
|
} |
|
902
|
) |
|
903
|
|
|
904
|
await this.paymentService_.update( |
|
905
|
{ |
|
906
|
id: payment.id, |
|
907
|
data: paymentData.data, |
|
908
|
captured_at: options.isFullyCaptured ? new Date() : undefined, |
|
909
|
}, |
|
910
|
sharedContext |
|
911
|
) |
|
912
|
} else if (options.isFullyCaptured && !payment.captured_at) { |
|
913
|
/** |
|
914
|
* In the case of auto capture, we need to update the payment to set the captured_at date |
|
915
|
* only if fully captured. |
|
916
|
*/ |
|
917
|
await this.paymentService_.update( |
|
918
|
{ |
|
919
|
id: payment.id, |
|
920
|
captured_at: new Date(), |
|
921
|
}, |
|
922
|
sharedContext |
|
923
|
) |
|
924
|
} |
|
925
|
|
|
926
|
return payment |
|
927
|
} |
|
928
|
|
|
929
|
@InjectManager() |
|
930
|
@EmitEvents() |
|
931
|
async refundPayment( |
|
932
|
data: CreateRefundDTO, |
|
933
|
@MedusaContext() sharedContext: Context = {} |
|
934
|
): Promise<PaymentDTO> { |
|
935
|
const payment = await this.paymentService_.retrieve( |
|
936
|
data.payment_id, |
|
937
|
{ |
|
938
|
select: [ |
|
939
|
"id", |
|
940
|
"currency_code", |
|
941
|
"data", |
|
942
|
"provider_id", |
|
943
|
"payment_collection_id", |
|
944
|
"amount", |
|
945
|
"raw_amount", |
|
946
|
], |
|
947
|
relations: ["captures.raw_amount", "refunds.raw_amount"], |
|
948
|
}, |
|
949
|
sharedContext |
|
950
|
) |
|
951
|
const { refund, alreadyRefunded } = await this.refundPayment_( |
|
952
|
payment, |
|
953
|
data, |
|
954
|
sharedContext |
|
955
|
) |
|
956
|
|
|
957
|
if (!alreadyRefunded) { |
|
958
|
try { |
|
959
|
await this.refundPaymentFromProvider_(payment, refund, sharedContext) |
|
960
|
} catch (error) { |
|
961
|
// Soft-deleted rather than deleted: the row is the only record that a |
|
962
|
// request reached the provider, and its id backs the idempotency key a |
|
963
|
// retry has to reuse. Soft-deleting keeps it out of every refund total |
|
964
|
// without each caller having to filter it out. |
|
965
|
await this.refundService_.update( |
|
966
|
{ id: refund.id, status: RefundStatus.FAILED }, |
|
967
|
sharedContext |
|
968
|
) |
|
969
|
await this.refundService_.softDelete({ id: refund.id }, sharedContext) |
|
970
|
throw error |
|
971
|
} |
|
972
|
|
|
973
|
await this.refundService_.update( |
|
974
|
{ id: refund.id, status: RefundStatus.SUCCEEDED }, |
|
975
|
sharedContext |
|
976
|
) |
|
977
|
|
|
978
|
await this.maybeUpdatePaymentCollection_( |
|
979
|
payment.payment_collection_id, |
|
980
|
sharedContext |
|
981
|
) |
|
982
|
} |
|
983
|
|
|
984
|
return await this.retrievePayment( |
|
985
|
payment.id, |
|
986
|
{ relations: ["refunds"] }, |
|
987
|
sharedContext |
|
988
|
) |
|
989
|
} |
|
990
|
|
|
991
|
/** |
|
992
|
* Decides whether a refund request is a new refund, a retry of a failed one, |
|
993
|
* or a replay of one that already went through. Only a request carrying an |
|
994
|
* `idempotency_key` can be anything but a new refund. |
|
995
|
* |
|
996
|
* Throws when the request collides with an attempt that is still waiting on |
|
997
|
* the provider: the outcome of that attempt isn't known yet, so neither |
|
998
|
* answer a replay could be given would be true. |
|
999
|
*/ |
|
1000
|
private resolveRefundRequest_( |
|
1001
|
refunds: InferEntityType<typeof Refund>[], |
|
1002
|
data: CreateRefundDTO |
|
1003
|
): { resume?: InferEntityType<typeof Refund>; replayed: boolean } { |
|
1004
|
if (data.idempotency_key) { |
|
1005
|
const match = refunds.find( |
|
1006
|
(refund) => refund.idempotency_key === data.idempotency_key |
|
1007
|
) |
|
1008
|
|
|
1009
|
if (!match) { |
|
1010
|
return { replayed: false } |
|
1011
|
} |
|
1012
|
|
|
1013
|
if (!MathBN.eq(match.raw_amount as BigNumberInput, data.amount!)) { |
|
1014
|
throw new MedusaError( |
|
1015
|
MedusaError.Types.INVALID_DATA, |
|
1016
|
`A refund with idempotency key ${data.idempotency_key} already exists on payment ${data.payment_id} for a different amount.` |
|
1017
|
) |
|
1018
|
} |
|
1019
|
|
|
1020
|
if (match.status === RefundStatus.PENDING) { |
|
1021
|
// A pending refund is normally an attempt still waiting on the provider, |
|
1022
|
// and its outcome isn't known yet. But an attempt whose process died |
|
1023
|
// between the provider call and the status update would stay pending |
|
1024
|
// forever and lock the key out, so past a grace period the refund is |
|
1025
|
// retried instead: the provider sees the same key, which is what makes |
|
1026
|
// re-sending it safe. |
|
1027
|
const startedAt = (match.updated_at ?? match.created_at) as Date |
|
1028
|
const isStale = |
|
1029
|
Date.now() - new Date(startedAt).getTime() > |
|
1030
|
PENDING_REFUND_RECOVERY_MS |
|
1031
|
|
|
1032
|
if (!isStale) { |
|
1033
|
throw new MedusaError( |
|
1034
|
MedusaError.Types.CONFLICT, |
|
1035
|
`A refund with idempotency key ${data.idempotency_key} is still in progress on payment ${data.payment_id}.` |
|
1036
|
) |
|
1037
|
} |
|
1038
|
|
|
1039
|
return { resume: match, replayed: false } |
|
1040
|
} |
|
1041
|
|
|
1042
|
return match.status === RefundStatus.SUCCEEDED |
|
1043
|
? { resume: match, replayed: true } |
|
1044
|
: { resume: match, replayed: false } |
|
1045
|
} |
|
1046
|
|
|
1047
|
// Without a key there is nothing to match a retry against: two refunds of |
|
1048
|
// the same amount are indistinguishable from one refund sent twice. Such a |
|
1049
|
// request always starts a new refund, as it did before refunds could be |
|
1050
|
// resumed at all. |
|
1051
|
return { replayed: false } |
|
1052
|
} |
|
1053
|
|
|
1054
|
@InjectTransactionManager() |
|
1055
|
private async refundPayment_( |
|
1056
|
payment: InferEntityType<typeof Payment>, |
|
1057
|
data: CreateRefundDTO, |
|
1058
|
@MedusaContext() sharedContext: Context = {} |
|
1059
|
): Promise<{ |
|
1060
|
refund: InferEntityType<typeof Refund> |
|
1061
|
alreadyRefunded: boolean |
|
1062
|
}> { |
|
1063
|
// If no amount is passed, we assume the full payment amount needs to be |
|
1064
|
// refunded. An explicit amount, however, must be strictly positive. |
|
1065
|
if (data.amount == null) { |
|
1066
|
data.amount = payment.amount as BigNumberInput |
|
1067
|
} else if (MathBN.lte(data.amount, 0)) { |
|
1068
|
throw new MedusaError( |
|
1069
|
MedusaError.Types.INVALID_DATA, |
|
1070
|
`Refund amount must be greater than 0.` |
|
1071
|
) |
|
1072
|
} |
|
1073
|
|
|
1074
|
// Serialize concurrent refunds on the same payment: lock the payment row for |
|
1075
|
// the remainder of this transaction so the read-check-write below runs as a |
|
1076
|
// critical section, then re-read captures and refunds under the lock so the |
|
1077
|
// guard sees committed totals. Without this, two concurrent refunds both read |
|
1078
|
// a stale refunded total and each pass the guard, over-refunding the payment. |
|
1079
|
// The provider is called afterwards from `refundPaymentFromProvider_` in a |
|
1080
|
// separate context, so the lock is never held across the provider call. |
|
1081
|
// The transaction context is required: a FOR UPDATE issued on a pooled |
|
1082
|
// (autocommit) connection would release the lock immediately and silently |
|
1083
|
// stop serializing, so fail explicitly instead of falling back. |
|
1084
|
const manager = sharedContext.transactionManager as SqlEntityManager |
|
1085
|
const knex = manager?.getTransactionContext() |
|
1086
|
if (!knex) { |
|
1087
|
throw new MedusaError( |
|
1088
|
MedusaError.Types.UNEXPECTED_STATE, |
|
1089
|
"refundPayment_ must run inside a transaction to serialize concurrent refunds." |
|
1090
|
) |
|
1091
|
} |
|
1092
|
// Bound the wait for the row lock so a contended refund fails fast instead |
|
1093
|
// of hanging: `SET LOCAL` scopes the timeout to this transaction. |
|
1094
|
await knex.raw("SET LOCAL lock_timeout = '3s'") |
|
1095
|
await knex("payment").where("id", payment.id).forUpdate().select("id") |
|
1096
|
|
|
1097
|
const lockedPayment = await this.paymentService_.retrieve( |
|
1098
|
data.payment_id, |
|
1099
|
{ |
|
1100
|
select: ["id"], |
|
1101
|
relations: ["captures.raw_amount", "refunds"], |
|
1102
|
// Soft-deleted refunds are the failed attempts a retry resumes, so |
|
1103
|
// they have to be visible here even though they count for nothing. |
|
1104
|
filters: { [SoftDeletableFilterKey]: { withDeleted: true } }, |
|
1105
|
}, |
|
1106
|
sharedContext |
|
1107
|
) |
|
1108
|
|
|
1109
|
const { resume, replayed } = this.resolveRefundRequest_( |
|
1110
|
lockedPayment.refunds, |
|
1111
|
data |
|
1112
|
) |
|
1113
|
|
|
1114
|
// A replay moves no additional funds, so it skips the guard below: the |
|
1115
|
// amount it refunded is already part of the payment's refunded total. |
|
1116
|
if (replayed) { |
|
1117
|
return { refund: resume!, alreadyRefunded: true } |
|
1118
|
} |
|
1119
|
|
|
1120
|
const capturedAmount = lockedPayment.captures.reduce((captureAmount, next) => { |
|
1121
|
const amountAsBigNumber = new BigNumber(next.raw_amount as BigNumberInput) |
|
1122
|
return MathBN.add(captureAmount, amountAsBigNumber) |
|
1123
|
}, MathBN.convert(0)) |
|
1124
|
// The refund being resumed is excluded: a soft-deleted one counts for |
|
1125
|
// nothing already, and a stale pending one is this same refund rather than |
|
1126
|
// an additional one, so leaving it in would double-count `data.amount`. |
|
1127
|
const refundedAmount = lockedPayment.refunds |
|
1128
|
.filter((refund) => !refund.deleted_at && refund.id !== resume?.id) |
|
1129
|
.reduce((refundedAmount, next) => { |
|
1130
|
return MathBN.add(refundedAmount, next.raw_amount as BigNumberInput) |
|
1131
|
}, MathBN.convert(0)) |
|
1132
|
|
|
1133
|
const totalRefundedAmount = MathBN.add(refundedAmount, data.amount) |
|
1134
|
|
|
1135
|
const upperCurCode = payment.currency_code?.toUpperCase() as string |
|
1136
|
const currencyEpsilon = getEpsilonFromDecimalPrecision( |
|
1137
|
defaultCurrencies[upperCurCode]?.decimal_digits |
|
1138
|
) |
|
1139
|
|
|
1140
|
if ( |
|
1141
|
MathBN.lt( |
|
1142
|
MathBN.sub(capturedAmount, totalRefundedAmount), |
|
1143
|
-currencyEpsilon |
|
1144
|
) |
|
1145
|
) { |
|
1146
|
throw new MedusaError( |
|
1147
|
MedusaError.Types.INVALID_DATA, |
|
1148
|
`You cannot refund more than what is captured on the payment.` |
|
1149
|
) |
|
1150
|
} |
|
1151
|
|
|
1152
|
// Resumed only after the guard: a failed refund counts for nothing while it |
|
1153
|
// is soft-deleted, so restoring it adds its amount back to the refunded |
|
1154
|
// total and can push the payment past what was captured. |
|
1155
|
if (resume) { |
|
1156
|
if (resume.deleted_at) { |
|
1157
|
// Restored before the status is set: an update can't see a soft-deleted |
|
1158
|
// row, so the order here is load-bearing. |
|
1159
|
await this.refundService_.restore({ id: resume.id }, sharedContext) |
|
1160
|
} |
|
1161
|
|
|
1162
|
const restored = await this.refundService_.update( |
|
1163
|
{ id: resume.id, status: RefundStatus.PENDING }, |
|
1164
|
sharedContext |
|
1165
|
) |
|
1166
|
|
|
1167
|
return { refund: restored, alreadyRefunded: false } |
|
1168
|
} |
|
1169
|
|
|
1170
|
const refund = await this.refundService_.create( |
|
1171
|
{ |
|
1172
|
payment: data.payment_id, |
|
1173
|
amount: data.amount, |
|
1174
|
created_by: data.created_by, |
|
1175
|
note: data.note, |
|
1176
|
refund_reason_id: data.refund_reason_id, |
|
1177
|
metadata: data.metadata, |
|
1178
|
idempotency_key: data.idempotency_key, |
|
1179
|
status: RefundStatus.PENDING, |
|
1180
|
}, |
|
1181
|
sharedContext |
|
1182
|
) |
|
1183
|
|
|
1184
|
return { refund, alreadyRefunded: false } |
|
1185
|
} |
|
1186
|
|
|
1187
|
@InjectManager() |
|
1188
|
protected async refundPaymentFromProvider_( |
|
1189
|
payment: InferEntityType<typeof Payment>, |
|
1190
|
refund: InferEntityType<typeof Refund>, |
|
1191
|
@MedusaContext() sharedContext: Context = {} |
|
1192
|
) { |
|
1193
|
const paymentData = await this.paymentProviderService_.refundPayment( |
|
1194
|
payment.provider_id, |
|
1195
|
{ |
|
1196
|
data: payment.data!, |
|
1197
|
amount: refund.raw_amount as BigNumberInput, |
|
1198
|
context: { |
|
1199
|
idempotency_key: refund.idempotency_key ?? refund.id, |
|
1200
|
}, |
|
1201
|
} |
|
1202
|
) |
|
1203
|
|
|
1204
|
await this.paymentService_.update( |
|
1205
|
{ id: payment.id, data: paymentData.data }, |
|
1206
|
sharedContext |
|
1207
|
) |
|
1208
|
|
|
1209
|
return payment |
|
1210
|
} |
|
1211
|
|
|
1212
|
@InjectManager() |
|
1213
|
@EmitEvents() |
|
1214
|
async cancelPayment( |
|
1215
|
paymentId: string, |
|
1216
|
@MedusaContext() sharedContext?: Context |
|
1217
|
): Promise<PaymentDTO> { |
|
1218
|
const payment = await this.paymentService_.retrieve( |
|
1219
|
paymentId, |
|
1220
|
{ select: ["id", "data", "provider_id"] }, |
|
1221
|
sharedContext |
|
1222
|
) |
|
1223
|
|
|
1224
|
const { data } = await this.paymentProviderService_.cancelPayment( |
|
1225
|
payment.provider_id, |
|
1226
|
{ |
|
1227
|
data: payment.data!, |
|
1228
|
context: { |
|
1229
|
idempotency_key: payment.id, |
|
1230
|
}, |
|
1231
|
} |
|
1232
|
) |
|
1233
|
|
|
1234
|
await this.paymentService_.update( |
|
1235
|
{ id: paymentId, canceled_at: new Date(), data }, |
|
1236
|
sharedContext |
|
1237
|
) |
|
1238
|
|
|
1239
|
return await this.retrievePayment(payment.id, {}, sharedContext) |
|
1240
|
} |
|
1241
|
|
|
1242
|
@InjectManager() |
|
1243
|
protected async maybeUpdatePaymentCollection_( |
|
1244
|
paymentCollectionId: string, |
|
1245
|
sharedContext?: Context |
|
1246
|
) { |
|
1247
|
const paymentCollection = await this.paymentCollectionService_.retrieve( |
|
1248
|
paymentCollectionId, |
|
1249
|
{ |
|
1250
|
select: ["amount", "raw_amount", "status", "currency_code"], |
|
1251
|
// Use relation paths (not scalar field paths such as |
|
1252
|
// "payment_sessions.amount") so the select-in load strategy populates |
|
1253
|
// the nested collections. `refresh` forces the collections to be |
|
1254
|
// re-hydrated from the database: this runs inside the write transaction |
|
1255
|
// right after sessions/captures/refunds were created, and select-in |
|
1256
|
// does not otherwise re-populate collections that are already loaded on |
|
1257
|
// the managed entities in the shared context. |
|
1258
|
relations: ["payment_sessions", "payments.captures", "payments.refunds"], |
|
1259
|
options: { refresh: true }, |
|
1260
|
}, |
|
1261
|
sharedContext |
|
1262
|
) |
|
1263
|
|
|
1264
|
const paymentSessions = paymentCollection.payment_sessions |
|
1265
|
const captures = paymentCollection.payments |
|
1266
|
.map((pay) => [...pay.captures]) |
|
1267
|
.flat() |
|
1268
|
const refunds = paymentCollection.payments |
|
1269
|
.map((pay) => [...pay.refunds]) |
|
1270
|
.flat() |
|
1271
|
|
|
1272
|
let authorizedAmount = MathBN.convert(0) |
|
1273
|
let capturedAmount = MathBN.convert(0) |
|
1274
|
let refundedAmount = MathBN.convert(0) |
|
1275
|
let completedAt: Date | undefined |
|
1276
|
|
|
1277
|
for (const ps of paymentSessions) { |
|
1278
|
if (ps.status === PaymentSessionStatus.AUTHORIZED) { |
|
1279
|
authorizedAmount = MathBN.add(authorizedAmount, ps.amount) |
|
1280
|
} |
|
1281
|
} |
|
1282
|
|
|
1283
|
for (const capture of captures) { |
|
1284
|
capturedAmount = MathBN.add(capturedAmount, capture.amount) |
|
1285
|
} |
|
1286
|
|
|
1287
|
for (const refund of refunds) { |
|
1288
|
refundedAmount = MathBN.add(refundedAmount, refund.amount) |
|
1289
|
} |
|
1290
|
|
|
1291
|
let status = |
|
1292
|
paymentSessions.length === 0 |
|
1293
|
? PaymentCollectionStatus.NOT_PAID |
|
1294
|
: PaymentCollectionStatus.AWAITING |
|
1295
|
|
|
1296
|
if (MathBN.gt(authorizedAmount, 0)) { |
|
1297
|
status = MathBN.gte( |
|
1298
|
this.roundToCurrencyPrecision( |
|
1299
|
authorizedAmount, |
|
1300
|
paymentCollection.currency_code |
|
1301
|
), |
|
1302
|
this.roundToCurrencyPrecision( |
|
1303
|
paymentCollection.amount, |
|
1304
|
paymentCollection.currency_code |
|
1305
|
) |
|
1306
|
) |
|
1307
|
? PaymentCollectionStatus.AUTHORIZED |
|
1308
|
: PaymentCollectionStatus.PARTIALLY_AUTHORIZED |
|
1309
|
} |
|
1310
|
|
|
1311
|
if ( |
|
1312
|
MathBN.gte( |
|
1313
|
this.roundToCurrencyPrecision( |
|
1314
|
capturedAmount, |
|
1315
|
paymentCollection.currency_code |
|
1316
|
), |
|
1317
|
this.roundToCurrencyPrecision( |
|
1318
|
paymentCollection.amount, |
|
1319
|
paymentCollection.currency_code |
|
1320
|
) |
|
1321
|
) |
|
1322
|
) { |
|
1323
|
status = PaymentCollectionStatus.COMPLETED |
|
1324
|
completedAt = new Date() |
|
1325
|
} |
|
1326
|
|
|
1327
|
await this.paymentCollectionService_.update( |
|
1328
|
{ |
|
1329
|
id: paymentCollectionId, |
|
1330
|
status, |
|
1331
|
authorized_amount: authorizedAmount, |
|
1332
|
captured_amount: capturedAmount, |
|
1333
|
refunded_amount: refundedAmount, |
|
1334
|
completed_at: completedAt, |
|
1335
|
}, |
|
1336
|
sharedContext |
|
1337
|
) |
|
1338
|
} |
|
1339
|
|
|
1340
|
@InjectManager() |
|
1341
|
async listPaymentProviders( |
|
1342
|
filters: FilterablePaymentProviderProps = {}, |
|
1343
|
config: FindConfig<PaymentProviderDTO> = {}, |
|
1344
|
@MedusaContext() sharedContext?: Context |
|
1345
|
): Promise<PaymentProviderDTO[]> { |
|
1346
|
const providers = await this.paymentProviderService_.list( |
|
1347
|
filters, |
|
1348
|
config, |
|
1349
|
sharedContext |
|
1350
|
) |
|
1351
|
|
|
1352
|
return await this.baseRepository_.serialize<PaymentProviderDTO[]>( |
|
1353
|
providers, |
|
1354
|
{ |
|
1355
|
populate: true, |
|
1356
|
} |
|
1357
|
) |
|
1358
|
} |
|
1359
|
|
|
1360
|
@InjectManager() |
|
1361
|
async listAndCountPaymentProviders( |
|
1362
|
filters: FilterablePaymentProviderProps = {}, |
|
1363
|
config: FindConfig<PaymentProviderDTO> = {}, |
|
1364
|
@MedusaContext() sharedContext?: Context |
|
1365
|
): Promise<[PaymentProviderDTO[], number]> { |
|
1366
|
const [providers, count] = await this.paymentProviderService_.listAndCount( |
|
1367
|
filters, |
|
1368
|
config, |
|
1369
|
sharedContext |
|
1370
|
) |
|
1371
|
|
|
1372
|
return [ |
|
1373
|
await this.baseRepository_.serialize<PaymentProviderDTO[]>(providers, { |
|
1374
|
populate: true, |
|
1375
|
}), |
|
1376
|
count, |
|
1377
|
] |
|
1378
|
} |
|
1379
|
|
|
1380
|
@InjectManager() |
|
1381
|
@EmitEvents() |
|
1382
|
async createAccountHolder( |
|
1383
|
input: CreateAccountHolderDTO, |
|
1384
|
@MedusaContext() sharedContext?: Context |
|
1385
|
): Promise<AccountHolderDTO> { |
|
1386
|
if (input.context?.account_holder) { |
|
1387
|
return input.context.account_holder as AccountHolderDTO |
|
1388
|
} |
|
1389
|
|
|
1390
|
let accountHolder: InferEntityType<typeof AccountHolder> | undefined |
|
1391
|
let providerAccountHolder: CreateAccountHolderOutput | undefined |
|
1392
|
|
|
1393
|
providerAccountHolder = |
|
1394
|
await this.paymentProviderService_.createAccountHolder( |
|
1395
|
input.provider_id, |
|
1396
|
{ |
|
1397
|
context: { |
|
1398
|
idempotency_key: input.context?.customer?.id, |
|
1399
|
...input.context, |
|
1400
|
}, |
|
1401
|
} |
|
1402
|
) |
|
1403
|
|
|
1404
|
// This can be empty when either the method is not supported or an account holder wasn't created |
|
1405
|
if (isPresent(providerAccountHolder)) { |
|
1406
|
accountHolder = await this.accountHolderService_.create( |
|
1407
|
{ |
|
1408
|
external_id: providerAccountHolder.id, |
|
1409
|
email: input.context.customer?.email, |
|
1410
|
data: providerAccountHolder.data, |
|
1411
|
provider_id: input.provider_id, |
|
1412
|
}, |
|
1413
|
sharedContext |
|
1414
|
) |
|
1415
|
} |
|
1416
|
|
|
1417
|
return await this.baseRepository_.serialize(accountHolder) |
|
1418
|
} |
|
1419
|
|
|
1420
|
@InjectManager() |
|
1421
|
@EmitEvents() |
|
1422
|
async updateAccountHolder( |
|
1423
|
input: UpdateAccountHolderDTO, |
|
1424
|
@MedusaContext() sharedContext?: Context |
|
1425
|
): Promise<AccountHolderDTO> { |
|
1426
|
if (!input.context?.account_holder) { |
|
1427
|
throw new MedusaError( |
|
1428
|
MedusaError.Types.INVALID_DATA, |
|
1429
|
"Missing account holder data while updating account holder." |
|
1430
|
) |
|
1431
|
} |
|
1432
|
|
|
1433
|
let accountHolder: InferEntityType<typeof AccountHolder> | undefined |
|
1434
|
let providerAccountHolder: UpdateAccountHolderOutput | undefined |
|
1435
|
|
|
1436
|
providerAccountHolder = |
|
1437
|
await this.paymentProviderService_.updateAccountHolder( |
|
1438
|
input.provider_id, |
|
1439
|
{ |
|
1440
|
context: input.context, |
|
1441
|
} |
|
1442
|
) |
|
1443
|
|
|
1444
|
// The data field can be empty when either the method is not supported or an account holder wasn't updated |
|
1445
|
// We still want to do the update as we might only be updating the metadata |
|
1446
|
accountHolder = await this.accountHolderService_.update( |
|
1447
|
{ |
|
1448
|
id: input.id, |
|
1449
|
...(providerAccountHolder?.data |
|
1450
|
? { data: providerAccountHolder.data } |
|
1451
|
: {}), |
|
1452
|
metadata: input.metadata, |
|
1453
|
}, |
|
1454
|
sharedContext |
|
1455
|
) |
|
1456
|
|
|
1457
|
return await this.baseRepository_.serialize(accountHolder) |
|
1458
|
} |
|
1459
|
|
|
1460
|
@InjectManager() |
|
1461
|
@EmitEvents() |
|
1462
|
async deleteAccountHolder( |
|
1463
|
id: string, |
|
1464
|
@MedusaContext() sharedContext?: Context |
|
1465
|
): Promise<void> { |
|
1466
|
const accountHolder = await this.accountHolderService_.retrieve( |
|
1467
|
id, |
|
1468
|
{ select: ["id", "provider_id", "external_id", "email", "data"] }, |
|
1469
|
sharedContext |
|
1470
|
) |
|
1471
|
|
|
1472
|
await this.accountHolderService_.delete(id, sharedContext) |
|
1473
|
|
|
1474
|
await this.paymentProviderService_.deleteAccountHolder( |
|
1475
|
accountHolder.provider_id, |
|
1476
|
{ |
|
1477
|
context: { account_holder: accountHolder }, |
|
1478
|
} |
|
1479
|
) |
|
1480
|
} |
|
1481
|
|
|
1482
|
@InjectManager() |
|
1483
|
async listPaymentMethods( |
|
1484
|
filters: FilterablePaymentMethodProps, |
|
1485
|
config: FindConfig<PaymentMethodDTO> = {}, |
|
1486
|
@MedusaContext() sharedContext?: Context |
|
1487
|
): Promise<PaymentMethodDTO[]> { |
|
1488
|
const res = await this.paymentProviderService_.listPaymentMethods( |
|
1489
|
filters.provider_id, |
|
1490
|
{ context: filters.context } |
|
1491
|
) |
|
1492
|
|
|
1493
|
return res.map((item) => ({ |
|
1494
|
id: item.id, |
|
1495
|
data: item.data!, |
|
1496
|
provider_id: filters.provider_id, |
|
1497
|
})) |
|
1498
|
} |
|
1499
|
|
|
1500
|
@InjectManager() |
|
1501
|
async listAndCountPaymentMethods( |
|
1502
|
filters: FilterablePaymentMethodProps, |
|
1503
|
config: FindConfig<PaymentMethodDTO> = {}, |
|
1504
|
@MedusaContext() sharedContext?: Context |
|
1505
|
): Promise<[PaymentMethodDTO[], number]> { |
|
1506
|
const paymentMethods = |
|
1507
|
await this.paymentProviderService_.listPaymentMethods( |
|
1508
|
filters.provider_id, |
|
1509
|
{ context: filters.context } |
|
1510
|
) |
|
1511
|
|
|
1512
|
const normalizedResponse = paymentMethods.map((item) => ({ |
|
1513
|
id: item.id, |
|
1514
|
data: item.data!, |
|
1515
|
provider_id: filters.provider_id, |
|
1516
|
})) |
|
1517
|
|
|
1518
|
return [normalizedResponse, paymentMethods.length] |
|
1519
|
} |
|
1520
|
|
|
1521
|
createPaymentMethods( |
|
1522
|
data: CreatePaymentMethodDTO, |
|
1523
|
sharedContext?: Context |
|
1524
|
): Promise<PaymentMethodDTO> |
|
1525
|
|
|
1526
|
createPaymentMethods( |
|
1527
|
data: CreatePaymentMethodDTO[], |
|
1528
|
sharedContext?: Context |
|
1529
|
): Promise<PaymentMethodDTO[]> |
|
1530
|
|
|
1531
|
@InjectManager() |
|
1532
|
@EmitEvents() |
|
1533
|
async createPaymentMethods( |
|
1534
|
data: CreatePaymentMethodDTO | CreatePaymentMethodDTO[], |
|
1535
|
@MedusaContext() sharedContext?: Context |
|
1536
|
): Promise<PaymentMethodDTO | PaymentMethodDTO[]> { |
|
1537
|
const input = Array.isArray(data) ? data : [data] |
|
1538
|
|
|
1539
|
const result = await promiseAll( |
|
1540
|
input.map((item) => |
|
1541
|
this.paymentProviderService_.savePaymentMethod(item.provider_id, item) |
|
1542
|
), |
|
1543
|
{ aggregateErrors: true } |
|
1544
|
) |
|
1545
|
|
|
1546
|
const normalizedResponse = result.map((item, i) => { |
|
1547
|
return { |
|
1548
|
id: item.id, |
|
1549
|
data: item.data!, |
|
1550
|
provider_id: input[i].provider_id, |
|
1551
|
} |
|
1552
|
}) |
|
1553
|
|
|
1554
|
return Array.isArray(data) ? normalizedResponse : normalizedResponse[0] |
|
1555
|
} |
|
1556
|
|
|
1557
|
deletePaymentMethods( |
|
1558
|
data: DeletePaymentMethodDTO, |
|
1559
|
sharedContext?: Context |
|
1560
|
): Promise<void> |
|
1561
|
|
|
1562
|
deletePaymentMethods( |
|
1563
|
data: DeletePaymentMethodDTO[], |
|
1564
|
sharedContext?: Context |
|
1565
|
): Promise<void> |
|
1566
|
|
|
1567
|
@InjectManager() |
|
1568
|
@EmitEvents() |
|
1569
|
async deletePaymentMethods( |
|
1570
|
data: DeletePaymentMethodDTO | DeletePaymentMethodDTO[], |
|
1571
|
@MedusaContext() sharedContext?: Context |
|
1572
|
): Promise<void> { |
|
1573
|
const input = Array.isArray(data) ? data : [data] |
|
1574
|
|
|
1575
|
await promiseAll( |
|
1576
|
input.map((item) => |
|
1577
|
this.paymentProviderService_.deletePaymentMethod(item.provider_id, { |
|
1578
|
context: item.context, |
|
1579
|
data: { |
|
1580
|
...item.data, |
|
1581
|
id: item.id, |
|
1582
|
}, |
|
1583
|
}) |
|
1584
|
), |
|
1585
|
{ aggregateErrors: true } |
|
1586
|
) |
|
1587
|
} |
|
1588
|
|
|
1589
|
@InjectManager() |
|
1590
|
async getWebhookActionAndData( |
|
1591
|
eventData: ProviderWebhookPayload, |
|
1592
|
@MedusaContext() sharedContext?: Context |
|
1593
|
): Promise<WebhookActionResult> { |
|
1594
|
const providerId = eventData.provider.startsWith("pp_") |
|
1595
|
? eventData.provider |
|
1596
|
: `pp_${eventData.provider}` |
|
1597
|
|
|
1598
|
return await this.paymentProviderService_.getWebhookActionAndData( |
|
1599
|
providerId, |
|
1600
|
eventData.payload |
|
1601
|
) |
|
1602
|
} |
|
1603
|
} |