@easypayment/medusa-payment-paypal 1.2.4 → 1.2.6

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.
Files changed (41) hide show
  1. package/.medusa/server/src/admin/index.js +10 -10
  2. package/.medusa/server/src/admin/index.mjs +10 -10
  3. package/.medusa/server/src/api/store/payment-collections/[id]/payment-sessions/route.d.ts.map +1 -1
  4. package/.medusa/server/src/api/store/payment-collections/[id]/payment-sessions/route.js +6 -1
  5. package/.medusa/server/src/api/store/payment-collections/[id]/payment-sessions/route.js.map +1 -1
  6. package/.medusa/server/src/api/store/paypal/create-order/route.d.ts.map +1 -1
  7. package/.medusa/server/src/api/store/paypal/create-order/route.js +26 -6
  8. package/.medusa/server/src/api/store/paypal/create-order/route.js.map +1 -1
  9. package/.medusa/server/src/api/store/paypal-complete/route.d.ts.map +1 -1
  10. package/.medusa/server/src/api/store/paypal-complete/route.js +22 -2
  11. package/.medusa/server/src/api/store/paypal-complete/route.js.map +1 -1
  12. package/.medusa/server/src/modules/paypal/payment-provider/base-provider.d.ts +24 -1
  13. package/.medusa/server/src/modules/paypal/payment-provider/base-provider.d.ts.map +1 -1
  14. package/.medusa/server/src/modules/paypal/payment-provider/base-provider.js +296 -0
  15. package/.medusa/server/src/modules/paypal/payment-provider/base-provider.js.map +1 -1
  16. package/.medusa/server/src/modules/paypal/payment-provider/card-service.d.ts +1 -2
  17. package/.medusa/server/src/modules/paypal/payment-provider/card-service.d.ts.map +1 -1
  18. package/.medusa/server/src/modules/paypal/payment-provider/card-service.js +3 -184
  19. package/.medusa/server/src/modules/paypal/payment-provider/card-service.js.map +1 -1
  20. package/.medusa/server/src/modules/paypal/payment-provider/service.d.ts +1 -2
  21. package/.medusa/server/src/modules/paypal/payment-provider/service.d.ts.map +1 -1
  22. package/.medusa/server/src/modules/paypal/payment-provider/service.js +3 -182
  23. package/.medusa/server/src/modules/paypal/payment-provider/service.js.map +1 -1
  24. package/.medusa/server/src/modules/paypal/payment-provider/status-utils.d.ts +21 -0
  25. package/.medusa/server/src/modules/paypal/payment-provider/status-utils.d.ts.map +1 -1
  26. package/.medusa/server/src/modules/paypal/payment-provider/status-utils.js +54 -0
  27. package/.medusa/server/src/modules/paypal/payment-provider/status-utils.js.map +1 -1
  28. package/.medusa/server/src/modules/paypal/utils/credential-resolver.d.ts +10 -0
  29. package/.medusa/server/src/modules/paypal/utils/credential-resolver.d.ts.map +1 -1
  30. package/.medusa/server/src/modules/paypal/utils/credential-resolver.js +42 -0
  31. package/.medusa/server/src/modules/paypal/utils/credential-resolver.js.map +1 -1
  32. package/CHANGELOG.md +60 -0
  33. package/package.json +1 -1
  34. package/src/api/store/payment-collections/[id]/payment-sessions/route.ts +7 -1
  35. package/src/api/store/paypal/create-order/route.ts +31 -6
  36. package/src/api/store/paypal-complete/route.ts +30 -3
  37. package/src/modules/paypal/payment-provider/base-provider.ts +417 -4
  38. package/src/modules/paypal/payment-provider/card-service.ts +4 -238
  39. package/src/modules/paypal/payment-provider/service.ts +4 -237
  40. package/src/modules/paypal/payment-provider/status-utils.ts +57 -0
  41. package/src/modules/paypal/utils/credential-resolver.ts +40 -0
@@ -1,6 +1,8 @@
1
- import { AbstractPaymentProvider } from "@medusajs/framework/utils"
1
+ import { AbstractPaymentProvider, MedusaError } from "@medusajs/framework/utils"
2
2
  import { randomUUID } from "crypto"
