@easypayment/medusa-payment-paypal 1.1.2 → 1.2.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.medusa/server/src/admin/index.js +73 -73
- package/.medusa/server/src/admin/index.mjs +73 -73
- package/.medusa/server/src/api/middlewares.d.ts.map +1 -1
- package/.medusa/server/src/api/middlewares.js +16 -2
- package/.medusa/server/src/api/middlewares.js.map +1 -1
- package/.medusa/server/src/api/store/paypal/capture-order/route.d.ts.map +1 -1
- package/.medusa/server/src/api/store/paypal/capture-order/route.js +66 -13
- package/.medusa/server/src/api/store/paypal/capture-order/route.js.map +1 -1
- package/.medusa/server/src/api/store/paypal/create-order/route.d.ts.map +1 -1
- package/.medusa/server/src/api/store/paypal/create-order/route.js +11 -6
- package/.medusa/server/src/api/store/paypal/create-order/route.js.map +1 -1
- package/.medusa/server/src/api/utils/rate-limit.d.ts +13 -1
- package/.medusa/server/src/api/utils/rate-limit.d.ts.map +1 -1
- package/.medusa/server/src/api/utils/rate-limit.js +7 -5
- package/.medusa/server/src/api/utils/rate-limit.js.map +1 -1
- package/.medusa/server/src/jobs/paypal-webhook-retry.d.ts.map +1 -1
- package/.medusa/server/src/jobs/paypal-webhook-retry.js +4 -0
- package/.medusa/server/src/jobs/paypal-webhook-retry.js.map +1 -1
- package/.medusa/server/src/modules/paypal/payment-provider/base-provider.d.ts +15 -0
- package/.medusa/server/src/modules/paypal/payment-provider/base-provider.d.ts.map +1 -1
- package/.medusa/server/src/modules/paypal/payment-provider/base-provider.js +26 -0
- package/.medusa/server/src/modules/paypal/payment-provider/base-provider.js.map +1 -1
- package/.medusa/server/src/modules/paypal/payment-provider/card-service.d.ts.map +1 -1
- package/.medusa/server/src/modules/paypal/payment-provider/card-service.js +244 -169
- package/.medusa/server/src/modules/paypal/payment-provider/card-service.js.map +1 -1
- package/.medusa/server/src/modules/paypal/payment-provider/service.d.ts +0 -4
- package/.medusa/server/src/modules/paypal/payment-provider/service.d.ts.map +1 -1
- package/.medusa/server/src/modules/paypal/payment-provider/service.js +8 -25
- package/.medusa/server/src/modules/paypal/payment-provider/service.js.map +1 -1
- package/.medusa/server/src/modules/paypal/service.d.ts +2 -0
- package/.medusa/server/src/modules/paypal/service.d.ts.map +1 -1
- package/.medusa/server/src/modules/paypal/service.js +54 -13
- package/.medusa/server/src/modules/paypal/service.js.map +1 -1
- package/.medusa/server/src/modules/paypal/types/config.d.ts.map +1 -1
- package/.medusa/server/src/modules/paypal/types/config.js +13 -0
- package/.medusa/server/src/modules/paypal/types/config.js.map +1 -1
- package/.medusa/server/src/modules/paypal/utils/amounts.d.ts +1 -1
- package/.medusa/server/src/modules/paypal/utils/credential-resolver.d.ts.map +1 -1
- package/.medusa/server/src/modules/paypal/utils/credential-resolver.js +10 -34
- package/.medusa/server/src/modules/paypal/utils/credential-resolver.js.map +1 -1
- package/.medusa/server/src/modules/paypal/utils/metrics.d.ts +18 -0
- package/.medusa/server/src/modules/paypal/utils/metrics.d.ts.map +1 -0
- package/.medusa/server/src/modules/paypal/utils/metrics.js +45 -0
- package/.medusa/server/src/modules/paypal/utils/metrics.js.map +1 -0
- package/.medusa/server/src/modules/paypal/webhook-processor.d.ts +16 -0
- package/.medusa/server/src/modules/paypal/webhook-processor.d.ts.map +1 -1
- package/.medusa/server/src/modules/paypal/webhook-processor.js +85 -2
- package/.medusa/server/src/modules/paypal/webhook-processor.js.map +1 -1
- package/.medusa/server/src/subscribers/paypal-webhook-process.d.ts.map +1 -1
- package/.medusa/server/src/subscribers/paypal-webhook-process.js +4 -0
- package/.medusa/server/src/subscribers/paypal-webhook-process.js.map +1 -1
- package/CHANGELOG.md +208 -146
- package/README.md +175 -184
- package/package.json +91 -88
- package/src/api/middlewares.ts +16 -2
- package/src/api/store/paypal/capture-order/route.ts +83 -12
- package/src/api/store/paypal/create-order/route.ts +11 -7
- package/src/api/utils/rate-limit.ts +20 -5
- package/src/jobs/paypal-webhook-retry.ts +4 -0
- package/src/modules/paypal/payment-provider/base-provider.ts +31 -0
- package/src/modules/paypal/payment-provider/card-service.ts +84 -0
- package/src/modules/paypal/payment-provider/service.ts +12 -30
- package/src/modules/paypal/service.ts +1703 -1651
- package/src/modules/paypal/types/config.ts +16 -0
- package/src/modules/paypal/utils/credential-resolver.ts +9 -36
- package/src/modules/paypal/utils/metrics.ts +48 -0
- package/src/modules/paypal/webhook-processor.ts +101 -2
- package/src/subscribers/paypal-webhook-process.ts +4 -0
|
@@ -1,1651 +1,1703 @@
|
|
|
1
|
-
import { MedusaService } from "@medusajs/framework/utils"
|
|
2
|
-
import {
|
|
3
|
-
import {
|
|
4
|
-
import
|
|
5
|
-
import
|
|
6
|
-
import
|
|
7
|
-
import
|
|
8
|
-
import
|
|
9
|
-
import {
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
type
|
|
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
|
-
private
|
|
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
|
-
return
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
const
|
|
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
|
-
|
|
342
|
-
|
|
343
|
-
|
|
344
|
-
|
|
345
|
-
|
|
346
|
-
|
|
347
|
-
|
|
348
|
-
|
|
349
|
-
|
|
350
|
-
|
|
351
|
-
|
|
352
|
-
|
|
353
|
-
|
|
354
|
-
|
|
355
|
-
|
|
356
|
-
|
|
357
|
-
|
|
358
|
-
|
|
359
|
-
|
|
360
|
-
|
|
361
|
-
|
|
362
|
-
|
|
363
|
-
|
|
364
|
-
|
|
365
|
-
|
|
366
|
-
|
|
367
|
-
|
|
368
|
-
|
|
369
|
-
|
|
370
|
-
|
|
371
|
-
|
|
372
|
-
|
|
373
|
-
|
|
374
|
-
|
|
375
|
-
|
|
376
|
-
|
|
377
|
-
|
|
378
|
-
|
|
379
|
-
|
|
380
|
-
|
|
381
|
-
|
|
382
|
-
|
|
383
|
-
|
|
384
|
-
|
|
385
|
-
|
|
386
|
-
|
|
387
|
-
|
|
388
|
-
|
|
389
|
-
|
|
390
|
-
|
|
391
|
-
|
|
392
|
-
|
|
393
|
-
|
|
394
|
-
|
|
395
|
-
|
|
396
|
-
|
|
397
|
-
|
|
398
|
-
|
|
399
|
-
|
|
400
|
-
|
|
401
|
-
|
|
402
|
-
|
|
403
|
-
|
|
404
|
-
|
|
405
|
-
|
|
406
|
-
|
|
407
|
-
|
|
408
|
-
|
|
409
|
-
|
|
410
|
-
|
|
411
|
-
|
|
412
|
-
|
|
413
|
-
|
|
414
|
-
|
|
415
|
-
|
|
416
|
-
|
|
417
|
-
|
|
418
|
-
|
|
419
|
-
|
|
420
|
-
|
|
421
|
-
|
|
422
|
-
|
|
423
|
-
|
|
424
|
-
|
|
425
|
-
|
|
426
|
-
|
|
427
|
-
|
|
428
|
-
|
|
429
|
-
|
|
430
|
-
|
|
431
|
-
|
|
432
|
-
|
|
433
|
-
|
|
434
|
-
|
|
435
|
-
|
|
436
|
-
|
|
437
|
-
|
|
438
|
-
|
|
439
|
-
|
|
440
|
-
|
|
441
|
-
|
|
442
|
-
|
|
443
|
-
|
|
444
|
-
|
|
445
|
-
|
|
446
|
-
}
|
|
447
|
-
}
|
|
448
|
-
|
|
449
|
-
|
|
450
|
-
|
|
451
|
-
|
|
452
|
-
|
|
453
|
-
const
|
|
454
|
-
|
|
455
|
-
|
|
456
|
-
|
|
457
|
-
|
|
458
|
-
|
|
459
|
-
|
|
460
|
-
|
|
461
|
-
|
|
462
|
-
|
|
463
|
-
|
|
464
|
-
|
|
465
|
-
|
|
466
|
-
|
|
467
|
-
|
|
468
|
-
|
|
469
|
-
|
|
470
|
-
|
|
471
|
-
|
|
472
|
-
|
|
473
|
-
|
|
474
|
-
|
|
475
|
-
|
|
476
|
-
|
|
477
|
-
|
|
478
|
-
|
|
479
|
-
|
|
480
|
-
|
|
481
|
-
|
|
482
|
-
|
|
483
|
-
|
|
484
|
-
|
|
485
|
-
|
|
486
|
-
|
|
487
|
-
|
|
488
|
-
|
|
489
|
-
|
|
490
|
-
|
|
491
|
-
|
|
492
|
-
|
|
493
|
-
|
|
494
|
-
|
|
495
|
-
|
|
496
|
-
|
|
497
|
-
|
|
498
|
-
|
|
499
|
-
|
|
500
|
-
|
|
501
|
-
|
|
502
|
-
|
|
503
|
-
|
|
504
|
-
|
|
505
|
-
|
|
506
|
-
|
|
507
|
-
|
|
508
|
-
|
|
509
|
-
|
|
510
|
-
|
|
511
|
-
|
|
512
|
-
|
|
513
|
-
|
|
514
|
-
|
|
515
|
-
|
|
516
|
-
|
|
517
|
-
|
|
518
|
-
|
|
519
|
-
|
|
520
|
-
|
|
521
|
-
|
|
522
|
-
|
|
523
|
-
|
|
524
|
-
|
|
525
|
-
|
|
526
|
-
|
|
527
|
-
|
|
528
|
-
|
|
529
|
-
|
|
530
|
-
|
|
531
|
-
|
|
532
|
-
|
|
533
|
-
|
|
534
|
-
|
|
535
|
-
|
|
536
|
-
const
|
|
537
|
-
|
|
538
|
-
|
|
539
|
-
|
|
540
|
-
|
|
541
|
-
|
|
542
|
-
|
|
543
|
-
|
|
544
|
-
|
|
545
|
-
|
|
546
|
-
|
|
547
|
-
|
|
548
|
-
|
|
549
|
-
|
|
550
|
-
|
|
551
|
-
|
|
552
|
-
|
|
553
|
-
|
|
554
|
-
|
|
555
|
-
|
|
556
|
-
|
|
557
|
-
|
|
558
|
-
|
|
559
|
-
|
|
560
|
-
|
|
561
|
-
|
|
562
|
-
|
|
563
|
-
|
|
564
|
-
|
|
565
|
-
|
|
566
|
-
|
|
567
|
-
|
|
568
|
-
|
|
569
|
-
|
|
570
|
-
|
|
571
|
-
|
|
572
|
-
|
|
573
|
-
|
|
574
|
-
|
|
575
|
-
|
|
576
|
-
|
|
577
|
-
|
|
578
|
-
|
|
579
|
-
|
|
580
|
-
|
|
581
|
-
|
|
582
|
-
|
|
583
|
-
|
|
584
|
-
|
|
585
|
-
|
|
586
|
-
const
|
|
587
|
-
|
|
588
|
-
|
|
589
|
-
|
|
590
|
-
|
|
591
|
-
|
|
592
|
-
|
|
593
|
-
|
|
594
|
-
|
|
595
|
-
|
|
596
|
-
|
|
597
|
-
|
|
598
|
-
|
|
599
|
-
|
|
600
|
-
|
|
601
|
-
|
|
602
|
-
|
|
603
|
-
|
|
604
|
-
|
|
605
|
-
|
|
606
|
-
|
|
607
|
-
|
|
608
|
-
|
|
609
|
-
|
|
610
|
-
|
|
611
|
-
|
|
612
|
-
|
|
613
|
-
|
|
614
|
-
|
|
615
|
-
|
|
616
|
-
|
|
617
|
-
|
|
618
|
-
`
|
|
619
|
-
|
|
620
|
-
|
|
621
|
-
|
|
622
|
-
|
|
623
|
-
|
|
624
|
-
|
|
625
|
-
|
|
626
|
-
if (
|
|
627
|
-
|
|
628
|
-
|
|
629
|
-
|
|
630
|
-
|
|
631
|
-
|
|
632
|
-
|
|
633
|
-
|
|
634
|
-
|
|
635
|
-
|
|
636
|
-
|
|
637
|
-
|
|
638
|
-
|
|
639
|
-
|
|
640
|
-
|
|
641
|
-
|
|
642
|
-
|
|
643
|
-
|
|
644
|
-
|
|
645
|
-
|
|
646
|
-
|
|
647
|
-
|
|
648
|
-
|
|
649
|
-
|
|
650
|
-
|
|
651
|
-
|
|
652
|
-
|
|
653
|
-
|
|
654
|
-
|
|
655
|
-
|
|
656
|
-
|
|
657
|
-
|
|
658
|
-
|
|
659
|
-
|
|
660
|
-
|
|
661
|
-
|
|
662
|
-
|
|
663
|
-
|
|
664
|
-
|
|
665
|
-
|
|
666
|
-
|
|
667
|
-
|
|
668
|
-
|
|
669
|
-
|
|
670
|
-
|
|
671
|
-
|
|
672
|
-
|
|
673
|
-
|
|
674
|
-
|
|
675
|
-
|
|
676
|
-
|
|
677
|
-
|
|
678
|
-
|
|
679
|
-
|
|
680
|
-
|
|
681
|
-
|
|
682
|
-
|
|
683
|
-
|
|
684
|
-
const
|
|
685
|
-
|
|
686
|
-
|
|
687
|
-
|
|
688
|
-
|
|
689
|
-
|
|
690
|
-
|
|
691
|
-
|
|
692
|
-
|
|
693
|
-
|
|
694
|
-
|
|
695
|
-
|
|
696
|
-
|
|
697
|
-
|
|
698
|
-
|
|
699
|
-
|
|
700
|
-
|
|
701
|
-
|
|
702
|
-
|
|
703
|
-
|
|
704
|
-
|
|
705
|
-
|
|
706
|
-
|
|
707
|
-
|
|
708
|
-
|
|
709
|
-
|
|
710
|
-
|
|
711
|
-
|
|
712
|
-
|
|
713
|
-
|
|
714
|
-
|
|
715
|
-
|
|
716
|
-
|
|
717
|
-
|
|
718
|
-
|
|
719
|
-
|
|
720
|
-
|
|
721
|
-
|
|
722
|
-
|
|
723
|
-
|
|
724
|
-
|
|
725
|
-
|
|
726
|
-
|
|
727
|
-
|
|
728
|
-
|
|
729
|
-
|
|
730
|
-
|
|
731
|
-
|
|
732
|
-
|
|
733
|
-
|
|
734
|
-
|
|
735
|
-
|
|
736
|
-
|
|
737
|
-
|
|
738
|
-
|
|
739
|
-
|
|
740
|
-
|
|
741
|
-
|
|
742
|
-
|
|
743
|
-
|
|
744
|
-
|
|
745
|
-
|
|
746
|
-
|
|
747
|
-
|
|
748
|
-
|
|
749
|
-
|
|
750
|
-
|
|
751
|
-
)
|
|
752
|
-
|
|
753
|
-
|
|
754
|
-
|
|
755
|
-
|
|
756
|
-
|
|
757
|
-
|
|
758
|
-
|
|
759
|
-
|
|
760
|
-
|
|
761
|
-
|
|
762
|
-
|
|
763
|
-
|
|
764
|
-
|
|
765
|
-
|
|
766
|
-
|
|
767
|
-
|
|
768
|
-
|
|
769
|
-
|
|
770
|
-
|
|
771
|
-
|
|
772
|
-
|
|
773
|
-
}
|
|
774
|
-
|
|
775
|
-
|
|
776
|
-
|
|
777
|
-
|
|
778
|
-
|
|
779
|
-
|
|
780
|
-
if (!
|
|
781
|
-
|
|
782
|
-
|
|
783
|
-
|
|
784
|
-
|
|
785
|
-
|
|
786
|
-
|
|
787
|
-
|
|
788
|
-
|
|
789
|
-
|
|
790
|
-
|
|
791
|
-
|
|
792
|
-
|
|
793
|
-
|
|
794
|
-
|
|
795
|
-
|
|
796
|
-
|
|
797
|
-
|
|
798
|
-
|
|
799
|
-
|
|
800
|
-
|
|
801
|
-
|
|
802
|
-
|
|
803
|
-
|
|
804
|
-
|
|
805
|
-
|
|
806
|
-
|
|
807
|
-
|
|
808
|
-
|
|
809
|
-
|
|
810
|
-
|
|
811
|
-
|
|
812
|
-
|
|
813
|
-
|
|
814
|
-
|
|
815
|
-
|
|
816
|
-
|
|
817
|
-
|
|
818
|
-
|
|
819
|
-
|
|
820
|
-
|
|
821
|
-
|
|
822
|
-
|
|
823
|
-
|
|
824
|
-
|
|
825
|
-
|
|
826
|
-
|
|
827
|
-
|
|
828
|
-
|
|
829
|
-
|
|
830
|
-
|
|
831
|
-
|
|
832
|
-
|
|
833
|
-
|
|
834
|
-
|
|
835
|
-
|
|
836
|
-
|
|
837
|
-
|
|
838
|
-
|
|
839
|
-
|
|
840
|
-
|
|
841
|
-
|
|
842
|
-
|
|
843
|
-
|
|
844
|
-
|
|
845
|
-
|
|
846
|
-
|
|
847
|
-
|
|
848
|
-
|
|
849
|
-
|
|
850
|
-
|
|
851
|
-
|
|
852
|
-
|
|
853
|
-
|
|
854
|
-
|
|
855
|
-
|
|
856
|
-
|
|
857
|
-
|
|
858
|
-
|
|
859
|
-
|
|
860
|
-
|
|
861
|
-
|
|
862
|
-
|
|
863
|
-
|
|
864
|
-
|
|
865
|
-
|
|
866
|
-
|
|
867
|
-
|
|
868
|
-
|
|
869
|
-
|
|
870
|
-
|
|
871
|
-
|
|
872
|
-
|
|
873
|
-
|
|
874
|
-
|
|
875
|
-
|
|
876
|
-
|
|
877
|
-
|
|
878
|
-
|
|
879
|
-
|
|
880
|
-
|
|
881
|
-
|
|
882
|
-
|
|
883
|
-
|
|
884
|
-
|
|
885
|
-
|
|
886
|
-
|
|
887
|
-
|
|
888
|
-
|
|
889
|
-
|
|
890
|
-
|
|
891
|
-
|
|
892
|
-
|
|
893
|
-
|
|
894
|
-
|
|
895
|
-
|
|
896
|
-
|
|
897
|
-
|
|
898
|
-
|
|
899
|
-
|
|
900
|
-
|
|
901
|
-
|
|
902
|
-
|
|
903
|
-
await this.
|
|
904
|
-
|
|
905
|
-
|
|
906
|
-
|
|
907
|
-
|
|
908
|
-
|
|
909
|
-
|
|
910
|
-
|
|
911
|
-
|
|
912
|
-
|
|
913
|
-
|
|
914
|
-
|
|
915
|
-
|
|
916
|
-
|
|
917
|
-
|
|
918
|
-
|
|
919
|
-
|
|
920
|
-
|
|
921
|
-
|
|
922
|
-
|
|
923
|
-
|
|
924
|
-
|
|
925
|
-
|
|
926
|
-
|
|
927
|
-
|
|
928
|
-
|
|
929
|
-
|
|
930
|
-
|
|
931
|
-
|
|
932
|
-
|
|
933
|
-
|
|
934
|
-
|
|
935
|
-
|
|
936
|
-
|
|
937
|
-
|
|
938
|
-
|
|
939
|
-
|
|
940
|
-
|
|
941
|
-
|
|
942
|
-
|
|
943
|
-
|
|
944
|
-
|
|
945
|
-
|
|
946
|
-
|
|
947
|
-
|
|
948
|
-
|
|
949
|
-
|
|
950
|
-
|
|
951
|
-
|
|
952
|
-
|
|
953
|
-
|
|
954
|
-
|
|
955
|
-
|
|
956
|
-
|
|
957
|
-
|
|
958
|
-
|
|
959
|
-
|
|
960
|
-
|
|
961
|
-
|
|
962
|
-
|
|
963
|
-
|
|
964
|
-
|
|
965
|
-
|
|
966
|
-
|
|
967
|
-
|
|
968
|
-
|
|
969
|
-
|
|
970
|
-
|
|
971
|
-
|
|
972
|
-
|
|
973
|
-
}
|
|
974
|
-
|
|
975
|
-
|
|
976
|
-
|
|
977
|
-
|
|
978
|
-
|
|
979
|
-
|
|
980
|
-
|
|
981
|
-
private
|
|
982
|
-
|
|
983
|
-
|
|
984
|
-
if (
|
|
985
|
-
|
|
986
|
-
|
|
987
|
-
|
|
988
|
-
|
|
989
|
-
|
|
990
|
-
|
|
991
|
-
|
|
992
|
-
|
|
993
|
-
|
|
994
|
-
|
|
995
|
-
|
|
996
|
-
|
|
997
|
-
|
|
998
|
-
|
|
999
|
-
|
|
1000
|
-
|
|
1001
|
-
|
|
1002
|
-
|
|
1003
|
-
|
|
1004
|
-
|
|
1005
|
-
|
|
1006
|
-
|
|
1007
|
-
|
|
1008
|
-
|
|
1009
|
-
|
|
1010
|
-
|
|
1011
|
-
const
|
|
1012
|
-
|
|
1013
|
-
|
|
1014
|
-
|
|
1015
|
-
|
|
1016
|
-
|
|
1017
|
-
|
|
1018
|
-
"
|
|
1019
|
-
|
|
1020
|
-
|
|
1021
|
-
|
|
1022
|
-
|
|
1023
|
-
|
|
1024
|
-
)
|
|
1025
|
-
|
|
1026
|
-
|
|
1027
|
-
|
|
1028
|
-
|
|
1029
|
-
|
|
1030
|
-
|
|
1031
|
-
|
|
1032
|
-
|
|
1033
|
-
|
|
1034
|
-
|
|
1035
|
-
|
|
1036
|
-
|
|
1037
|
-
|
|
1038
|
-
|
|
1039
|
-
|
|
1040
|
-
|
|
1041
|
-
|
|
1042
|
-
|
|
1043
|
-
if (
|
|
1044
|
-
|
|
1045
|
-
|
|
1046
|
-
|
|
1047
|
-
|
|
1048
|
-
|
|
1049
|
-
|
|
1050
|
-
|
|
1051
|
-
|
|
1052
|
-
|
|
1053
|
-
|
|
1054
|
-
|
|
1055
|
-
|
|
1056
|
-
|
|
1057
|
-
const
|
|
1058
|
-
const
|
|
1059
|
-
const
|
|
1060
|
-
|
|
1061
|
-
if (
|
|
1062
|
-
|
|
1063
|
-
|
|
1064
|
-
|
|
1065
|
-
|
|
1066
|
-
|
|
1067
|
-
|
|
1068
|
-
|
|
1069
|
-
|
|
1070
|
-
|
|
1071
|
-
|
|
1072
|
-
|
|
1073
|
-
|
|
1074
|
-
|
|
1075
|
-
|
|
1076
|
-
|
|
1077
|
-
const
|
|
1078
|
-
|
|
1079
|
-
|
|
1080
|
-
|
|
1081
|
-
|
|
1082
|
-
|
|
1083
|
-
|
|
1084
|
-
|
|
1085
|
-
|
|
1086
|
-
|
|
1087
|
-
|
|
1088
|
-
|
|
1089
|
-
|
|
1090
|
-
|
|
1091
|
-
|
|
1092
|
-
|
|
1093
|
-
|
|
1094
|
-
|
|
1095
|
-
|
|
1096
|
-
|
|
1097
|
-
|
|
1098
|
-
|
|
1099
|
-
|
|
1100
|
-
|
|
1101
|
-
|
|
1102
|
-
|
|
1103
|
-
|
|
1104
|
-
|
|
1105
|
-
|
|
1106
|
-
|
|
1107
|
-
|
|
1108
|
-
|
|
1109
|
-
|
|
1110
|
-
|
|
1111
|
-
|
|
1112
|
-
|
|
1113
|
-
|
|
1114
|
-
|
|
1115
|
-
|
|
1116
|
-
|
|
1117
|
-
|
|
1118
|
-
|
|
1119
|
-
|
|
1120
|
-
|
|
1121
|
-
|
|
1122
|
-
|
|
1123
|
-
|
|
1124
|
-
|
|
1125
|
-
|
|
1126
|
-
|
|
1127
|
-
|
|
1128
|
-
|
|
1129
|
-
|
|
1130
|
-
|
|
1131
|
-
|
|
1132
|
-
|
|
1133
|
-
|
|
1134
|
-
|
|
1135
|
-
|
|
1136
|
-
|
|
1137
|
-
|
|
1138
|
-
|
|
1139
|
-
|
|
1140
|
-
}
|
|
1141
|
-
|
|
1142
|
-
|
|
1143
|
-
|
|
1144
|
-
|
|
1145
|
-
|
|
1146
|
-
|
|
1147
|
-
|
|
1148
|
-
|
|
1149
|
-
|
|
1150
|
-
|
|
1151
|
-
|
|
1152
|
-
|
|
1153
|
-
|
|
1154
|
-
|
|
1155
|
-
|
|
1156
|
-
|
|
1157
|
-
|
|
1158
|
-
|
|
1159
|
-
|
|
1160
|
-
|
|
1161
|
-
|
|
1162
|
-
|
|
1163
|
-
|
|
1164
|
-
|
|
1165
|
-
|
|
1166
|
-
|
|
1167
|
-
|
|
1168
|
-
|
|
1169
|
-
|
|
1170
|
-
|
|
1171
|
-
|
|
1172
|
-
|
|
1173
|
-
|
|
1174
|
-
|
|
1175
|
-
|
|
1176
|
-
|
|
1177
|
-
|
|
1178
|
-
|
|
1179
|
-
|
|
1180
|
-
|
|
1181
|
-
|
|
1182
|
-
|
|
1183
|
-
|
|
1184
|
-
|
|
1185
|
-
|
|
1186
|
-
|
|
1187
|
-
|
|
1188
|
-
|
|
1189
|
-
|
|
1190
|
-
|
|
1191
|
-
}
|
|
1192
|
-
}
|
|
1193
|
-
|
|
1194
|
-
|
|
1195
|
-
|
|
1196
|
-
|
|
1197
|
-
|
|
1198
|
-
|
|
1199
|
-
|
|
1200
|
-
|
|
1201
|
-
|
|
1202
|
-
|
|
1203
|
-
|
|
1204
|
-
|
|
1205
|
-
|
|
1206
|
-
|
|
1207
|
-
|
|
1208
|
-
|
|
1209
|
-
|
|
1210
|
-
|
|
1211
|
-
|
|
1212
|
-
|
|
1213
|
-
|
|
1214
|
-
|
|
1215
|
-
|
|
1216
|
-
|
|
1217
|
-
|
|
1218
|
-
|
|
1219
|
-
|
|
1220
|
-
|
|
1221
|
-
|
|
1222
|
-
|
|
1223
|
-
|
|
1224
|
-
|
|
1225
|
-
|
|
1226
|
-
|
|
1227
|
-
|
|
1228
|
-
|
|
1229
|
-
|
|
1230
|
-
|
|
1231
|
-
|
|
1232
|
-
|
|
1233
|
-
|
|
1234
|
-
|
|
1235
|
-
|
|
1236
|
-
|
|
1237
|
-
|
|
1238
|
-
|
|
1239
|
-
|
|
1240
|
-
|
|
1241
|
-
|
|
1242
|
-
|
|
1243
|
-
|
|
1244
|
-
|
|
1245
|
-
|
|
1246
|
-
|
|
1247
|
-
|
|
1248
|
-
|
|
1249
|
-
|
|
1250
|
-
|
|
1251
|
-
|
|
1252
|
-
|
|
1253
|
-
|
|
1254
|
-
|
|
1255
|
-
|
|
1256
|
-
|
|
1257
|
-
|
|
1258
|
-
|
|
1259
|
-
|
|
1260
|
-
|
|
1261
|
-
|
|
1262
|
-
})
|
|
1263
|
-
|
|
1264
|
-
|
|
1265
|
-
|
|
1266
|
-
|
|
1267
|
-
|
|
1268
|
-
|
|
1269
|
-
|
|
1270
|
-
|
|
1271
|
-
|
|
1272
|
-
|
|
1273
|
-
|
|
1274
|
-
|
|
1275
|
-
|
|
1276
|
-
|
|
1277
|
-
|
|
1278
|
-
|
|
1279
|
-
|
|
1280
|
-
|
|
1281
|
-
|
|
1282
|
-
|
|
1283
|
-
|
|
1284
|
-
|
|
1285
|
-
|
|
1286
|
-
|
|
1287
|
-
|
|
1288
|
-
|
|
1289
|
-
|
|
1290
|
-
|
|
1291
|
-
|
|
1292
|
-
|
|
1293
|
-
|
|
1294
|
-
|
|
1295
|
-
|
|
1296
|
-
|
|
1297
|
-
|
|
1298
|
-
|
|
1299
|
-
|
|
1300
|
-
|
|
1301
|
-
|
|
1302
|
-
|
|
1303
|
-
|
|
1304
|
-
|
|
1305
|
-
|
|
1306
|
-
|
|
1307
|
-
|
|
1308
|
-
|
|
1309
|
-
|
|
1310
|
-
|
|
1311
|
-
|
|
1312
|
-
|
|
1313
|
-
|
|
1314
|
-
|
|
1315
|
-
|
|
1316
|
-
const
|
|
1317
|
-
|
|
1318
|
-
|
|
1319
|
-
|
|
1320
|
-
|
|
1321
|
-
|
|
1322
|
-
|
|
1323
|
-
const
|
|
1324
|
-
|
|
1325
|
-
|
|
1326
|
-
|
|
1327
|
-
|
|
1328
|
-
|
|
1329
|
-
|
|
1330
|
-
|
|
1331
|
-
|
|
1332
|
-
|
|
1333
|
-
|
|
1334
|
-
|
|
1335
|
-
|
|
1336
|
-
|
|
1337
|
-
const
|
|
1338
|
-
|
|
1339
|
-
|
|
1340
|
-
|
|
1341
|
-
const
|
|
1342
|
-
|
|
1343
|
-
|
|
1344
|
-
|
|
1345
|
-
|
|
1346
|
-
|
|
1347
|
-
|
|
1348
|
-
|
|
1349
|
-
|
|
1350
|
-
|
|
1351
|
-
|
|
1352
|
-
|
|
1353
|
-
|
|
1354
|
-
|
|
1355
|
-
|
|
1356
|
-
|
|
1357
|
-
const
|
|
1358
|
-
|
|
1359
|
-
|
|
1360
|
-
|
|
1361
|
-
|
|
1362
|
-
|
|
1363
|
-
|
|
1364
|
-
|
|
1365
|
-
|
|
1366
|
-
|
|
1367
|
-
|
|
1368
|
-
|
|
1369
|
-
|
|
1370
|
-
|
|
1371
|
-
|
|
1372
|
-
|
|
1373
|
-
|
|
1374
|
-
|
|
1375
|
-
const
|
|
1376
|
-
|
|
1377
|
-
|
|
1378
|
-
|
|
1379
|
-
|
|
1380
|
-
|
|
1381
|
-
|
|
1382
|
-
|
|
1383
|
-
|
|
1384
|
-
|
|
1385
|
-
|
|
1386
|
-
|
|
1387
|
-
|
|
1388
|
-
|
|
1389
|
-
|
|
1390
|
-
}
|
|
1391
|
-
|
|
1392
|
-
|
|
1393
|
-
|
|
1394
|
-
|
|
1395
|
-
|
|
1396
|
-
|
|
1397
|
-
|
|
1398
|
-
|
|
1399
|
-
|
|
1400
|
-
const
|
|
1401
|
-
|
|
1402
|
-
|
|
1403
|
-
const
|
|
1404
|
-
|
|
1405
|
-
|
|
1406
|
-
|
|
1407
|
-
|
|
1408
|
-
|
|
1409
|
-
|
|
1410
|
-
|
|
1411
|
-
|
|
1412
|
-
|
|
1413
|
-
|
|
1414
|
-
|
|
1415
|
-
|
|
1416
|
-
|
|
1417
|
-
|
|
1418
|
-
|
|
1419
|
-
|
|
1420
|
-
|
|
1421
|
-
|
|
1422
|
-
|
|
1423
|
-
|
|
1424
|
-
|
|
1425
|
-
|
|
1426
|
-
|
|
1427
|
-
|
|
1428
|
-
|
|
1429
|
-
|
|
1430
|
-
|
|
1431
|
-
|
|
1432
|
-
|
|
1433
|
-
|
|
1434
|
-
|
|
1435
|
-
|
|
1436
|
-
|
|
1437
|
-
|
|
1438
|
-
|
|
1439
|
-
|
|
1440
|
-
|
|
1441
|
-
|
|
1442
|
-
|
|
1443
|
-
|
|
1444
|
-
|
|
1445
|
-
|
|
1446
|
-
|
|
1447
|
-
|
|
1448
|
-
|
|
1449
|
-
|
|
1450
|
-
{
|
|
1451
|
-
|
|
1452
|
-
|
|
1453
|
-
|
|
1454
|
-
|
|
1455
|
-
|
|
1456
|
-
|
|
1457
|
-
|
|
1458
|
-
|
|
1459
|
-
)
|
|
1460
|
-
|
|
1461
|
-
|
|
1462
|
-
|
|
1463
|
-
|
|
1464
|
-
|
|
1465
|
-
|
|
1466
|
-
|
|
1467
|
-
|
|
1468
|
-
|
|
1469
|
-
|
|
1470
|
-
|
|
1471
|
-
|
|
1472
|
-
|
|
1473
|
-
|
|
1474
|
-
|
|
1475
|
-
|
|
1476
|
-
|
|
1477
|
-
|
|
1478
|
-
|
|
1479
|
-
}
|
|
1480
|
-
|
|
1481
|
-
|
|
1482
|
-
|
|
1483
|
-
|
|
1484
|
-
|
|
1485
|
-
|
|
1486
|
-
|
|
1487
|
-
|
|
1488
|
-
|
|
1489
|
-
|
|
1490
|
-
|
|
1491
|
-
|
|
1492
|
-
|
|
1493
|
-
|
|
1494
|
-
|
|
1495
|
-
|
|
1496
|
-
|
|
1497
|
-
|
|
1498
|
-
|
|
1499
|
-
|
|
1500
|
-
|
|
1501
|
-
|
|
1502
|
-
|
|
1503
|
-
|
|
1504
|
-
|
|
1505
|
-
|
|
1506
|
-
}
|
|
1507
|
-
|
|
1508
|
-
|
|
1509
|
-
|
|
1510
|
-
|
|
1511
|
-
|
|
1512
|
-
|
|
1513
|
-
|
|
1514
|
-
|
|
1515
|
-
|
|
1516
|
-
|
|
1517
|
-
|
|
1518
|
-
|
|
1519
|
-
|
|
1520
|
-
|
|
1521
|
-
|
|
1522
|
-
|
|
1523
|
-
|
|
1524
|
-
|
|
1525
|
-
|
|
1526
|
-
|
|
1527
|
-
|
|
1528
|
-
|
|
1529
|
-
|
|
1530
|
-
|
|
1531
|
-
|
|
1532
|
-
|
|
1533
|
-
|
|
1534
|
-
|
|
1535
|
-
|
|
1536
|
-
|
|
1537
|
-
|
|
1538
|
-
|
|
1539
|
-
|
|
1540
|
-
|
|
1541
|
-
|
|
1542
|
-
|
|
1543
|
-
|
|
1544
|
-
|
|
1545
|
-
|
|
1546
|
-
|
|
1547
|
-
|
|
1548
|
-
}
|
|
1549
|
-
|
|
1550
|
-
|
|
1551
|
-
|
|
1552
|
-
|
|
1553
|
-
|
|
1554
|
-
|
|
1555
|
-
|
|
1556
|
-
|
|
1557
|
-
|
|
1558
|
-
|
|
1559
|
-
|
|
1560
|
-
|
|
1561
|
-
|
|
1562
|
-
|
|
1563
|
-
|
|
1564
|
-
|
|
1565
|
-
|
|
1566
|
-
|
|
1567
|
-
|
|
1568
|
-
|
|
1569
|
-
|
|
1570
|
-
|
|
1571
|
-
|
|
1572
|
-
|
|
1573
|
-
|
|
1574
|
-
|
|
1575
|
-
|
|
1576
|
-
|
|
1577
|
-
|
|
1578
|
-
|
|
1579
|
-
|
|
1580
|
-
|
|
1581
|
-
|
|
1582
|
-
|
|
1583
|
-
|
|
1584
|
-
|
|
1585
|
-
|
|
1586
|
-
|
|
1587
|
-
|
|
1588
|
-
|
|
1589
|
-
|
|
1590
|
-
|
|
1591
|
-
|
|
1592
|
-
|
|
1593
|
-
|
|
1594
|
-
|
|
1595
|
-
}
|
|
1596
|
-
|
|
1597
|
-
|
|
1598
|
-
|
|
1599
|
-
|
|
1600
|
-
|
|
1601
|
-
|
|
1602
|
-
|
|
1603
|
-
|
|
1604
|
-
|
|
1605
|
-
|
|
1606
|
-
|
|
1607
|
-
|
|
1608
|
-
|
|
1609
|
-
|
|
1610
|
-
|
|
1611
|
-
|
|
1612
|
-
|
|
1613
|
-
|
|
1614
|
-
|
|
1615
|
-
|
|
1616
|
-
|
|
1617
|
-
|
|
1618
|
-
|
|
1619
|
-
|
|
1620
|
-
|
|
1621
|
-
|
|
1622
|
-
|
|
1623
|
-
|
|
1624
|
-
|
|
1625
|
-
|
|
1626
|
-
|
|
1627
|
-
},
|
|
1628
|
-
|
|
1629
|
-
|
|
1630
|
-
|
|
1631
|
-
|
|
1632
|
-
|
|
1633
|
-
|
|
1634
|
-
|
|
1635
|
-
|
|
1636
|
-
|
|
1637
|
-
|
|
1638
|
-
|
|
1639
|
-
}
|
|
1640
|
-
}
|
|
1641
|
-
|
|
1642
|
-
|
|
1643
|
-
|
|
1644
|
-
|
|
1645
|
-
|
|
1646
|
-
|
|
1647
|
-
|
|
1648
|
-
}
|
|
1649
|
-
|
|
1650
|
-
|
|
1651
|
-
|
|
1
|
+
import { MedusaService } from "@medusajs/framework/utils"
|
|
2
|
+
import { recordMetricAtomic } from "./utils/metrics"
|
|
3
|
+
import { paypalFetch } from "./utils/paypal-fetch"
|
|
4
|
+
import { decryptSecret, encryptSecret } from "./utils/secret-crypto"
|
|
5
|
+
import PayPalConnection from "./models/paypal_connection"
|
|
6
|
+
import PayPalMetric from "./models/paypal_metric"
|
|
7
|
+
import PayPalSettings from "./models/paypal_settings"
|
|
8
|
+
import PayPalWebhookEvent from "./models/paypal_webhook_event"
|
|
9
|
+
import { getPayPalConfig } from "./types/config"
|
|
10
|
+
import { getPayPalApiBase } from "./utils/paypal-auth"
|
|
11
|
+
import { normalizeCurrencyCode } from "./utils/currencies"
|
|
12
|
+
|
|
13
|
+
type Environment = "sandbox" | "live"
|
|
14
|
+
|
|
15
|
+
type Status =
|
|
16
|
+
| "disconnected"
|
|
17
|
+
| "pending"
|
|
18
|
+
| "pending_credentials"
|
|
19
|
+
| "connected"
|
|
20
|
+
| "revoked"
|
|
21
|
+
|
|
22
|
+
const SENSITIVE_KEY_RE =
|
|
23
|
+
/secret|password|client_secret|access_token|refresh_token|authorization|auth_code|api[_-]?key/i
|
|
24
|
+
|
|
25
|
+
/**
|
|
26
|
+
* Defensive redaction for audit logs: replace values of keys that look
|
|
27
|
+
* sensitive with "[REDACTED]". Bounded depth/breadth so a pathological payload
|
|
28
|
+
* can't blow up logging.
|
|
29
|
+
*/
|
|
30
|
+
function redactSensitive(value: unknown, depth = 0): unknown {
|
|
31
|
+
if (depth > 6 || value === null || typeof value !== "object") {
|
|
32
|
+
return value
|
|
33
|
+
}
|
|
34
|
+
if (Array.isArray(value)) {
|
|
35
|
+
return value.slice(0, 50).map((v) => redactSensitive(v, depth + 1))
|
|
36
|
+
}
|
|
37
|
+
const out: Record<string, unknown> = {}
|
|
38
|
+
for (const [k, v] of Object.entries(value as Record<string, unknown>)) {
|
|
39
|
+
out[k] = SENSITIVE_KEY_RE.test(k) ? "[REDACTED]" : redactSensitive(v, depth + 1)
|
|
40
|
+
}
|
|
41
|
+
return out
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
class PayPalModuleService extends MedusaService({
|
|
45
|
+
PayPalConnection,
|
|
46
|
+
PayPalMetric,
|
|
47
|
+
PayPalSettings,
|
|
48
|
+
PayPalWebhookEvent,
|
|
49
|
+
}) {
|
|
50
|
+
protected cfg = getPayPalConfig()
|
|
51
|
+
private tokenRefreshPromise: Promise<string> | null = null
|
|
52
|
+
// Raw knex connection for the atomic metric upsert; null when the container
|
|
53
|
+
// doesn't expose it (recordMetric then falls back to the ORM path).
|
|
54
|
+
private pgForMetrics: { raw: (sql: string, bindings: unknown[]) => Promise<unknown> } | null =
|
|
55
|
+
null
|
|
56
|
+
|
|
57
|
+
constructor(...args: any[]) {
|
|
58
|
+
// MedusaService's generated constructor signature varies across framework
|
|
59
|
+
// versions — pass everything through untouched.
|
|
60
|
+
super(...args)
|
|
61
|
+
try {
|
|
62
|
+
const cradle = (args[0] || {}) as Record<string, any>
|
|
63
|
+
const pg = cradle.__pg_connection__ ?? cradle.pgConnection ?? null
|
|
64
|
+
this.pgForMetrics = pg && typeof pg.raw === "function" ? pg : null
|
|
65
|
+
} catch {
|
|
66
|
+
this.pgForMetrics = null
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
private get bnCode(): string {
|
|
71
|
+
return this.cfg.bnCode || "MBJTechnolabs_SI_SPB"
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
private async getSettingsData() {
|
|
75
|
+
const settings = await this.getSettings()
|
|
76
|
+
return (settings?.data || {}) as Record<string, any>
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
private async ensureSettingsDefaults() {
|
|
80
|
+
const data = await this.getSettingsData()
|
|
81
|
+
const onboarding = { ...(data.onboarding_config || {}) } as Record<string, any>
|
|
82
|
+
const apiDetails = { ...(data.api_details || {}) } as Record<string, any>
|
|
83
|
+
let changed = false
|
|
84
|
+
|
|
85
|
+
if (!onboarding.partner_service_url) {
|
|
86
|
+
onboarding.partner_service_url = this.cfg.partnerServiceUrl
|
|
87
|
+
changed = true
|
|
88
|
+
}
|
|
89
|
+
if (!onboarding.partner_js_url) {
|
|
90
|
+
onboarding.partner_js_url = this.cfg.partnerJsUrl
|
|
91
|
+
changed = true
|
|
92
|
+
}
|
|
93
|
+
if (!onboarding.backend_url) {
|
|
94
|
+
onboarding.backend_url = this.cfg.backendUrl
|
|
95
|
+
changed = true
|
|
96
|
+
}
|
|
97
|
+
if (!onboarding.seller_nonce) {
|
|
98
|
+
onboarding.seller_nonce = this.cfg.sellerNonce
|
|
99
|
+
changed = true
|
|
100
|
+
}
|
|
101
|
+
if (!onboarding.bn_code && this.cfg.bnCode) {
|
|
102
|
+
onboarding.bn_code = this.cfg.bnCode
|
|
103
|
+
changed = true
|
|
104
|
+
}
|
|
105
|
+
if (!onboarding.partner_merchant_id_sandbox) {
|
|
106
|
+
onboarding.partner_merchant_id_sandbox = this.cfg.partnerMerchantIdSandbox
|
|
107
|
+
changed = true
|
|
108
|
+
}
|
|
109
|
+
if (!onboarding.partner_merchant_id_live) {
|
|
110
|
+
onboarding.partner_merchant_id_live = this.cfg.partnerMerchantIdLive
|
|
111
|
+
changed = true
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
if (!apiDetails.currency_code) {
|
|
115
|
+
const raw = (process.env.PAYPAL_CURRENCY || "").trim()
|
|
116
|
+
apiDetails.currency_code = raw ? normalizeCurrencyCode(raw) : "EUR"
|
|
117
|
+
changed = true
|
|
118
|
+
}
|
|
119
|
+
if (!apiDetails.storefront_url) {
|
|
120
|
+
const storeUrl = process.env.STOREFRONT_URL || process.env.STORE_URL
|
|
121
|
+
if (storeUrl) {
|
|
122
|
+
apiDetails.storefront_url = storeUrl
|
|
123
|
+
changed = true
|
|
124
|
+
}
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
if (changed) {
|
|
128
|
+
await this.saveSettings({
|
|
129
|
+
onboarding_config: onboarding,
|
|
130
|
+
api_details: apiDetails,
|
|
131
|
+
})
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
return { onboarding, apiDetails }
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
async getApiDetails() {
|
|
138
|
+
const { onboarding, apiDetails } = await this.ensureSettingsDefaults()
|
|
139
|
+
return {
|
|
140
|
+
onboarding,
|
|
141
|
+
apiDetails,
|
|
142
|
+
}
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
private getAlertWebhookUrls() {
|
|
146
|
+
return (this.cfg.alertWebhookUrls || []).map((url) => url.trim()).filter(Boolean)
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
private async getPartnerMerchantId(env: Environment) {
|
|
150
|
+
const { onboarding } = await this.ensureSettingsDefaults()
|
|
151
|
+
return env === "live" ? onboarding.partner_merchant_id_live : onboarding.partner_merchant_id_sandbox
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
private async getCurrentRow(): Promise<any | null> {
|
|
155
|
+
const rows = await this.listPayPalConnections(
|
|
156
|
+
{},
|
|
157
|
+
{ take: 1, order: { created_at: "DESC" } }
|
|
158
|
+
)
|
|
159
|
+
return rows?.[0] ?? null
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
private async getCurrentEnvironment(): Promise<Environment> {
|
|
163
|
+
try {
|
|
164
|
+
const row = await this.getCurrentRow()
|
|
165
|
+
const env = (row?.environment as Environment) || "live"
|
|
166
|
+
return env === "sandbox" ? "sandbox" : "live"
|
|
167
|
+
} catch {
|
|
168
|
+
return "live"
|
|
169
|
+
}
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
private getEnvCreds(
|
|
173
|
+
row: any,
|
|
174
|
+
env: Environment
|
|
175
|
+
): { clientId?: string; clientSecret?: string; sellerMerchantId?: string; sellerEmail?: string } {
|
|
176
|
+
const meta = (row?.metadata || {}) as any
|
|
177
|
+
const creds = meta?.credentials?.[env] || {}
|
|
178
|
+
return {
|
|
179
|
+
clientId: creds.client_id || creds.clientId || undefined,
|
|
180
|
+
// Secrets are encrypted at rest when PAYPAL_ENCRYPTION_KEY is set; decrypt
|
|
181
|
+
// here so every consumer (auth, status) sees plaintext. Legacy plaintext
|
|
182
|
+
// values pass through unchanged.
|
|
183
|
+
clientSecret: decryptSecret(creds.client_secret || creds.clientSecret) || undefined,
|
|
184
|
+
sellerMerchantId:
|
|
185
|
+
creds.seller_merchant_id ||
|
|
186
|
+
creds.sellerMerchantId ||
|
|
187
|
+
creds.payer_id ||
|
|
188
|
+
creds.merchant_id ||
|
|
189
|
+
creds.merchantId ||
|
|
190
|
+
undefined,
|
|
191
|
+
sellerEmail: creds.seller_email || creds.sellerEmail || undefined,
|
|
192
|
+
}
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
private extractSellerEmail(...candidates: unknown[]): string | null {
|
|
196
|
+
const queue = [...candidates]
|
|
197
|
+
const seen = new WeakSet<object>()
|
|
198
|
+
const MAX_ITERATIONS = 500
|
|
199
|
+
|
|
200
|
+
let iterations = 0
|
|
201
|
+
while (queue.length > 0 && iterations < MAX_ITERATIONS) {
|
|
202
|
+
iterations++
|
|
203
|
+
const value = queue.shift()
|
|
204
|
+
if (!value) {
|
|
205
|
+
continue
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
if (typeof value === "string") {
|
|
209
|
+
const trimmed = value.trim()
|
|
210
|
+
if (trimmed && trimmed.includes("@")) {
|
|
211
|
+
return trimmed
|
|
212
|
+
}
|
|
213
|
+
continue
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
if (typeof value !== "object") {
|
|
217
|
+
continue
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
if (seen.has(value as object)) {
|
|
221
|
+
continue
|
|
222
|
+
}
|
|
223
|
+
seen.add(value as object)
|
|
224
|
+
|
|
225
|
+
if (Array.isArray(value)) {
|
|
226
|
+
queue.push(...value)
|
|
227
|
+
continue
|
|
228
|
+
}
|
|
229
|
+
|
|
230
|
+
const obj = value as Record<string, unknown>
|
|
231
|
+
const prioritized = [
|
|
232
|
+
obj.email,
|
|
233
|
+
obj.primary_email,
|
|
234
|
+
obj.merchant_email,
|
|
235
|
+
obj.email_address,
|
|
236
|
+
obj.account_email,
|
|
237
|
+
obj.contact_email,
|
|
238
|
+
obj.value,
|
|
239
|
+
obj.address,
|
|
240
|
+
]
|
|
241
|
+
queue.push(...prioritized)
|
|
242
|
+
|
|
243
|
+
for (const [k, v] of Object.entries(obj)) {
|
|
244
|
+
const key = String(k).toLowerCase()
|
|
245
|
+
if (key.includes("email") || key.includes("address")) {
|
|
246
|
+
queue.push(v)
|
|
247
|
+
}
|
|
248
|
+
}
|
|
249
|
+
|
|
250
|
+
queue.push(...Object.values(obj))
|
|
251
|
+
}
|
|
252
|
+
|
|
253
|
+
return null
|
|
254
|
+
}
|
|
255
|
+
|
|
256
|
+
private async fetchMerchantIntegrationDetails(
|
|
257
|
+
env: Environment,
|
|
258
|
+
merchantId: string,
|
|
259
|
+
accessTokenOverride?: string
|
|
260
|
+
) {
|
|
261
|
+
const partnerMerchantId = await this.getPartnerMerchantId(env)
|
|
262
|
+
if (!partnerMerchantId) {
|
|
263
|
+
throw new Error("Missing PayPal partner merchant id configuration.")
|
|
264
|
+
}
|
|
265
|
+
|
|
266
|
+
const baseUrl = getPayPalApiBase(env)
|
|
267
|
+
const accessToken = accessTokenOverride ?? await this.getAppAccessToken()
|
|
268
|
+
|
|
269
|
+
const resp = await paypalFetch(
|
|
270
|
+
`${baseUrl}/v1/customer/partners/${encodeURIComponent(
|
|
271
|
+
partnerMerchantId
|
|
272
|
+
)}/merchant-integrations/${encodeURIComponent(merchantId)}`,
|
|
273
|
+
{
|
|
274
|
+
method: "GET",
|
|
275
|
+
headers: {
|
|
276
|
+
"Content-Type": "application/json",
|
|
277
|
+
Authorization: `Bearer ${accessToken}`,
|
|
278
|
+
"PayPal-Partner-Attribution-Id": this.bnCode,
|
|
279
|
+
},
|
|
280
|
+
}
|
|
281
|
+
)
|
|
282
|
+
|
|
283
|
+
const text = await resp.text().catch(() => "")
|
|
284
|
+
let json: any = {}
|
|
285
|
+
try {
|
|
286
|
+
json = text ? JSON.parse(text) : {}
|
|
287
|
+
} catch (e: any) {
|
|
288
|
+
console.warn("[PayPal] Failed to parse response JSON — using empty object:", e?.message)
|
|
289
|
+
}
|
|
290
|
+
|
|
291
|
+
if (!resp.ok) {
|
|
292
|
+
throw new Error(
|
|
293
|
+
`PayPal merchant integration lookup failed (${resp.status}): ${text || JSON.stringify(json)}`
|
|
294
|
+
)
|
|
295
|
+
}
|
|
296
|
+
|
|
297
|
+
return json
|
|
298
|
+
}
|
|
299
|
+
|
|
300
|
+
private async getAppAccessTokenForCredentials(
|
|
301
|
+
env: Environment,
|
|
302
|
+
credentials: { clientId: string; clientSecret: string }
|
|
303
|
+
) {
|
|
304
|
+
const baseUrl = getPayPalApiBase(env)
|
|
305
|
+
const basic = Buffer.from(`${credentials.clientId}:${credentials.clientSecret}`).toString("base64")
|
|
306
|
+
|
|
307
|
+
const body = new URLSearchParams()
|
|
308
|
+
body.set("grant_type", "client_credentials")
|
|
309
|
+
|
|
310
|
+
const res = await paypalFetch(`${baseUrl}/v1/oauth2/token`, {
|
|
311
|
+
method: "POST",
|
|
312
|
+
headers: {
|
|
313
|
+
"Content-Type": "application/x-www-form-urlencoded",
|
|
314
|
+
Authorization: `Basic ${basic}`,
|
|
315
|
+
"PayPal-Partner-Attribution-Id": this.bnCode,
|
|
316
|
+
},
|
|
317
|
+
body,
|
|
318
|
+
})
|
|
319
|
+
|
|
320
|
+
const text = await res.text().catch(() => "")
|
|
321
|
+
let json: any = {}
|
|
322
|
+
try {
|
|
323
|
+
json = text ? JSON.parse(text) : {}
|
|
324
|
+
} catch (e: any) {
|
|
325
|
+
console.warn("[PayPal] Failed to parse app token response JSON:", e?.message)
|
|
326
|
+
}
|
|
327
|
+
|
|
328
|
+
if (!res.ok) {
|
|
329
|
+
throw new Error(`PayPal client_credentials failed (${res.status}): ${text || JSON.stringify(json)}`)
|
|
330
|
+
}
|
|
331
|
+
|
|
332
|
+
const accessToken = String(json.access_token || "")
|
|
333
|
+
if (!accessToken) {
|
|
334
|
+
throw new Error("PayPal client_credentials succeeded but access_token is missing.")
|
|
335
|
+
}
|
|
336
|
+
|
|
337
|
+
return { accessToken, tokenPayload: json }
|
|
338
|
+
}
|
|
339
|
+
|
|
340
|
+
private async fetchSellerProfileFromDirectCredentials(
|
|
341
|
+
env: Environment,
|
|
342
|
+
credentials?: { clientId: string; clientSecret: string }
|
|
343
|
+
): Promise<{ sellerMerchantId: string | null; sellerEmail: string | null }> {
|
|
344
|
+
const baseUrl = getPayPalApiBase(env)
|
|
345
|
+
const partnerMerchantId = await this.getPartnerMerchantId(env)
|
|
346
|
+
let tokenPayload: Record<string, any> | null = null
|
|
347
|
+
|
|
348
|
+
let accessToken = ""
|
|
349
|
+
if (credentials) {
|
|
350
|
+
const tokenResp = await this.getAppAccessTokenForCredentials(env, {
|
|
351
|
+
clientId: credentials.clientId,
|
|
352
|
+
clientSecret: credentials.clientSecret,
|
|
353
|
+
})
|
|
354
|
+
accessToken = tokenResp.accessToken
|
|
355
|
+
tokenPayload = tokenResp.tokenPayload
|
|
356
|
+
} else {
|
|
357
|
+
accessToken = await this.getAppAccessToken()
|
|
358
|
+
}
|
|
359
|
+
|
|
360
|
+
let sellerEmail = this.extractSellerEmail(tokenPayload || undefined)
|
|
361
|
+
let sellerMerchantId = String(
|
|
362
|
+
tokenPayload?.merchant_id || tokenPayload?.payer_id || tokenPayload?.account_id || ""
|
|
363
|
+
).trim() || null
|
|
364
|
+
|
|
365
|
+
try {
|
|
366
|
+
const userInfoResp = await paypalFetch(`${baseUrl}/v1/identity/oauth2/userinfo?schema=paypalv1`, {
|
|
367
|
+
method: "GET",
|
|
368
|
+
headers: {
|
|
369
|
+
Authorization: `Bearer ${accessToken}`,
|
|
370
|
+
"Content-Type": "application/json",
|
|
371
|
+
Accept: "application/json",
|
|
372
|
+
"PayPal-Partner-Attribution-Id": this.bnCode,
|
|
373
|
+
},
|
|
374
|
+
})
|
|
375
|
+
if (userInfoResp.ok) {
|
|
376
|
+
const userInfo = await userInfoResp.json().catch(() => ({}))
|
|
377
|
+
sellerEmail = sellerEmail || this.extractSellerEmail(userInfo)
|
|
378
|
+
sellerMerchantId =
|
|
379
|
+
sellerMerchantId ||
|
|
380
|
+
String(userInfo?.merchant_id || userInfo?.payer_id || userInfo?.user_id || userInfo?.sub || "").trim() ||
|
|
381
|
+
null
|
|
382
|
+
}
|
|
383
|
+
} catch (e: any) {
|
|
384
|
+
console.warn("[PayPal] userinfo lookup failed:", e?.message || e)
|
|
385
|
+
}
|
|
386
|
+
|
|
387
|
+
if (partnerMerchantId) {
|
|
388
|
+
try {
|
|
389
|
+
const credsResp = await paypalFetch(
|
|
390
|
+
`${baseUrl}/v1/customer/partners/${encodeURIComponent(
|
|
391
|
+
partnerMerchantId
|
|
392
|
+
)}/merchant-integrations/credentials/`,
|
|
393
|
+
{
|
|
394
|
+
method: "GET",
|
|
395
|
+
headers: {
|
|
396
|
+
Authorization: `Bearer ${accessToken}`,
|
|
397
|
+
"Content-Type": "application/json",
|
|
398
|
+
"PayPal-Partner-Attribution-Id": this.bnCode,
|
|
399
|
+
},
|
|
400
|
+
}
|
|
401
|
+
)
|
|
402
|
+
if (credsResp.ok) {
|
|
403
|
+
const credsJson = await credsResp.json().catch(() => ({}))
|
|
404
|
+
sellerEmail = sellerEmail || this.extractSellerEmail(credsJson)
|
|
405
|
+
sellerMerchantId = sellerMerchantId || String(credsJson?.merchant_id || "").trim() || null
|
|
406
|
+
}
|
|
407
|
+
} catch (e: any) {
|
|
408
|
+
console.warn("[PayPal] direct credential profile lookup failed:", e?.message || e)
|
|
409
|
+
}
|
|
410
|
+
}
|
|
411
|
+
|
|
412
|
+
const hydrated = await this.hydrateSellerMetadataFromCredentials(env, {
|
|
413
|
+
accessToken,
|
|
414
|
+
sellerMerchantId,
|
|
415
|
+
sellerEmail,
|
|
416
|
+
})
|
|
417
|
+
|
|
418
|
+
return {
|
|
419
|
+
sellerMerchantId: hydrated.sellerMerchantId,
|
|
420
|
+
sellerEmail: hydrated.sellerEmail,
|
|
421
|
+
}
|
|
422
|
+
}
|
|
423
|
+
|
|
424
|
+
private async hydrateSellerMetadataFromCredentials(
|
|
425
|
+
env: Environment,
|
|
426
|
+
input: {
|
|
427
|
+
accessToken?: string
|
|
428
|
+
sellerMerchantId?: string | null
|
|
429
|
+
sellerEmail?: string | null
|
|
430
|
+
metadataCandidates?: any[]
|
|
431
|
+
}
|
|
432
|
+
): Promise<{ sellerMerchantId: string | null; sellerEmail: string | null }> {
|
|
433
|
+
let sellerMerchantId = (input.sellerMerchantId || "").trim() || null
|
|
434
|
+
let sellerEmail = (input.sellerEmail || "").trim() || null
|
|
435
|
+
|
|
436
|
+
if (!sellerEmail && input.metadataCandidates?.length) {
|
|
437
|
+
sellerEmail = this.extractSellerEmail(...input.metadataCandidates)
|
|
438
|
+
}
|
|
439
|
+
|
|
440
|
+
if (sellerMerchantId && !sellerEmail) {
|
|
441
|
+
try {
|
|
442
|
+
const details = await this.fetchMerchantIntegrationDetails(env, sellerMerchantId, input.accessToken)
|
|
443
|
+
sellerEmail = this.extractSellerEmail(details)
|
|
444
|
+
} catch (e: any) {
|
|
445
|
+
console.warn("[PayPal] merchant integration lookup failed:", e?.message || e)
|
|
446
|
+
}
|
|
447
|
+
}
|
|
448
|
+
|
|
449
|
+
return { sellerMerchantId, sellerEmail }
|
|
450
|
+
}
|
|
451
|
+
|
|
452
|
+
private async syncRowFieldsFromMetadata(row: any, env: Environment) {
|
|
453
|
+
const c = this.getEnvCreds(row, env)
|
|
454
|
+
await this.updatePayPalConnections({
|
|
455
|
+
id: row.id,
|
|
456
|
+
status: c.clientId && c.clientSecret ? "connected" : "disconnected",
|
|
457
|
+
seller_client_id: c.clientId || null,
|
|
458
|
+
// c.clientSecret is decrypted (from getEnvCreds); re-encrypt for the column.
|
|
459
|
+
seller_client_secret: encryptSecret(c.clientSecret) || null,
|
|
460
|
+
seller_merchant_id: c.sellerMerchantId || null,
|
|
461
|
+
seller_email: c.sellerEmail || null,
|
|
462
|
+
metadata: {
|
|
463
|
+
...(row.metadata || {}),
|
|
464
|
+
active_environment: env,
|
|
465
|
+
},
|
|
466
|
+
})
|
|
467
|
+
}
|
|
468
|
+
|
|
469
|
+
async setEnvironment(env: Environment) {
|
|
470
|
+
const nextEnv: Environment = env === "sandbox" ? "sandbox" : "live"
|
|
471
|
+
const row = await this.getCurrentRow()
|
|
472
|
+
const previousEnv = (row?.environment as Environment) || "live"
|
|
473
|
+
|
|
474
|
+
if (!row) {
|
|
475
|
+
const created = await this.createPayPalConnections({
|
|
476
|
+
environment: nextEnv,
|
|
477
|
+
status: "disconnected",
|
|
478
|
+
shared_id: null,
|
|
479
|
+
auth_code: null,
|
|
480
|
+
seller_client_id: null,
|
|
481
|
+
seller_client_secret: null,
|
|
482
|
+
seller_merchant_id: null,
|
|
483
|
+
seller_email: null,
|
|
484
|
+
app_access_token: null,
|
|
485
|
+
app_access_token_expires_at: null,
|
|
486
|
+
metadata: { credentials: {}, active_environment: nextEnv },
|
|
487
|
+
})
|
|
488
|
+
await this.recordAuditEvent("environment_switched", {
|
|
489
|
+
previous_environment: previousEnv,
|
|
490
|
+
environment: nextEnv,
|
|
491
|
+
})
|
|
492
|
+
return created
|
|
493
|
+
}
|
|
494
|
+
|
|
495
|
+
await this.updatePayPalConnections({
|
|
496
|
+
id: row.id,
|
|
497
|
+
environment: nextEnv,
|
|
498
|
+
app_access_token: null,
|
|
499
|
+
app_access_token_expires_at: null,
|
|
500
|
+
metadata: {
|
|
501
|
+
...(row.metadata || {}),
|
|
502
|
+
active_environment: nextEnv,
|
|
503
|
+
},
|
|
504
|
+
})
|
|
505
|
+
|
|
506
|
+
const updated = await this.getCurrentRow()
|
|
507
|
+
if (updated) {
|
|
508
|
+
await this.syncRowFieldsFromMetadata(updated, nextEnv)
|
|
509
|
+
}
|
|
510
|
+
|
|
511
|
+
await this.recordAuditEvent("environment_switched", {
|
|
512
|
+
previous_environment: previousEnv,
|
|
513
|
+
environment: nextEnv,
|
|
514
|
+
})
|
|
515
|
+
return await this.getCurrentRow()
|
|
516
|
+
}
|
|
517
|
+
|
|
518
|
+
async createOnboardingLink(input?: { email?: string; products?: string[]; env?: Environment }) {
|
|
519
|
+
const { onboarding } = await this.ensureSettingsDefaults()
|
|
520
|
+
// Honor an explicit environment from the caller so the generated link can't
|
|
521
|
+
// depend on a racing "set environment" request having landed first.
|
|
522
|
+
const env =
|
|
523
|
+
input?.env === "sandbox" || input?.env === "live"
|
|
524
|
+
? input.env
|
|
525
|
+
: await this.getCurrentEnvironment()
|
|
526
|
+
// The popup lands here after onboarding, as a plain top-level navigation with
|
|
527
|
+
// no auth token — so it must be the PUBLIC store bridge route, not an
|
|
528
|
+
// /admin/* route (which would 401 and leave the popup stuck). The bridge
|
|
529
|
+
// exchanges the auth code for seller credentials server-side, relays the
|
|
530
|
+
// result to the opener, and closes the popup. We pin the environment in the
|
|
531
|
+
// URL so the bridge saves credentials under the correct env even though
|
|
532
|
+
// PayPal's redirect carries no auth/session.
|
|
533
|
+
// Use the /hooks namespace: Medusa's publishable-key middleware rejects
|
|
534
|
+
// unauthenticated top-level navigations to /store/* routes, so the popup
|
|
535
|
+
// would land on a NOT_ALLOWED error page instead of the bridge.
|
|
536
|
+
const return_url = `${String(onboarding.backend_url || "").replace(/\/$/, "")}/hooks/paypal/onboard-return?env=${env}`
|
|
537
|
+
const partner_merchant_id = await this.getPartnerMerchantId(env)
|
|
538
|
+
|
|
539
|
+
const email = (input?.email || "").trim()
|
|
540
|
+
|
|
541
|
+
if (!partner_merchant_id) {
|
|
542
|
+
throw new Error("Missing PAYPAL_PARTNER_MERCHANT_ID_* env for current environment")
|
|
543
|
+
}
|
|
544
|
+
|
|
545
|
+
const form = new URLSearchParams()
|
|
546
|
+
if (email) {
|
|
547
|
+
form.set("email", email)
|
|
548
|
+
}
|
|
549
|
+
form.set("sandbox", env === "live" ? "no" : "yes")
|
|
550
|
+
form.set("return_url", return_url)
|
|
551
|
+
form.set("return_url_description", "Return to your shop.")
|
|
552
|
+
form.set("partner_merchant_id", partner_merchant_id)
|
|
553
|
+
form.set("from", "medusa")
|
|
554
|
+
|
|
555
|
+
const products = input?.products?.length ? input.products : ["PPCP"]
|
|
556
|
+
|
|
557
|
+
products.forEach((p) => {
|
|
558
|
+
form.append("products[]", p)
|
|
559
|
+
})
|
|
560
|
+
|
|
561
|
+
const res = await paypalFetch(onboarding.partner_service_url, {
|
|
562
|
+
method: "POST",
|
|
563
|
+
headers: { "Content-Type": "application/x-www-form-urlencoded" },
|
|
564
|
+
body: form.toString(),
|
|
565
|
+
})
|
|
566
|
+
|
|
567
|
+
const text = await res.text().catch(() => "")
|
|
568
|
+
if (!res.ok) {
|
|
569
|
+
throw new Error(`Onboarding service failed (${res.status}): ${text}`)
|
|
570
|
+
}
|
|
571
|
+
|
|
572
|
+
const trimmed = text.trim()
|
|
573
|
+
|
|
574
|
+
if (trimmed.startsWith("http")) {
|
|
575
|
+
return { onboarding_url: trimmed, return_url }
|
|
576
|
+
}
|
|
577
|
+
|
|
578
|
+
let json: any
|
|
579
|
+
try {
|
|
580
|
+
json = JSON.parse(trimmed)
|
|
581
|
+
} catch {
|
|
582
|
+
throw new Error(`Invalid onboarding link response (not JSON / URL): ${trimmed.slice(0, 200)}`)
|
|
583
|
+
}
|
|
584
|
+
|
|
585
|
+
if (json?.body) {
|
|
586
|
+
const inner = typeof json.body === "string" ? json.body.trim() : json.body
|
|
587
|
+
|
|
588
|
+
if (typeof inner === "string" && inner.startsWith("http")) {
|
|
589
|
+
return { onboarding_url: inner, return_url }
|
|
590
|
+
}
|
|
591
|
+
|
|
592
|
+
try {
|
|
593
|
+
json = typeof inner === "string" ? JSON.parse(inner) : inner
|
|
594
|
+
} catch {
|
|
595
|
+
throw new Error(
|
|
596
|
+
`Onboarding wrapper JSON 'body' is not valid JSON / URL: ${
|
|
597
|
+
typeof inner === "string" ? inner.slice(0, 200) : "[object]"
|
|
598
|
+
}`
|
|
599
|
+
)
|
|
600
|
+
}
|
|
601
|
+
}
|
|
602
|
+
|
|
603
|
+
if (json?.name && json?.message && (json?.debug_id || json?.details || json?.links)) {
|
|
604
|
+
const debug = json.debug_id ? ` debug_id=${json.debug_id}` : ""
|
|
605
|
+
const details = Array.isArray(json.details)
|
|
606
|
+
? json.details
|
|
607
|
+
.slice(0, 3)
|
|
608
|
+
.map((d: any) => {
|
|
609
|
+
const issue = d?.issue ? String(d.issue) : ""
|
|
610
|
+
const desc = d?.description ? String(d.description) : ""
|
|
611
|
+
const field = d?.field ? String(d.field) : ""
|
|
612
|
+
return [issue, desc, field].filter(Boolean).join(" | ")
|
|
613
|
+
})
|
|
614
|
+
.filter(Boolean)
|
|
615
|
+
.join("; ")
|
|
616
|
+
: ""
|
|
617
|
+
|
|
618
|
+
throw new Error(`PayPal onboarding error: ${json.name}: ${json.message}.${debug}${details ? ` Details: ${details}` : ""}`)
|
|
619
|
+
}
|
|
620
|
+
|
|
621
|
+
if (json?.onboarding_url && String(json.onboarding_url).startsWith("http")) {
|
|
622
|
+
return { onboarding_url: String(json.onboarding_url), return_url }
|
|
623
|
+
}
|
|
624
|
+
|
|
625
|
+
const links = Array.isArray(json?.links) ? json.links : null
|
|
626
|
+
if (links) {
|
|
627
|
+
const action = links.find(
|
|
628
|
+
(l: any) => l?.rel === "action_url" || l?.rel === "actionUrl" || l?.rel === "action-url"
|
|
629
|
+
)
|
|
630
|
+
const href = action?.href ? String(action.href) : null
|
|
631
|
+
if (href && href.startsWith("http")) {
|
|
632
|
+
return { onboarding_url: href, return_url }
|
|
633
|
+
}
|
|
634
|
+
}
|
|
635
|
+
|
|
636
|
+
throw new Error(
|
|
637
|
+
`Onboarding JSON missing action_url link. Keys: ${Object.keys(json || {}).join(", ")}`
|
|
638
|
+
)
|
|
639
|
+
}
|
|
640
|
+
|
|
641
|
+
async startOnboarding() {
|
|
642
|
+
const row = await this.getCurrentRow()
|
|
643
|
+
const env = await this.getCurrentEnvironment()
|
|
644
|
+
|
|
645
|
+
if (row) {
|
|
646
|
+
await this.updatePayPalConnections({ id: row.id, status: "pending" })
|
|
647
|
+
return
|
|
648
|
+
}
|
|
649
|
+
|
|
650
|
+
await this.createPayPalConnections({
|
|
651
|
+
environment: env,
|
|
652
|
+
status: "pending",
|
|
653
|
+
metadata: {},
|
|
654
|
+
})
|
|
655
|
+
}
|
|
656
|
+
|
|
657
|
+
async saveOnboardCallback(input: { authCode: string; sharedId: string }) {
|
|
658
|
+
const row = await this.getCurrentRow()
|
|
659
|
+
const env = await this.getCurrentEnvironment()
|
|
660
|
+
|
|
661
|
+
if (!row) {
|
|
662
|
+
return await this.createPayPalConnections({
|
|
663
|
+
environment: env,
|
|
664
|
+
status: "pending_credentials",
|
|
665
|
+
auth_code: input.authCode,
|
|
666
|
+
shared_id: input.sharedId,
|
|
667
|
+
metadata: {},
|
|
668
|
+
})
|
|
669
|
+
}
|
|
670
|
+
|
|
671
|
+
return await this.updatePayPalConnections({
|
|
672
|
+
id: row.id,
|
|
673
|
+
status: "pending_credentials",
|
|
674
|
+
auth_code: input.authCode,
|
|
675
|
+
shared_id: input.sharedId,
|
|
676
|
+
})
|
|
677
|
+
}
|
|
678
|
+
|
|
679
|
+
async exchangeAndSaveSellerCredentials(input: {
|
|
680
|
+
authCode: string
|
|
681
|
+
sharedId: string
|
|
682
|
+
env?: "sandbox" | "live"
|
|
683
|
+
}) {
|
|
684
|
+
const env = (input.env || (await this.getCurrentEnvironment())) as Environment
|
|
685
|
+
|
|
686
|
+
// Onboarding completion can now arrive via several redundant paths
|
|
687
|
+
// (partner.js's onboardingCallback in the opener, the return_url bridge that
|
|
688
|
+
// runs inside the popup, and admin status polling). PayPal's authorization
|
|
689
|
+
// code is single-use, so a second exchange of the same code would fail with
|
|
690
|
+
// invalid_grant. If we already exchanged this exact code and hold seller
|
|
691
|
+
// credentials for this environment, treat the duplicate as a success no-op.
|
|
692
|
+
const existingRow = await this.getCurrentRow()
|
|
693
|
+
if (existingRow && existingRow.auth_code === input.authCode) {
|
|
694
|
+
const existingCreds = this.getEnvCreds(existingRow, env)
|
|
695
|
+
if (existingCreds.clientId && existingCreds.clientSecret) {
|
|
696
|
+
return
|
|
697
|
+
}
|
|
698
|
+
}
|
|
699
|
+
|
|
700
|
+
await this.saveOnboardCallback({ authCode: input.authCode, sharedId: input.sharedId })
|
|
701
|
+
const baseUrl = getPayPalApiBase(env)
|
|
702
|
+
|
|
703
|
+
const { onboarding } = await this.ensureSettingsDefaults()
|
|
704
|
+
const sellerNonce = (onboarding.seller_nonce || "").trim()
|
|
705
|
+
if (!sellerNonce) {
|
|
706
|
+
throw new Error("PayPal seller nonce is not configured. Set PAYPAL_SELLER_NONCE.")
|
|
707
|
+
}
|
|
708
|
+
|
|
709
|
+
const tokenBody = new URLSearchParams()
|
|
710
|
+
tokenBody.set("grant_type", "authorization_code")
|
|
711
|
+
tokenBody.set("code", input.authCode)
|
|
712
|
+
tokenBody.set("code_verifier", sellerNonce)
|
|
713
|
+
|
|
714
|
+
const basic = Buffer.from(`${input.sharedId}:`).toString("base64")
|
|
715
|
+
|
|
716
|
+
const tokenRes = await paypalFetch(`${baseUrl}/v1/oauth2/token`, {
|
|
717
|
+
method: "POST",
|
|
718
|
+
headers: {
|
|
719
|
+
"Content-Type": "application/x-www-form-urlencoded",
|
|
720
|
+
Authorization: `Basic ${basic}`,
|
|
721
|
+
"PayPal-Partner-Attribution-Id": this.bnCode,
|
|
722
|
+
},
|
|
723
|
+
body: tokenBody,
|
|
724
|
+
})
|
|
725
|
+
|
|
726
|
+
const tokenText = await tokenRes.text().catch(() => "")
|
|
727
|
+
let tokenJson: any = {}
|
|
728
|
+
try {
|
|
729
|
+
tokenJson = tokenText ? JSON.parse(tokenText) : {}
|
|
730
|
+
} catch (e: any) {
|
|
731
|
+
console.warn("[PayPal] Failed to parse token response JSON:", e?.message)
|
|
732
|
+
}
|
|
733
|
+
|
|
734
|
+
if (!tokenRes.ok) {
|
|
735
|
+
// Two redundant completion paths can race to exchange the same single-use
|
|
736
|
+
// code; the loser gets invalid_grant. If credentials were saved in the
|
|
737
|
+
// meantime (the other path won), the onboarding actually succeeded.
|
|
738
|
+
const racedRow = await this.getCurrentRow()
|
|
739
|
+
if (racedRow) {
|
|
740
|
+
const racedCreds = this.getEnvCreds(racedRow, env)
|
|
741
|
+
if (racedCreds.clientId && racedCreds.clientSecret) {
|
|
742
|
+
return
|
|
743
|
+
}
|
|
744
|
+
}
|
|
745
|
+
throw new Error(
|
|
746
|
+
`PayPal authorization_code token exchange failed (${tokenRes.status}): ${tokenText || JSON.stringify(tokenJson)}`
|
|
747
|
+
)
|
|
748
|
+
}
|
|
749
|
+
|
|
750
|
+
const sellerAccessToken = String(tokenJson.access_token || "")
|
|
751
|
+
if (!sellerAccessToken) {
|
|
752
|
+
throw new Error("PayPal token exchange succeeded but access_token is missing.")
|
|
753
|
+
}
|
|
754
|
+
|
|
755
|
+
const partnerMerchantId = await this.getPartnerMerchantId(env)
|
|
756
|
+
if (!partnerMerchantId) {
|
|
757
|
+
throw new Error("Missing PayPal partner merchant id configuration.")
|
|
758
|
+
}
|
|
759
|
+
|
|
760
|
+
const credRes = await paypalFetch(
|
|
761
|
+
`${baseUrl}/v1/customer/partners/${encodeURIComponent(partnerMerchantId)}/merchant-integrations/credentials/`,
|
|
762
|
+
{
|
|
763
|
+
method: "GET",
|
|
764
|
+
headers: {
|
|
765
|
+
"Content-Type": "application/json",
|
|
766
|
+
Authorization: `Bearer ${sellerAccessToken}`,
|
|
767
|
+
"PayPal-Partner-Attribution-Id": this.bnCode,
|
|
768
|
+
},
|
|
769
|
+
}
|
|
770
|
+
)
|
|
771
|
+
|
|
772
|
+
const credText = await credRes.text().catch(() => "")
|
|
773
|
+
let credJson: any = {}
|
|
774
|
+
try {
|
|
775
|
+
credJson = credText ? JSON.parse(credText) : {}
|
|
776
|
+
} catch (e: any) {
|
|
777
|
+
console.warn("[PayPal] Failed to parse token response JSON:", e?.message)
|
|
778
|
+
}
|
|
779
|
+
|
|
780
|
+
if (!credRes.ok) {
|
|
781
|
+
throw new Error(
|
|
782
|
+
`PayPal credentials fetch failed (${credRes.status}): ${credText || JSON.stringify(credJson)}`
|
|
783
|
+
)
|
|
784
|
+
}
|
|
785
|
+
|
|
786
|
+
const clientId = String(credJson.client_id || credJson.clientId || "")
|
|
787
|
+
const clientSecret = String(credJson.client_secret || credJson.clientSecret || "")
|
|
788
|
+
if (!clientId || !clientSecret) {
|
|
789
|
+
throw new Error(
|
|
790
|
+
`PayPal credentials response missing client_id/client_secret. Keys: ${Object.keys(credJson || {}).join(", ")}`
|
|
791
|
+
)
|
|
792
|
+
}
|
|
793
|
+
|
|
794
|
+
let sellerEmail = this.extractSellerEmail(credJson, tokenJson)
|
|
795
|
+
let sellerMerchantId =
|
|
796
|
+
String(credJson.payer_id || credJson.merchant_id || tokenJson.payer_id || tokenJson.merchant_id || "").trim() ||
|
|
797
|
+
null
|
|
798
|
+
|
|
799
|
+
if (!sellerEmail) {
|
|
800
|
+
const merchantCandidates = [
|
|
801
|
+
String(credJson.payer_id || "").trim(),
|
|
802
|
+
String(credJson.merchant_id || "").trim(),
|
|
803
|
+
String(tokenJson.payer_id || "").trim(),
|
|
804
|
+
String(tokenJson.merchant_id || "").trim(),
|
|
805
|
+
].filter(Boolean).filter((v, i, arr) => arr.indexOf(v) === i)
|
|
806
|
+
|
|
807
|
+
for (const merchantId of merchantCandidates) {
|
|
808
|
+
try {
|
|
809
|
+
const merchantDetails = await this.fetchMerchantIntegrationDetails(env, merchantId, sellerAccessToken)
|
|
810
|
+
sellerMerchantId = sellerMerchantId || merchantId
|
|
811
|
+
sellerEmail = this.extractSellerEmail(merchantDetails)
|
|
812
|
+
if (sellerEmail) {
|
|
813
|
+
break
|
|
814
|
+
}
|
|
815
|
+
} catch (e: any) {
|
|
816
|
+
console.warn(`[PayPal] Merchant integration lookup for ${merchantId} failed:`, e?.message || e)
|
|
817
|
+
}
|
|
818
|
+
}
|
|
819
|
+
}
|
|
820
|
+
|
|
821
|
+
await this.saveSellerCredentials({
|
|
822
|
+
clientId,
|
|
823
|
+
clientSecret,
|
|
824
|
+
sellerMerchantId,
|
|
825
|
+
sellerEmail,
|
|
826
|
+
})
|
|
827
|
+
|
|
828
|
+
if (!sellerEmail && sellerMerchantId) {
|
|
829
|
+
try {
|
|
830
|
+
const appAccessToken = await this.getAppAccessToken()
|
|
831
|
+
const details = await this.fetchMerchantIntegrationDetails(env, sellerMerchantId, appAccessToken)
|
|
832
|
+
sellerEmail = this.extractSellerEmail(details)
|
|
833
|
+
if (sellerEmail) {
|
|
834
|
+
await this.saveSellerCredentials({ clientId, clientSecret, sellerMerchantId, sellerEmail })
|
|
835
|
+
}
|
|
836
|
+
} catch (e: any) {
|
|
837
|
+
console.warn("[PayPal] Post-save merchant_id email lookup failed:", e?.message || e)
|
|
838
|
+
}
|
|
839
|
+
}
|
|
840
|
+
}
|
|
841
|
+
|
|
842
|
+
async saveSellerCredentials(input: {
|
|
843
|
+
clientId: string
|
|
844
|
+
clientSecret: string
|
|
845
|
+
sellerMerchantId?: string | null
|
|
846
|
+
sellerEmail?: string | null
|
|
847
|
+
environment?: Environment
|
|
848
|
+
}) {
|
|
849
|
+
const row = await this.getCurrentRow()
|
|
850
|
+
const currentEnv = await this.getCurrentEnvironment()
|
|
851
|
+
const env = (input.environment || currentEnv) as Environment
|
|
852
|
+
|
|
853
|
+
const existingCreds = row ? this.getEnvCreds(row, env) : {}
|
|
854
|
+
const nextSellerMerchantId =
|
|
855
|
+
(input.sellerMerchantId || "").trim() || existingCreds.sellerMerchantId || row?.seller_merchant_id || null
|
|
856
|
+
const nextSellerEmail =
|
|
857
|
+
(input.sellerEmail || "").trim() || existingCreds.sellerEmail || row?.seller_email || null
|
|
858
|
+
|
|
859
|
+
// Encrypt once and store the same ciphertext in both the metadata copy and
|
|
860
|
+
// the denormalized column (no-op when encryption is disabled).
|
|
861
|
+
const storedClientSecret = encryptSecret(input.clientSecret)
|
|
862
|
+
|
|
863
|
+
const nextCreds = {
|
|
864
|
+
client_id: input.clientId,
|
|
865
|
+
client_secret: storedClientSecret,
|
|
866
|
+
merchant_id: nextSellerMerchantId,
|
|
867
|
+
seller_merchant_id: nextSellerMerchantId,
|
|
868
|
+
seller_email: nextSellerEmail,
|
|
869
|
+
}
|
|
870
|
+
|
|
871
|
+
if (!row) {
|
|
872
|
+
const created = await this.createPayPalConnections({
|
|
873
|
+
environment: env,
|
|
874
|
+
status: "connected",
|
|
875
|
+
seller_client_id: input.clientId,
|
|
876
|
+
seller_client_secret: storedClientSecret,
|
|
877
|
+
seller_merchant_id: nextSellerMerchantId,
|
|
878
|
+
seller_email: nextSellerEmail,
|
|
879
|
+
app_access_token: null,
|
|
880
|
+
app_access_token_expires_at: null,
|
|
881
|
+
metadata: {
|
|
882
|
+
credentials: {
|
|
883
|
+
[env]: nextCreds,
|
|
884
|
+
},
|
|
885
|
+
active_environment: env,
|
|
886
|
+
},
|
|
887
|
+
})
|
|
888
|
+
await this.recordAuditEvent("credentials_saved", {
|
|
889
|
+
environment: env,
|
|
890
|
+
client_id: input.clientId,
|
|
891
|
+
})
|
|
892
|
+
await this.ensureWebhookRegistration()
|
|
893
|
+
return created
|
|
894
|
+
}
|
|
895
|
+
|
|
896
|
+
const meta = (row.metadata || {}) as any
|
|
897
|
+
const creds = { ...(meta.credentials || {}) }
|
|
898
|
+
creds[env] = {
|
|
899
|
+
...(creds[env] || {}),
|
|
900
|
+
...nextCreds,
|
|
901
|
+
}
|
|
902
|
+
|
|
903
|
+
const updated = await this.updatePayPalConnections({
|
|
904
|
+
id: row.id,
|
|
905
|
+
status: "connected",
|
|
906
|
+
seller_client_id: input.clientId,
|
|
907
|
+
seller_client_secret: storedClientSecret,
|
|
908
|
+
seller_merchant_id: nextSellerMerchantId,
|
|
909
|
+
seller_email: nextSellerEmail,
|
|
910
|
+
app_access_token: null,
|
|
911
|
+
app_access_token_expires_at: null,
|
|
912
|
+
metadata: {
|
|
913
|
+
...(row.metadata || {}),
|
|
914
|
+
credentials: creds,
|
|
915
|
+
active_environment: env,
|
|
916
|
+
},
|
|
917
|
+
})
|
|
918
|
+
await this.recordAuditEvent("credentials_saved", {
|
|
919
|
+
environment: env,
|
|
920
|
+
client_id: input.clientId,
|
|
921
|
+
})
|
|
922
|
+
await this.ensureWebhookRegistration()
|
|
923
|
+
return updated
|
|
924
|
+
}
|
|
925
|
+
|
|
926
|
+
async saveAndHydrateSellerCredentials(input: {
|
|
927
|
+
clientId: string
|
|
928
|
+
clientSecret: string
|
|
929
|
+
environment?: Environment
|
|
930
|
+
}) {
|
|
931
|
+
const env = (input.environment || (await this.getCurrentEnvironment())) as Environment
|
|
932
|
+
|
|
933
|
+
await this.saveSellerCredentials({
|
|
934
|
+
clientId: input.clientId,
|
|
935
|
+
clientSecret: input.clientSecret,
|
|
936
|
+
environment: env,
|
|
937
|
+
})
|
|
938
|
+
|
|
939
|
+
try {
|
|
940
|
+
const hydrated = await this.fetchSellerProfileFromDirectCredentials(env, {
|
|
941
|
+
clientId: input.clientId,
|
|
942
|
+
clientSecret: input.clientSecret,
|
|
943
|
+
})
|
|
944
|
+
|
|
945
|
+
if (hydrated.sellerEmail || hydrated.sellerMerchantId) {
|
|
946
|
+
await this.saveSellerCredentials({
|
|
947
|
+
clientId: input.clientId,
|
|
948
|
+
clientSecret: input.clientSecret,
|
|
949
|
+
sellerMerchantId: hydrated.sellerMerchantId,
|
|
950
|
+
sellerEmail: hydrated.sellerEmail,
|
|
951
|
+
environment: env,
|
|
952
|
+
})
|
|
953
|
+
}
|
|
954
|
+
|
|
955
|
+
const refreshedRow = await this.getCurrentRow()
|
|
956
|
+
if (refreshedRow) {
|
|
957
|
+
await this.syncRowFieldsFromMetadata(refreshedRow, env)
|
|
958
|
+
}
|
|
959
|
+
} catch (e: any) {
|
|
960
|
+
console.warn("[PayPal] saveAndHydrateSellerCredentials lookup failed:", e?.message || e)
|
|
961
|
+
}
|
|
962
|
+
|
|
963
|
+
// This is a write context (credentials were just saved), so it is allowed to
|
|
964
|
+
// backfill the seller profile if it is still missing.
|
|
965
|
+
return await this.getStatus(env, { hydrateMissingProfile: true })
|
|
966
|
+
}
|
|
967
|
+
|
|
968
|
+
private async resolveWebhookUrl() {
|
|
969
|
+
const { onboarding } = await this.ensureSettingsDefaults()
|
|
970
|
+
const base = String(onboarding.backend_url || "").replace(/\/$/, "")
|
|
971
|
+
if (!base) {
|
|
972
|
+
throw new Error("PayPal backend URL is not configured.")
|
|
973
|
+
}
|
|
974
|
+
// The /hooks namespace has no publishable-key guard. PayPal cannot send
|
|
975
|
+
// Medusa's x-publishable-api-key header, so a webhook registered at the
|
|
976
|
+
// old /store/paypal/webhook path is rejected before the handler runs.
|
|
977
|
+
return `${base}/hooks/paypal/webhook`
|
|
978
|
+
}
|
|
979
|
+
|
|
980
|
+
/** Legacy webhook path (blocked by Medusa's store publishable-key guard). */
|
|
981
|
+
private async resolveLegacyWebhookUrl() {
|
|
982
|
+
const { onboarding } = await this.ensureSettingsDefaults()
|
|
983
|
+
const base = String(onboarding.backend_url || "").replace(/\/$/, "")
|
|
984
|
+
if (!base) return ""
|
|
985
|
+
return `${base}/store/paypal/webhook`
|
|
986
|
+
}
|
|
987
|
+
|
|
988
|
+
private isLocalWebhookUrl(url: string) {
|
|
989
|
+
try {
|
|
990
|
+
const parsed = new URL(url)
|
|
991
|
+
return ["localhost", "127.0.0.1", "::1"].includes(parsed.hostname)
|
|
992
|
+
} catch {
|
|
993
|
+
return false
|
|
994
|
+
}
|
|
995
|
+
}
|
|
996
|
+
|
|
997
|
+
// Only probe PayPal for a stale legacy webhook URL once per process per
|
|
998
|
+
// environment — this runs on admin status reads and must stay cheap.
|
|
999
|
+
private webhookUrlMigrationChecked: Record<string, boolean> = {}
|
|
1000
|
+
private webhookHealScheduled: Record<string, boolean> = {}
|
|
1001
|
+
|
|
1002
|
+
private async migrateLegacyWebhookUrl(env: string, webhookId: string) {
|
|
1003
|
+
if (this.webhookUrlMigrationChecked[env]) return
|
|
1004
|
+
this.webhookUrlMigrationChecked[env] = true
|
|
1005
|
+
|
|
1006
|
+
const newUrl = await this.resolveWebhookUrl().catch(() => "")
|
|
1007
|
+
const legacyUrl = await this.resolveLegacyWebhookUrl()
|
|
1008
|
+
if (!newUrl || !legacyUrl || this.isLocalWebhookUrl(newUrl)) return
|
|
1009
|
+
|
|
1010
|
+
const accessToken = await this.getAppAccessToken()
|
|
1011
|
+
const baseUrl = getPayPalApiBase(env)
|
|
1012
|
+
|
|
1013
|
+
const getResp = await paypalFetch(
|
|
1014
|
+
`${baseUrl}/v1/notifications/webhooks/${encodeURIComponent(webhookId)}`,
|
|
1015
|
+
{
|
|
1016
|
+
headers: {
|
|
1017
|
+
Authorization: `Bearer ${accessToken}`,
|
|
1018
|
+
"Content-Type": "application/json",
|
|
1019
|
+
"PayPal-Partner-Attribution-Id": this.bnCode,
|
|
1020
|
+
},
|
|
1021
|
+
}
|
|
1022
|
+
)
|
|
1023
|
+
const getJson = await getResp.json().catch(() => ({}))
|
|
1024
|
+
if (!getResp.ok) return
|
|
1025
|
+
|
|
1026
|
+
const currentUrl = String(getJson?.url || "")
|
|
1027
|
+
if (currentUrl !== legacyUrl) return
|
|
1028
|
+
|
|
1029
|
+
const patchResp = await paypalFetch(
|
|
1030
|
+
`${baseUrl}/v1/notifications/webhooks/${encodeURIComponent(webhookId)}`,
|
|
1031
|
+
{
|
|
1032
|
+
method: "PATCH",
|
|
1033
|
+
headers: {
|
|
1034
|
+
Authorization: `Bearer ${accessToken}`,
|
|
1035
|
+
"Content-Type": "application/json",
|
|
1036
|
+
"PayPal-Partner-Attribution-Id": this.bnCode,
|
|
1037
|
+
},
|
|
1038
|
+
body: JSON.stringify([
|
|
1039
|
+
{ op: "replace", path: "/url", value: newUrl },
|
|
1040
|
+
]),
|
|
1041
|
+
}
|
|
1042
|
+
)
|
|
1043
|
+
if (patchResp.ok) {
|
|
1044
|
+
await this.recordAuditEvent("webhook_url_migrated", {
|
|
1045
|
+
environment: env,
|
|
1046
|
+
webhook_id: webhookId,
|
|
1047
|
+
from: legacyUrl,
|
|
1048
|
+
to: newUrl,
|
|
1049
|
+
})
|
|
1050
|
+
console.info(
|
|
1051
|
+
`[PayPal] migrated webhook ${webhookId} URL from ${legacyUrl} to ${newUrl}`
|
|
1052
|
+
)
|
|
1053
|
+
}
|
|
1054
|
+
}
|
|
1055
|
+
|
|
1056
|
+
private async ensureWebhookRegistration() {
|
|
1057
|
+
const env = await this.getCurrentEnvironment()
|
|
1058
|
+
const { apiDetails } = await this.ensureSettingsDefaults()
|
|
1059
|
+
const webhookIds = { ...(apiDetails.webhook_ids || {}) } as Record<string, string>
|
|
1060
|
+
|
|
1061
|
+
if (webhookIds[env]) {
|
|
1062
|
+
// Existing installs registered the webhook at /store/paypal/webhook,
|
|
1063
|
+
// which Medusa's publishable-key middleware blocks for external callers.
|
|
1064
|
+
// Migrate the registered URL to /hooks/paypal/webhook in place
|
|
1065
|
+
// (best-effort — a failure keeps the stored id and current behavior).
|
|
1066
|
+
await this.migrateLegacyWebhookUrl(env, webhookIds[env]).catch((e: any) => {
|
|
1067
|
+
console.warn(
|
|
1068
|
+
"[PayPal] webhook URL migration check failed:",
|
|
1069
|
+
e?.message || e
|
|
1070
|
+
)
|
|
1071
|
+
})
|
|
1072
|
+
return webhookIds[env]
|
|
1073
|
+
}
|
|
1074
|
+
|
|
1075
|
+
const accessToken = await this.getAppAccessToken()
|
|
1076
|
+
const baseUrl = getPayPalApiBase(env)
|
|
1077
|
+
const webhookUrl = await this.resolveWebhookUrl()
|
|
1078
|
+
|
|
1079
|
+
if (this.isLocalWebhookUrl(webhookUrl)) {
|
|
1080
|
+
await this.recordAuditEvent("webhook_skipped_localhost", {
|
|
1081
|
+
environment: env,
|
|
1082
|
+
webhook_url: webhookUrl,
|
|
1083
|
+
})
|
|
1084
|
+
return webhookIds[env] || ""
|
|
1085
|
+
}
|
|
1086
|
+
|
|
1087
|
+
const listResp = await paypalFetch(`${baseUrl}/v1/notifications/webhooks`, {
|
|
1088
|
+
headers: {
|
|
1089
|
+
Authorization: `Bearer ${accessToken}`,
|
|
1090
|
+
"Content-Type": "application/json",
|
|
1091
|
+
"PayPal-Partner-Attribution-Id": this.bnCode,
|
|
1092
|
+
},
|
|
1093
|
+
})
|
|
1094
|
+
|
|
1095
|
+
const listJson = await listResp.json().catch(() => ({}))
|
|
1096
|
+
if (!listResp.ok) {
|
|
1097
|
+
throw new Error(`PayPal webhook list failed (${listResp.status}): ${JSON.stringify(listJson)}`)
|
|
1098
|
+
}
|
|
1099
|
+
|
|
1100
|
+
const existing = Array.isArray(listJson?.webhooks)
|
|
1101
|
+
? listJson.webhooks.find((hook: any) => hook?.url === webhookUrl)
|
|
1102
|
+
: null
|
|
1103
|
+
|
|
1104
|
+
let webhookId = existing?.id ? String(existing.id) : ""
|
|
1105
|
+
|
|
1106
|
+
if (!webhookId) {
|
|
1107
|
+
const createResp = await paypalFetch(`${baseUrl}/v1/notifications/webhooks`, {
|
|
1108
|
+
method: "POST",
|
|
1109
|
+
headers: {
|
|
1110
|
+
Authorization: `Bearer ${accessToken}`,
|
|
1111
|
+
"Content-Type": "application/json",
|
|
1112
|
+
"PayPal-Partner-Attribution-Id": this.bnCode,
|
|
1113
|
+
},
|
|
1114
|
+
body: JSON.stringify({
|
|
1115
|
+
url: webhookUrl,
|
|
1116
|
+
event_types: [
|
|
1117
|
+
{ name: "CHECKOUT.ORDER.APPROVED" },
|
|
1118
|
+
{ name: "CHECKOUT.ORDER.CANCELLED" },
|
|
1119
|
+
{ name: "PAYMENT.CAPTURE.COMPLETED" },
|
|
1120
|
+
{ name: "PAYMENT.CAPTURE.DENIED" },
|
|
1121
|
+
{ name: "PAYMENT.CAPTURE.REFUNDED" },
|
|
1122
|
+
{ name: "PAYMENT.CAPTURE.REVERSED" },
|
|
1123
|
+
{ name: "PAYMENT.AUTHORIZATION.CREATED" },
|
|
1124
|
+
{ name: "PAYMENT.AUTHORIZATION.VOIDED" },
|
|
1125
|
+
{ name: "PAYMENT.AUTHORIZATION.DENIED" },
|
|
1126
|
+
{ name: "PAYMENT.REFUND.COMPLETED" },
|
|
1127
|
+
{ name: "PAYMENT.REFUND.DENIED" },
|
|
1128
|
+
],
|
|
1129
|
+
}),
|
|
1130
|
+
})
|
|
1131
|
+
|
|
1132
|
+
const createJson = await createResp.json().catch(() => ({}))
|
|
1133
|
+
if (!createResp.ok) {
|
|
1134
|
+
throw new Error(
|
|
1135
|
+
`PayPal webhook create failed (${createResp.status}): ${JSON.stringify(createJson)}`
|
|
1136
|
+
)
|
|
1137
|
+
}
|
|
1138
|
+
|
|
1139
|
+
webhookId = String(createJson?.id || "")
|
|
1140
|
+
}
|
|
1141
|
+
|
|
1142
|
+
if (!webhookId) {
|
|
1143
|
+
throw new Error("PayPal webhook registration did not return an id")
|
|
1144
|
+
}
|
|
1145
|
+
|
|
1146
|
+
const nextWebhookIds = { ...webhookIds, [env]: webhookId }
|
|
1147
|
+
await this.saveSettings({
|
|
1148
|
+
api_details: {
|
|
1149
|
+
...apiDetails,
|
|
1150
|
+
webhook_ids: nextWebhookIds,
|
|
1151
|
+
},
|
|
1152
|
+
})
|
|
1153
|
+
|
|
1154
|
+
await this.recordAuditEvent("webhook_registered", {
|
|
1155
|
+
environment: env,
|
|
1156
|
+
webhook_id: webhookId,
|
|
1157
|
+
webhook_url: webhookUrl,
|
|
1158
|
+
})
|
|
1159
|
+
|
|
1160
|
+
return webhookId
|
|
1161
|
+
}
|
|
1162
|
+
|
|
1163
|
+
private maskValue(value?: string | null, visibleChars = 4) {
|
|
1164
|
+
if (!value) return null
|
|
1165
|
+
const trimmed = String(value)
|
|
1166
|
+
if (trimmed.length <= visibleChars) {
|
|
1167
|
+
return "•".repeat(trimmed.length)
|
|
1168
|
+
}
|
|
1169
|
+
return `${"•".repeat(Math.max(0, trimmed.length - visibleChars))}${trimmed.slice(
|
|
1170
|
+
-visibleChars
|
|
1171
|
+
)}`
|
|
1172
|
+
}
|
|
1173
|
+
|
|
1174
|
+
/**
|
|
1175
|
+
* Report the current connection status.
|
|
1176
|
+
*
|
|
1177
|
+
* `hydrateMissingProfile` is opt-in and OFF by default: status is read on
|
|
1178
|
+
* `GET /admin/paypal/status` (and other read-only routes), where it must be a
|
|
1179
|
+
* safe, side-effect-free read. The seller-profile backfill makes an outbound
|
|
1180
|
+
* PayPal call and persists to the DB, so it only runs from write contexts
|
|
1181
|
+
* (e.g. saving credentials) that explicitly request it.
|
|
1182
|
+
*/
|
|
1183
|
+
async getStatus(
|
|
1184
|
+
envOverride?: Environment,
|
|
1185
|
+
opts: { hydrateMissingProfile?: boolean } = {}
|
|
1186
|
+
) {
|
|
1187
|
+
const row = await this.getCurrentRow()
|
|
1188
|
+
const env = envOverride ?? (await this.getCurrentEnvironment())
|
|
1189
|
+
|
|
1190
|
+
if (!row) {
|
|
1191
|
+
return { environment: env, status: "disconnected" as Status, seller_client_id_present: false }
|
|
1192
|
+
}
|
|
1193
|
+
|
|
1194
|
+
const c = this.getEnvCreds(row, env)
|
|
1195
|
+
const hasCreds = !!(c.clientId && c.clientSecret)
|
|
1196
|
+
let sellerEmail: string | null = c.sellerEmail || row.seller_email || null
|
|
1197
|
+
let sellerMerchantId: string | null = c.sellerMerchantId || row.seller_merchant_id || null
|
|
1198
|
+
|
|
1199
|
+
// Self-heal the webhook registration for already-connected merchants:
|
|
1200
|
+
// installs that registered the webhook at the old (blocked)
|
|
1201
|
+
// /store/paypal/webhook path get migrated to /hooks/paypal/webhook the
|
|
1202
|
+
// first time an admin views the status page after upgrading. Fire and
|
|
1203
|
+
// forget — status reads must never block on PayPal, and the migration is
|
|
1204
|
+
// throttled to once per process per environment internally.
|
|
1205
|
+
if (hasCreds && !this.webhookHealScheduled[env]) {
|
|
1206
|
+
this.webhookHealScheduled[env] = true
|
|
1207
|
+
void this.ensureWebhookRegistration().catch((e: any) => {
|
|
1208
|
+
console.warn("[PayPal] webhook self-heal failed:", e?.message || e)
|
|
1209
|
+
})
|
|
1210
|
+
}
|
|
1211
|
+
|
|
1212
|
+
if (!sellerEmail && hasCreds && opts.hydrateMissingProfile) {
|
|
1213
|
+
try {
|
|
1214
|
+
const hydrated = await this.fetchSellerProfileFromDirectCredentials(env)
|
|
1215
|
+
if (hydrated.sellerEmail || hydrated.sellerMerchantId) {
|
|
1216
|
+
await this.saveSellerCredentials({
|
|
1217
|
+
clientId: c.clientId!,
|
|
1218
|
+
clientSecret: c.clientSecret!,
|
|
1219
|
+
sellerMerchantId: hydrated.sellerMerchantId || sellerMerchantId,
|
|
1220
|
+
sellerEmail: hydrated.sellerEmail || sellerEmail,
|
|
1221
|
+
environment: env,
|
|
1222
|
+
})
|
|
1223
|
+
|
|
1224
|
+
const refreshedRow = await this.getCurrentRow()
|
|
1225
|
+
if (refreshedRow) {
|
|
1226
|
+
const refreshedCreds = this.getEnvCreds(refreshedRow, env)
|
|
1227
|
+
sellerEmail = refreshedCreds.sellerEmail || refreshedRow.seller_email || sellerEmail
|
|
1228
|
+
sellerMerchantId =
|
|
1229
|
+
refreshedCreds.sellerMerchantId || refreshedRow.seller_merchant_id || sellerMerchantId
|
|
1230
|
+
}
|
|
1231
|
+
}
|
|
1232
|
+
} catch (e: any) {
|
|
1233
|
+
console.warn("[PayPal] status direct credential lookup failed:", e?.message || e)
|
|
1234
|
+
}
|
|
1235
|
+
}
|
|
1236
|
+
|
|
1237
|
+
return {
|
|
1238
|
+
environment: env,
|
|
1239
|
+
status: (hasCreds ? "connected" : "disconnected") as Status,
|
|
1240
|
+
shared_id: row.shared_id ?? null,
|
|
1241
|
+
auth_code: row.auth_code ? "***stored***" : null,
|
|
1242
|
+
seller_client_id_present: hasCreds,
|
|
1243
|
+
seller_client_id_masked: this.maskValue(c.clientId),
|
|
1244
|
+
seller_client_secret_masked: c.clientSecret ? "••••••••" : null,
|
|
1245
|
+
seller_merchant_id: sellerMerchantId,
|
|
1246
|
+
seller_email: sellerEmail,
|
|
1247
|
+
updated_at: (row.updated_at as any)?.toISOString?.() ?? null,
|
|
1248
|
+
}
|
|
1249
|
+
}
|
|
1250
|
+
|
|
1251
|
+
async disconnect() {
|
|
1252
|
+
const row = await this.getCurrentRow()
|
|
1253
|
+
if (!row) return
|
|
1254
|
+
const env = await this.getCurrentEnvironment()
|
|
1255
|
+
|
|
1256
|
+
const meta = (row.metadata || {}) as any
|
|
1257
|
+
const creds = { ...(meta.credentials || {}) }
|
|
1258
|
+
delete creds[env]
|
|
1259
|
+
|
|
1260
|
+
const hasAnyCreds = Object.values(creds).some((v: any) => {
|
|
1261
|
+
return v && typeof v === "object" && (v as any).client_id && (v as any).client_secret
|
|
1262
|
+
})
|
|
1263
|
+
|
|
1264
|
+
await this.updatePayPalConnections({
|
|
1265
|
+
id: row.id,
|
|
1266
|
+
status: hasAnyCreds ? "connected" : "disconnected",
|
|
1267
|
+
shared_id: null,
|
|
1268
|
+
auth_code: null,
|
|
1269
|
+
seller_client_id: null,
|
|
1270
|
+
seller_client_secret: null,
|
|
1271
|
+
seller_merchant_id: null,
|
|
1272
|
+
seller_email: null,
|
|
1273
|
+
app_access_token: null,
|
|
1274
|
+
app_access_token_expires_at: null,
|
|
1275
|
+
metadata: {
|
|
1276
|
+
...(row.metadata || {}),
|
|
1277
|
+
credentials: creds,
|
|
1278
|
+
active_environment: env,
|
|
1279
|
+
},
|
|
1280
|
+
})
|
|
1281
|
+
const updated = await this.getCurrentRow()
|
|
1282
|
+
if (updated) {
|
|
1283
|
+
await this.syncRowFieldsFromMetadata(updated, env)
|
|
1284
|
+
}
|
|
1285
|
+
await this.recordAuditEvent("disconnected", { environment: env })
|
|
1286
|
+
}
|
|
1287
|
+
|
|
1288
|
+
async getAppAccessToken(): Promise<string> {
|
|
1289
|
+
const row = await this.getCurrentRow()
|
|
1290
|
+
|
|
1291
|
+
if (!row) {
|
|
1292
|
+
throw new Error("PayPal connection row not found. Please complete onboarding.")
|
|
1293
|
+
}
|
|
1294
|
+
|
|
1295
|
+
const expiresAt = row.app_access_token_expires_at ? new Date(row.app_access_token_expires_at as string) : null
|
|
1296
|
+
if (row.app_access_token && expiresAt) {
|
|
1297
|
+
const msLeft = expiresAt.getTime() - Date.now()
|
|
1298
|
+
// Token is encrypted at rest when a key is configured; decrypt the cached
|
|
1299
|
+
// value (legacy plaintext passes through unchanged).
|
|
1300
|
+
if (msLeft > 2 * 60 * 1000) return decryptSecret(row.app_access_token as string) as string
|
|
1301
|
+
}
|
|
1302
|
+
|
|
1303
|
+
if (this.tokenRefreshPromise) {
|
|
1304
|
+
return this.tokenRefreshPromise
|
|
1305
|
+
}
|
|
1306
|
+
|
|
1307
|
+
this.tokenRefreshPromise = this.refreshAccessToken(row).finally(() => {
|
|
1308
|
+
this.tokenRefreshPromise = null
|
|
1309
|
+
})
|
|
1310
|
+
|
|
1311
|
+
return this.tokenRefreshPromise
|
|
1312
|
+
}
|
|
1313
|
+
|
|
1314
|
+
private async refreshAccessToken(row: { id: string }): Promise<string> {
|
|
1315
|
+
const env = await this.getCurrentEnvironment()
|
|
1316
|
+
const creds = await this.getActiveCredentials()
|
|
1317
|
+
const baseUrl = getPayPalApiBase(env)
|
|
1318
|
+
const basic = Buffer.from(`${creds.client_id}:${creds.client_secret}`).toString("base64")
|
|
1319
|
+
|
|
1320
|
+
const body = new URLSearchParams()
|
|
1321
|
+
body.set("grant_type", "client_credentials")
|
|
1322
|
+
|
|
1323
|
+
const res = await paypalFetch(`${baseUrl}/v1/oauth2/token`, {
|
|
1324
|
+
method: "POST",
|
|
1325
|
+
headers: {
|
|
1326
|
+
"Content-Type": "application/x-www-form-urlencoded",
|
|
1327
|
+
Authorization: `Basic ${basic}`,
|
|
1328
|
+
"PayPal-Partner-Attribution-Id": this.bnCode,
|
|
1329
|
+
},
|
|
1330
|
+
body,
|
|
1331
|
+
signal: AbortSignal.timeout(30_000),
|
|
1332
|
+
})
|
|
1333
|
+
|
|
1334
|
+
const json = await res.json().catch(() => ({}))
|
|
1335
|
+
if (!res.ok) throw new Error(`PayPal client_credentials failed (${res.status}): ${JSON.stringify(json)}`)
|
|
1336
|
+
|
|
1337
|
+
const accessToken = String(json.access_token || "")
|
|
1338
|
+
if (!accessToken) {
|
|
1339
|
+
throw new Error("PayPal client_credentials succeeded but access_token is missing.")
|
|
1340
|
+
}
|
|
1341
|
+
const expiresIn = Number(json.expires_in || 3600)
|
|
1342
|
+
const newExpiresAt = new Date(Date.now() + expiresIn * 1000)
|
|
1343
|
+
|
|
1344
|
+
await this.updatePayPalConnections({
|
|
1345
|
+
id: row.id,
|
|
1346
|
+
app_access_token: encryptSecret(accessToken),
|
|
1347
|
+
app_access_token_expires_at: newExpiresAt as unknown as Date,
|
|
1348
|
+
})
|
|
1349
|
+
|
|
1350
|
+
return accessToken
|
|
1351
|
+
}
|
|
1352
|
+
|
|
1353
|
+
async generateClientToken(opts?: { locale?: string }): Promise<string> {
|
|
1354
|
+
const env = await this.getCurrentEnvironment()
|
|
1355
|
+
const baseUrl = getPayPalApiBase(env)
|
|
1356
|
+
|
|
1357
|
+
const accessToken = await this.getAppAccessToken()
|
|
1358
|
+
|
|
1359
|
+
const res = await paypalFetch(`${baseUrl}/v1/identity/generate-token`, {
|
|
1360
|
+
method: "POST",
|
|
1361
|
+
headers: {
|
|
1362
|
+
Authorization: `Bearer ${accessToken}`,
|
|
1363
|
+
"Content-Type": "application/json",
|
|
1364
|
+
Accept: "application/json",
|
|
1365
|
+
"PayPal-Partner-Attribution-Id": this.bnCode,
|
|
1366
|
+
...(opts?.locale ? { "Accept-Language": opts.locale } : {}),
|
|
1367
|
+
},
|
|
1368
|
+
})
|
|
1369
|
+
|
|
1370
|
+
const json = await res.json().catch(() => ({}))
|
|
1371
|
+
if (!res.ok) {
|
|
1372
|
+
throw new Error(`PayPal generate-token failed (${res.status}): ${JSON.stringify(json)}`)
|
|
1373
|
+
}
|
|
1374
|
+
|
|
1375
|
+
const token = String((json as any)?.client_token || "")
|
|
1376
|
+
if (!token) {
|
|
1377
|
+
throw new Error("PayPal client_token is missing in generate-token response")
|
|
1378
|
+
}
|
|
1379
|
+
|
|
1380
|
+
return token
|
|
1381
|
+
}
|
|
1382
|
+
|
|
1383
|
+
async getSettings() {
|
|
1384
|
+
// Deterministic singleton read: always the OLDEST row. If a first-boot race
|
|
1385
|
+
// ever created a duplicate settings row, every reader (here and the
|
|
1386
|
+
// credential resolver's raw read) must agree on the same winner — ordering
|
|
1387
|
+
// by created_at ASC guarantees that; an unordered `take: 1` does not.
|
|
1388
|
+
const rows = await this.listPayPalSettings(
|
|
1389
|
+
{},
|
|
1390
|
+
{ take: 1, order: { created_at: "ASC" } }
|
|
1391
|
+
)
|
|
1392
|
+
const row = rows?.[0]
|
|
1393
|
+
return { data: (row?.data || {}) as Record<string, any> }
|
|
1394
|
+
}
|
|
1395
|
+
|
|
1396
|
+
private deepMerge(
|
|
1397
|
+
target: Record<string, any>,
|
|
1398
|
+
source: Record<string, any>
|
|
1399
|
+
): Record<string, any> {
|
|
1400
|
+
const result = { ...target }
|
|
1401
|
+
for (const key of Object.keys(source)) {
|
|
1402
|
+
const sv = source[key]
|
|
1403
|
+
const tv = target[key]
|
|
1404
|
+
if (
|
|
1405
|
+
sv !== null &&
|
|
1406
|
+
typeof sv === "object" &&
|
|
1407
|
+
!Array.isArray(sv) &&
|
|
1408
|
+
tv !== null &&
|
|
1409
|
+
typeof tv === "object" &&
|
|
1410
|
+
!Array.isArray(tv)
|
|
1411
|
+
) {
|
|
1412
|
+
result[key] = this.deepMerge(tv, sv)
|
|
1413
|
+
} else {
|
|
1414
|
+
result[key] = sv
|
|
1415
|
+
}
|
|
1416
|
+
}
|
|
1417
|
+
return result
|
|
1418
|
+
}
|
|
1419
|
+
|
|
1420
|
+
async saveSettings(patch: Record<string, any>) {
|
|
1421
|
+
// Same deterministic ordering as getSettings so reads and writes always
|
|
1422
|
+
// target the same singleton row.
|
|
1423
|
+
const rows = await this.listPayPalSettings(
|
|
1424
|
+
{},
|
|
1425
|
+
{ take: 1, order: { created_at: "ASC" } }
|
|
1426
|
+
)
|
|
1427
|
+
const row = rows?.[0]
|
|
1428
|
+
const current = (row?.data || {}) as Record<string, any>
|
|
1429
|
+
|
|
1430
|
+
const next = this.deepMerge(current, patch)
|
|
1431
|
+
|
|
1432
|
+
if (!row) {
|
|
1433
|
+
const created = await this.createPayPalSettings({ data: next })
|
|
1434
|
+
// First-boot race guard: if a concurrent save created a row a moment
|
|
1435
|
+
// earlier, the ASC ordering means that row is the canonical singleton —
|
|
1436
|
+
// merge this patch into it instead of leaving a divergent duplicate.
|
|
1437
|
+
const recheck = await this.listPayPalSettings(
|
|
1438
|
+
{},
|
|
1439
|
+
{ take: 1, order: { created_at: "ASC" } }
|
|
1440
|
+
)
|
|
1441
|
+
const canonical = recheck?.[0]
|
|
1442
|
+
if (canonical && canonical.id !== created.id) {
|
|
1443
|
+
const merged = this.deepMerge(
|
|
1444
|
+
(canonical.data || {}) as Record<string, any>,
|
|
1445
|
+
patch
|
|
1446
|
+
)
|
|
1447
|
+
await this.updatePayPalSettings({ id: canonical.id, data: merged })
|
|
1448
|
+
return { data: merged }
|
|
1449
|
+
}
|
|
1450
|
+
return { data: (created.data || {}) as Record<string, any> }
|
|
1451
|
+
}
|
|
1452
|
+
|
|
1453
|
+
await this.updatePayPalSettings({ id: row.id, data: next })
|
|
1454
|
+
return { data: next }
|
|
1455
|
+
}
|
|
1456
|
+
|
|
1457
|
+
async getActiveCredentials() {
|
|
1458
|
+
const row = await this.getCurrentRow()
|
|
1459
|
+
const env = await this.getCurrentEnvironment()
|
|
1460
|
+
|
|
1461
|
+
if (!row) {
|
|
1462
|
+
throw new Error("PayPal connection row not found. Please complete onboarding.")
|
|
1463
|
+
}
|
|
1464
|
+
|
|
1465
|
+
const c = this.getEnvCreds(row, env)
|
|
1466
|
+
const clientSecret = c.clientSecret || ""
|
|
1467
|
+
|
|
1468
|
+
if (!c.clientId || !clientSecret) {
|
|
1469
|
+
throw new Error(
|
|
1470
|
+
`PayPal credentials missing for environment "${env}". Please save credentials.`
|
|
1471
|
+
)
|
|
1472
|
+
}
|
|
1473
|
+
|
|
1474
|
+
return {
|
|
1475
|
+
environment: env,
|
|
1476
|
+
client_id: c.clientId,
|
|
1477
|
+
client_secret: clientSecret,
|
|
1478
|
+
}
|
|
1479
|
+
}
|
|
1480
|
+
|
|
1481
|
+
async getOrderDetails(orderId: string) {
|
|
1482
|
+
if (!orderId) {
|
|
1483
|
+
throw new Error("PayPal orderId is required")
|
|
1484
|
+
}
|
|
1485
|
+
|
|
1486
|
+
const env = await this.getCurrentEnvironment()
|
|
1487
|
+
const base = getPayPalApiBase(env)
|
|
1488
|
+
|
|
1489
|
+
const accessToken = await this.getAppAccessToken()
|
|
1490
|
+
|
|
1491
|
+
const resp = await paypalFetch(
|
|
1492
|
+
`${base}/v2/checkout/orders/${encodeURIComponent(orderId)}`,
|
|
1493
|
+
{
|
|
1494
|
+
method: "GET",
|
|
1495
|
+
headers: {
|
|
1496
|
+
Authorization: `Bearer ${accessToken}`,
|
|
1497
|
+
"Content-Type": "application/json",
|
|
1498
|
+
"PayPal-Partner-Attribution-Id": this.bnCode,
|
|
1499
|
+
},
|
|
1500
|
+
signal: AbortSignal.timeout(30_000),
|
|
1501
|
+
}
|
|
1502
|
+
)
|
|
1503
|
+
|
|
1504
|
+
const text = await resp.text()
|
|
1505
|
+
if (!resp.ok) {
|
|
1506
|
+
throw new Error(`PayPal get order error (${resp.status}): ${text}`)
|
|
1507
|
+
}
|
|
1508
|
+
|
|
1509
|
+
return JSON.parse(text)
|
|
1510
|
+
}
|
|
1511
|
+
|
|
1512
|
+
async createWebhookEventRecord(input: {
|
|
1513
|
+
event_id: string
|
|
1514
|
+
event_type: string
|
|
1515
|
+
resource_id?: string | null
|
|
1516
|
+
payload?: Record<string, unknown>
|
|
1517
|
+
event_version?: string | null
|
|
1518
|
+
transmission_id?: string | null
|
|
1519
|
+
transmission_time?: Date | null
|
|
1520
|
+
status?: string
|
|
1521
|
+
attempt_count?: number
|
|
1522
|
+
}) {
|
|
1523
|
+
try {
|
|
1524
|
+
const created = await this.createPayPalWebhookEvents({
|
|
1525
|
+
event_id: input.event_id,
|
|
1526
|
+
event_type: input.event_type,
|
|
1527
|
+
resource_id: input.resource_id ?? null,
|
|
1528
|
+
payload: input.payload ?? {},
|
|
1529
|
+
event_version: input.event_version ?? null,
|
|
1530
|
+
transmission_id: input.transmission_id ?? null,
|
|
1531
|
+
transmission_time: input.transmission_time ?? null,
|
|
1532
|
+
status: input.status ?? "pending",
|
|
1533
|
+
attempt_count: input.attempt_count ?? 0,
|
|
1534
|
+
next_retry_at: null,
|
|
1535
|
+
processed_at: null,
|
|
1536
|
+
last_error: null,
|
|
1537
|
+
})
|
|
1538
|
+
return { created: true, event: created }
|
|
1539
|
+
} catch (error: any) {
|
|
1540
|
+
const message = String(error?.message || "")
|
|
1541
|
+
const code = String(error?.code || "")
|
|
1542
|
+
if (
|
|
1543
|
+
message.includes("paypal_webhook_event_event_id_unique") ||
|
|
1544
|
+
code === "23505" ||
|
|
1545
|
+
(message.includes("unique") && message.includes("event_id"))
|
|
1546
|
+
) {
|
|
1547
|
+
const existing = await this.listPayPalWebhookEvents({ event_id: input.event_id })
|
|
1548
|
+
return { created: false, event: existing?.[0] ?? null }
|
|
1549
|
+
}
|
|
1550
|
+
throw error
|
|
1551
|
+
}
|
|
1552
|
+
}
|
|
1553
|
+
|
|
1554
|
+
async updateWebhookEventRecord(input: {
|
|
1555
|
+
id: string
|
|
1556
|
+
status?: string
|
|
1557
|
+
attempt_count?: number
|
|
1558
|
+
next_retry_at?: Date | null
|
|
1559
|
+
processed_at?: Date | null
|
|
1560
|
+
last_error?: string | null
|
|
1561
|
+
resource_id?: string | null
|
|
1562
|
+
}) {
|
|
1563
|
+
return await this.updatePayPalWebhookEvents({
|
|
1564
|
+
id: input.id,
|
|
1565
|
+
status: input.status,
|
|
1566
|
+
attempt_count: input.attempt_count,
|
|
1567
|
+
next_retry_at: input.next_retry_at ?? null,
|
|
1568
|
+
processed_at: input.processed_at ?? null,
|
|
1569
|
+
last_error: input.last_error ?? null,
|
|
1570
|
+
resource_id: input.resource_id ?? null,
|
|
1571
|
+
})
|
|
1572
|
+
}
|
|
1573
|
+
|
|
1574
|
+
/**
|
|
1575
|
+
* Emit an audit event as a single structured log line.
|
|
1576
|
+
*
|
|
1577
|
+
* The dedicated audit-log table was removed; for high-volume/containerized
|
|
1578
|
+
* deployments the audit trail lives in aggregated stdout logs. This records a
|
|
1579
|
+
* greppable `paypal_audit` line (filter on `"log":"paypal_audit"`) with
|
|
1580
|
+
* sensitive keys redacted. It never throws — audit logging must not break the
|
|
1581
|
+
* caller's payment flow.
|
|
1582
|
+
*/
|
|
1583
|
+
async recordAuditEvent(eventType: string, metadata?: Record<string, unknown>) {
|
|
1584
|
+
try {
|
|
1585
|
+
console.info(
|
|
1586
|
+
JSON.stringify({
|
|
1587
|
+
log: "paypal_audit",
|
|
1588
|
+
event_type: eventType,
|
|
1589
|
+
at: new Date().toISOString(),
|
|
1590
|
+
...(metadata ? { metadata: redactSensitive(metadata) } : {}),
|
|
1591
|
+
})
|
|
1592
|
+
)
|
|
1593
|
+
} catch {
|
|
1594
|
+
// never let audit logging interfere with the payment flow
|
|
1595
|
+
}
|
|
1596
|
+
return null
|
|
1597
|
+
}
|
|
1598
|
+
|
|
1599
|
+
async recordMetric(name: string, metadata?: Record<string, unknown>) {
|
|
1600
|
+
// Preferred path: single atomic INSERT ... ON CONFLICT (same statement the
|
|
1601
|
+
// credential resolver uses), so concurrent routes/webhooks never lose
|
|
1602
|
+
// increments to a read-modify-write race.
|
|
1603
|
+
if (this.pgForMetrics) {
|
|
1604
|
+
await recordMetricAtomic(this.pgForMetrics, name, metadata)
|
|
1605
|
+
return null
|
|
1606
|
+
}
|
|
1607
|
+
// Fallback (container without a raw pg connection): the previous ORM
|
|
1608
|
+
// read-modify-write. Best-effort only — never throws.
|
|
1609
|
+
try {
|
|
1610
|
+
const existing = await this.listPayPalMetrics({ name })
|
|
1611
|
+
const row = existing?.[0]
|
|
1612
|
+
const current = (row?.data || {}) as Record<string, any>
|
|
1613
|
+
const next = {
|
|
1614
|
+
...current,
|
|
1615
|
+
...(metadata || {}),
|
|
1616
|
+
count: Number(current.count || 0) + 1,
|
|
1617
|
+
last_recorded_at: new Date().toISOString(),
|
|
1618
|
+
}
|
|
1619
|
+
|
|
1620
|
+
if (!row) {
|
|
1621
|
+
try {
|
|
1622
|
+
return await this.createPayPalMetrics({ name, data: next })
|
|
1623
|
+
} catch {
|
|
1624
|
+
const retry = await this.listPayPalMetrics({ name })
|
|
1625
|
+
const retryRow = retry?.[0]
|
|
1626
|
+
if (retryRow) {
|
|
1627
|
+
const retryData = (retryRow.data || {}) as Record<string, any>
|
|
1628
|
+
return await this.updatePayPalMetrics({
|
|
1629
|
+
id: retryRow.id,
|
|
1630
|
+
name,
|
|
1631
|
+
data: {
|
|
1632
|
+
...retryData,
|
|
1633
|
+
...(metadata || {}),
|
|
1634
|
+
count: Number(retryData.count || 0) + 1,
|
|
1635
|
+
last_recorded_at: new Date().toISOString(),
|
|
1636
|
+
},
|
|
1637
|
+
})
|
|
1638
|
+
}
|
|
1639
|
+
throw new Error(`Failed to record metric "${name}"`)
|
|
1640
|
+
}
|
|
1641
|
+
}
|
|
1642
|
+
|
|
1643
|
+
return await this.updatePayPalMetrics({ id: row.id, name, data: next })
|
|
1644
|
+
} catch (e: unknown) {
|
|
1645
|
+
console.warn("[PayPal] recordMetric failed:", e instanceof Error ? e.message : e)
|
|
1646
|
+
return null
|
|
1647
|
+
}
|
|
1648
|
+
}
|
|
1649
|
+
|
|
1650
|
+
async recordPaymentLog(eventType: string, metadata?: Record<string, unknown>) {
|
|
1651
|
+
return await this.recordAuditEvent(`payment_${eventType}`, metadata)
|
|
1652
|
+
}
|
|
1653
|
+
|
|
1654
|
+
async sendAlert(input: {
|
|
1655
|
+
type: string
|
|
1656
|
+
message: string
|
|
1657
|
+
metadata?: Record<string, unknown>
|
|
1658
|
+
}) {
|
|
1659
|
+
const urls = this.getAlertWebhookUrls()
|
|
1660
|
+
if (urls.length === 0) {
|
|
1661
|
+
return
|
|
1662
|
+
}
|
|
1663
|
+
|
|
1664
|
+
const payload = {
|
|
1665
|
+
type: input.type,
|
|
1666
|
+
message: input.message,
|
|
1667
|
+
metadata: input.metadata ?? {},
|
|
1668
|
+
source: "paypal",
|
|
1669
|
+
timestamp: new Date().toISOString(),
|
|
1670
|
+
}
|
|
1671
|
+
|
|
1672
|
+
await Promise.all(
|
|
1673
|
+
urls.map(async (url) => {
|
|
1674
|
+
try {
|
|
1675
|
+
const resp = await paypalFetch(url, {
|
|
1676
|
+
method: "POST",
|
|
1677
|
+
headers: {
|
|
1678
|
+
"Content-Type": "application/json",
|
|
1679
|
+
},
|
|
1680
|
+
body: JSON.stringify(payload),
|
|
1681
|
+
})
|
|
1682
|
+
if (!resp.ok) {
|
|
1683
|
+
const text = await resp.text().catch(() => "")
|
|
1684
|
+
await this.recordAuditEvent("alert_failed", {
|
|
1685
|
+
url,
|
|
1686
|
+
status: resp.status,
|
|
1687
|
+
response: text,
|
|
1688
|
+
})
|
|
1689
|
+
} else {
|
|
1690
|
+
await this.recordAuditEvent("alert_sent", { url, type: input.type })
|
|
1691
|
+
}
|
|
1692
|
+
} catch (error: any) {
|
|
1693
|
+
await this.recordAuditEvent("alert_failed", {
|
|
1694
|
+
url,
|
|
1695
|
+
message: error?.message,
|
|
1696
|
+
})
|
|
1697
|
+
}
|
|
1698
|
+
})
|
|
1699
|
+
)
|
|
1700
|
+
}
|
|
1701
|
+
}
|
|
1702
|
+
|
|
1703
|
+
export default PayPalModuleService
|