3
3
  import type {
4
+ CapturePaymentInput,
5
+ CapturePaymentOutput,
4
6
  CreateAccountHolderInput,
5
7
  CreateAccountHolderOutput,
6
8
  DeletePaymentInput,
@@ -8,16 +10,60 @@ import type {
8
10
  ProviderWebhookPayload,
9
11
  WebhookActionResult,
10
12
  } from "@medusajs/framework/types"
11
- import { formatAmountForPayPal, toAmountNumber } from "../utils/amounts"
13
+ import {
14
+ formatAmountForPayPal,
15
+ getCurrencyExponent,
16
+ toAmountNumber,
17
+ } from "../utils/amounts"
12
18
  import {
13
19
  assertPayPalCurrencySupported,
14
20
  normalizeCurrencyCode,
15
21
  } from "../utils/currencies"
16
22
  import { PayPalCredentialResolver } from "../utils/credential-resolver"
17
23
  import { PAYPAL_PARTNER_ATTRIBUTION_ID } from "../utils/partner"
18
- import { paypalFetch } from "../utils/paypal-fetch"
24
+ import { paypalFetch, paypalFetchWithRetry } from "../utils/paypal-fetch"
19
25
  import { getPayPalWebhookActionAndData } from "./webhook-utils"
20
- import { mapPayPalCaptureStatus } from "./status-utils"
26
+ import {
27
+ extractCaptureStatus,
28
+ isCaptureCompleted,
29
+ mapPayPalCaptureStatus,
30
+ sumCountedCaptureAmounts,
31
+ sumSettledCaptureAmounts,
32
+ } from "./status-utils"
33
+
34
+ /** Compact record of one PayPal capture kept on the session (`paypal.captures`). */
35
+ type StoredCaptureEntry = {
36
+ id?: string
37
+ status?: string
38
+ amount?: unknown
39
+ final_capture?: boolean
40
+ raw?: unknown
41
+ }
42
+
43
+ function toStoredCaptureEntry(capture: any): StoredCaptureEntry {
44
+ return {
45
+ id: capture?.id,
46
+ status: capture?.status,
47
+ amount: capture?.amount,
48
+ final_capture: capture?.final_capture,
49
+ raw: capture,
50
+ }
51
+ }
52
+
53
+ /** Merge capture entries by id — a later entry for the same id wins. */
54
+ function mergeCaptureEntries(
55
+ ...lists: (StoredCaptureEntry[] | undefined)[]
56
+ ): StoredCaptureEntry[] {
57
+ const byId = new Map<string, StoredCaptureEntry>()
58
+ const anonymous: StoredCaptureEntry[] = []
59
+ for (const list of lists) {
60
+ for (const entry of list || []) {
61
+ if (entry?.id) byId.set(String(entry.id), entry)
62
+ else if (entry) anonymous.push(entry)
63
+ }
64
+ }
65
+ return [...byId.values(), ...anonymous]
66
+ }
21
67
 
22
68
  export type Options = {}
23
69
 
@@ -257,6 +303,373 @@ export abstract class PayPalProviderBase extends AbstractPaymentProvider<Options
257
303
  return "pending"
258
304
  }
259
305
 
306
+ /**
307
+ * Capture funds for a session — one PayPal capture per Medusa capture row.
308
+ *
309
+ * Medusa calls this once per admin capture (full or partial) with the
310
+ * requested amount living on the Medusa capture row (see
311
+ * `resolveRequestedCaptureAmount`). The decision to call PayPal is driven by
312
+ * what PayPal already holds for the order, NOT by whether the session happens
313
+ * to carry a `capture_id`: after a first partial capture the session always
314
+ * has one, and short-circuiting on it silently skipped every later capture
315
+ * (Medusa recorded the money, PayPal never took it).
316
+ *
317
+ * - Order already fully captured at PayPal → idempotent success with the
318
+ * latest COMPLETED capture (a retry after a crash between the PayPal call
319
+ * and the session write, or a storefront capture-order that Medusa never
320
+ * saw). If everything it holds is still PENDING, fail — funds in flight
321
+ * are not settled money.
322
+ * - Otherwise capture exactly the requested amount; refuse (rather than
323
+ * silently clamp) if more than what remains capturable is requested, since
324
+ * Medusa records the requested amount regardless of what is returned.
325
+ * - The last capture that exhausts the session amount closes the
326
+ * authorization (`final_capture`), unless the session says otherwise.
327
+ */
328
+ async capturePayment(
329
+ input: CapturePaymentInput
330
+ ): Promise<CapturePaymentOutput> {
331
+ const data = (input.data || {}) as Record<string, any>
332
+ const paypalData = (data.paypal || {}) as Record<string, any>
333
+ const orderId = String(paypalData.order_id || data.order_id || "")
334
+ let authorizationId = String(
335
+ paypalData.authorization_id || data.authorization_id || ""
336
+ )
337
+ if (!orderId) {
338
+ throw new MedusaError(
339
+ MedusaError.Types.INVALID_DATA,
340
+ "PayPal order_id is required to capture payment"
341
+ )
342
+ }
343
+
344
+ const { amount: sessionAmount, currencyCode } =
345
+ await this.normalizePaymentData(input)
346
+ const exponent = getCurrencyExponent(currencyCode)
347
+ const roundMoney = (value: number) => Number(value.toFixed(exponent))
348
+ // The requested (possibly partial) capture amount lives on the Medusa
349
+ // capture row, not in the provider input — resolve it so partial captures
350
+ // don't charge the full session total.
351
+ const amount = await this.resolveRequestedCaptureAmount(
352
+ input,
353
+ sessionAmount
354
+ )
355
+ // Include the amount in the idempotency suffix: PayPal deduplicates by
356
+ // PayPal-Request-Id, so two sequential partial captures of the same order
357
+ // that share an upstream idempotency_key would otherwise collide and the
358
+ // second capture would silently return the first one's result.
359
+ const requestId = this.getIdempotencyKey(
360
+ input,
361
+ `capture-${orderId}-${amount}`
362
+ )
363
+ let debugId: string | null = null
364
+
365
+ const storedCaptures: StoredCaptureEntry[] = Array.isArray(
366
+ paypalData.captures
367
+ )
368
+ ? paypalData.captures
369
+ : []
370
+
371
+ const successResult = (
372
+ capture: any,
373
+ liveCaptures: any[],
374
+ newEntry?: StoredCaptureEntry
375
+ ): CapturePaymentOutput => {
376
+ const captureId =
377
+ capture?.id || capture?.purchase_units?.[0]?.payments?.captures?.[0]?.id
378
+ return {
379
+ data: {
380
+ ...(input.data || {}),
381
+ paypal: {
382
+ ...paypalData,
383
+ order_id: orderId,
384
+ capture_id: captureId,
385
+ capture,
386
+ authorization_id: authorizationId || paypalData.authorization_id,
387
+ captures: mergeCaptureEntries(
388
+ storedCaptures,
389
+ liveCaptures.map(toStoredCaptureEntry),
390
+ newEntry ? [newEntry] : undefined
391
+ ),
392
+ },
393
+ captured_at: new Date().toISOString(),
394
+ },
395
+ }
396
+ }
397
+
398
+ try {
399
+ const { accessToken, base } = await this.getPayPalAccessToken()
400
+ const order = await this.getOrderDetails(orderId).catch(() => null)
401
+ const liveCaptures: any[] =
402
+ order?.purchase_units?.[0]?.payments?.captures ?? []
403
+
404
+ if (order) {
405
+ // What PayPal has already taken (or reserved) for this order, and how
406
+ // much of it is settled.
407
+ const alreadyCaptured = roundMoney(
408
+ sumCountedCaptureAmounts(liveCaptures)
409
+ )
410
+ const settled = roundMoney(sumSettledCaptureAmounts(liveCaptures))
411
+ const remaining = roundMoney(sessionAmount - alreadyCaptured)
412
+ const requested = roundMoney(amount)
413
+
414
+ // Reconcile against Medusa's own ledger. Medusa creates the capture row
415
+ // BEFORE calling us and deletes it when the call (or its follow-up
416
+ // write) fails, so a retry arrives with a fresh row and a fresh
417
+ // PayPal-Request-Id. Whatever PayPal holds beyond the captures Medusa
418
+ // has booked on this payment is therefore a capture Medusa lost —
419
+ // that money IS this capture, and must not be taken from the buyer a
420
+ // second time. (Also covers a storefront capture-order the session
421
+ // never recorded.) Falls through to the amount-based checks below when
422
+ // the ledger can't be read.
423
+ const captureRowId = input?.context?.idempotency_key?.trim() || ""
424
+ const booked = captureRowId
425
+ ? await this.paypal.getBookedCaptureTotal(captureRowId)
426
+ : null
427
+ const unbookedHeld =
428
+ booked === null ? 0 : roundMoney(alreadyCaptured - booked)
429
+ const unbookedSettled =
430
+ booked === null ? 0 : roundMoney(settled - booked)
431
+
432
+ const pickCompletedCapture = () =>
433
+ [...liveCaptures]
434
+ .reverse()
435
+ .find(
436
+ (c) =>
437
+ isCaptureCompleted(c) &&
438
+ roundMoney(Number(c?.amount?.value)) === requested
439
+ ) ?? [...liveCaptures].reverse().find((c) => isCaptureCompleted(c))
440
+
441
+ if (booked !== null && unbookedHeld >= requested && requested > 0) {
442
+ const completed = pickCompletedCapture()
443
+ if (!completed || unbookedSettled < requested) {
444
+ // The unbooked money is still PENDING (eCheck / review): not
445
+ // settled, so it can't be booked yet — the CAPTURE.COMPLETED
446
+ // webhook settles it later.
447
+ throw new Error(
448
+ `PayPal already holds ${formatAmountForPayPal(unbookedHeld, currencyCode)} ${currencyCode} for order ${orderId} that Medusa has not booked, ` +
449
+ `but only ${formatAmountForPayPal(unbookedSettled, currencyCode)} of it has COMPLETED (statuses: ${
450
+ liveCaptures.map((c) => c?.status).join(", ") || "none"
451
+ }). The payment was not recorded as captured.`
452
+ )
453
+ }
454
+ console.info(
455
+ `[PayPal] capturePayment: order ${orderId} already holds ${unbookedHeld} ${currencyCode} not booked in Medusa (PayPal ${alreadyCaptured}, Medusa ${booked}); returning capture ${completed.id} instead of capturing again`
456
+ )
457
+ return successResult(completed, liveCaptures)
458
+ }
459
+
460
+ if (remaining <= 0) {
461
+ // Nothing left to capture at PayPal. Only settled money may be
462
+ // booked: a PENDING capture that fills the remainder is not
463
+ // captured yet.
464
+ const completed = pickCompletedCapture()
465
+ if (!completed || settled < roundMoney(sessionAmount)) {
466
+ throw new Error(
467
+ `PayPal already holds captures covering the full amount for order ${orderId}, ` +
468
+ `but only ${formatAmountForPayPal(settled, currencyCode)} ${currencyCode} has COMPLETED (statuses: ${
469
+ liveCaptures.map((c) => c?.status).join(", ") || "none"
470
+ }). The payment was not recorded as captured.`
471
+ )
472
+ }
473
+ console.info(
474
+ `[PayPal] capturePayment: order ${orderId} is already fully captured at PayPal (${alreadyCaptured} ${currencyCode}); returning capture ${completed.id}`
475
+ )
476
+ return successResult(completed, liveCaptures)
477
+ }
478
+
479
+ if (requested > remaining) {
480
+ throw new Error(
481
+ `PayPal can only capture ${formatAmountForPayPal(remaining, currencyCode)} ${currencyCode} more for order ${orderId} ` +
482
+ `(${formatAmountForPayPal(alreadyCaptured, currencyCode)} of ${formatAmountForPayPal(sessionAmount, currencyCode)} already captured); ` +
483
+ `${formatAmountForPayPal(amount, currencyCode)} was requested.`
484
+ )
485
+ }
486
+ } else {
487
+ // PayPal unreachable for the order lookup: the only safe short-circuit
488
+ // is a stored capture that demonstrably COMPLETED for the full session
489
+ // amount. Anything else proceeds to the capture call below, where the
490
+ // PayPal-Request-Id keeps a retry idempotent and PayPal itself rejects
491
+ // an over-capture.
492
+ const stored = paypalData.capture
493
+ const storedAmount = Number(
494
+ stored?.amount?.value ??
495
+ stored?.purchase_units?.[0]?.payments?.captures?.[0]?.amount?.value
496
+ )
497
+ if (
498
+ stored &&
499
+ isCaptureCompleted(stored) &&
500
+ Number.isFinite(storedAmount) &&
501
+ roundMoney(storedAmount) >= roundMoney(sessionAmount)
502
+ ) {
503
+ return successResult(stored, [])
504
+ }
505
+ }
506
+
507
+ const resolvedIntent = String(
508
+ order?.intent || paypalData.order?.intent || data.intent || ""
509
+ ).toUpperCase()
510
+
511
+ if (!authorizationId && resolvedIntent === "AUTHORIZE") {
512
+ const liveAuthorizationId =
513
+ order?.purchase_units?.[0]?.payments?.authorizations?.[0]?.id
514
+ if (liveAuthorizationId) {
515
+ authorizationId = String(liveAuthorizationId)
516
+ } else {
517
+ const authorizeResp = await paypalFetch(
518
+ `${base}/v2/checkout/orders/${encodeURIComponent(orderId)}/authorize`,
519
+ {
520
+ method: "POST",
521
+ headers: {
522
+ Authorization: `Bearer ${accessToken}`,
523
+ "Content-Type": "application/json",
524
+ "PayPal-Request-Id": `${requestId}-auth`,
525
+ "PayPal-Partner-Attribution-Id": PAYPAL_PARTNER_ATTRIBUTION_ID,
526
+ },
527
+ }
528
+ )
529
+ const authorizeText = await authorizeResp.text()
530
+ debugId = authorizeResp.headers.get("paypal-debug-id")
531
+ if (!authorizeResp.ok) {
532
+ throw new Error(
533
+ `PayPal authorize order error (${authorizeResp.status}): ${authorizeText}${
534
+ debugId ? ` debug_id=${debugId}` : ""
535
+ }`
536
+ )
537
+ }
538
+ const authorization = JSON.parse(authorizeText)
539
+ authorizationId =
540
+ authorization?.purchase_units?.[0]?.payments?.authorizations?.[0]
541
+ ?.id
542
+ }
543
+ }
544
+
545
+ const explicitFinalCapture =
546
+ paypalData.is_final_capture ??
547
+ data.is_final_capture ??
548
+ data.final_capture ??
549
+ undefined
550
+ const captureValue =
551
+ amount > 0 ? formatAmountForPayPal(amount, currencyCode) : null
552
+
553
+ // `amount` and `final_capture` are only honored on the authorizations
554
+ // capture endpoint. The orders capture endpoint always captures the FULL
555
+ // order and silently ignores an `amount` body — so a partial amount there
556
+ // would over-capture while we record the smaller requested value. Route
557
+ // partial captures through the authorization, and fail closed if a
558
+ // partial capture is attempted against a capture-intent order.
559
+ let capturePayload: Record<string, unknown>
560
+ let captureUrl: string
561
+ if (authorizationId) {
562
+ captureUrl = `${base}/v2/payments/authorizations/${encodeURIComponent(authorizationId)}/capture`
563
+ // Close the authorization once the session amount is exhausted, unless
564
+ // the session explicitly says otherwise.
565
+ const finalCapture =
566
+ typeof explicitFinalCapture === "boolean"
567
+ ? explicitFinalCapture
568
+ : order
569
+ ? roundMoney(sumCountedCaptureAmounts(liveCaptures) + amount) >=
570
+ roundMoney(sessionAmount)
571
+ : undefined
572
+ capturePayload = {
573
+ ...(captureValue
574
+ ? { amount: { currency_code: currencyCode, value: captureValue } }
575
+ : {}),
576
+ ...(typeof finalCapture === "boolean"
577
+ ? { final_capture: finalCapture }
578
+ : {}),
579
+ }
580
+ } else {
581
+ captureUrl = `${base}/v2/checkout/orders/${encodeURIComponent(orderId)}/capture`
582
+ capturePayload = {}
583
+ const orderTotal = order?.purchase_units?.[0]?.amount?.value
584
+ if (captureValue && orderTotal && captureValue !== String(orderTotal)) {
585
+ throw new Error(
586
+ `PayPal partial capture (${captureValue} ${currencyCode}) is not supported for ` +
587
+ `capture-intent orders (order total ${orderTotal}). Create the order with intent ` +
588
+ `AUTHORIZE to capture a partial amount.`
589
+ )
590
+ }
591
+ }
592
+
593
+ // Retry transient 5xx/429/timeout: the PayPal-Request-Id makes the
594
+ // capture idempotent, so a retry after a network blip re-uses the same
595
+ // capture instead of double-charging. `Prefer: return=representation`
596
+ // asks for the full capture resource (amount, final_capture, …) instead
597
+ // of the default id/status/links stub, so the session keeps a usable
598
+ // record of every capture.
599
+ const ppResp = await paypalFetchWithRetry(captureUrl, {
600
+ method: "POST",
601
+ headers: {
602
+ Authorization: `Bearer ${accessToken}`,
603
+ "Content-Type": "application/json",
604
+ Prefer: "return=representation",
605
+ "PayPal-Request-Id": requestId,
606
+ "PayPal-Partner-Attribution-Id": PAYPAL_PARTNER_ATTRIBUTION_ID,
607
+ },
608
+ body: JSON.stringify(capturePayload),
609
+ })
610
+
611
+ const ppText = await ppResp.text()
612
+ debugId = ppResp.headers.get("paypal-debug-id")
613
+ if (!ppResp.ok) {
614
+ throw new Error(
615
+ `PayPal capture error (${ppResp.status}): ${ppText}${
616
+ debugId ? ` debug_id=${debugId}` : ""
617
+ }`
618
+ )
619
+ }
620
+
621
+ const capture = JSON.parse(ppText)
622
+
623
+ // A 2xx response does NOT mean the funds were captured. PayPal returns 201
624
+ // for captures that are PENDING (pending review / eCheck), DECLINED, or
625
+ // FAILED. Recording any of these as "captured" books money that never
626
+ // settled, so only a COMPLETED capture is treated as success.
627
+ const captureStatus = extractCaptureStatus(capture)
628
+ if (captureStatus !== "COMPLETED") {
629
+ throw new Error(
630
+ `PayPal capture did not complete (status=${captureStatus || "UNKNOWN"}). ` +
631
+ `The payment was not captured.${debugId ? ` debug_id=${debugId}` : ""}`
632
+ )
633
+ }
634
+
635
+ const captureResource = authorizationId
636
+ ? capture
637
+ : (capture?.purchase_units?.[0]?.payments?.captures?.[0] ?? capture)
638
+ const captureId = captureResource?.id || capture?.id
639
+
640
+ await this.recordSuccess("capture_success")
641
+ await this.recordPaymentEvent("capture", {
642
+ order_id: orderId,
643
+ capture_id: captureId,
644
+ authorization_id: authorizationId || undefined,
645
+ amount,
646
+ currency_code: currencyCode,
647
+ request_id: requestId,
648
+ })
649
+
650
+ return successResult(capture, liveCaptures, {
651
+ ...toStoredCaptureEntry(captureResource),
652
+ id: captureId,
653
+ raw: capture,
654
+ })
655
+ } catch (error: any) {
656
+ await this.recordFailure("capture_failed", {
657
+ order_id: orderId,
658
+ request_id: requestId,
659
+ debug_id: debugId,
660
+ message: error?.message,
661
+ })
662
+ // Surface the real reason: Medusa masks non-MedusaErrors as a generic
663
+ // "unknown error" in production, hiding the PayPal failure.
664
+ throw error instanceof MedusaError
665
+ ? error
666
+ : new MedusaError(
667
+ MedusaError.Types.INVALID_DATA,
668
+ error?.message || "PayPal capture failed."
669
+ )
670
+ }
671
+ }
672
+
260
673
  async createAccountHolder(
261
674
  input: CreateAccountHolderInput
262
675
  ): Promise<CreateAccountHolderOutput> {