@easypayment/medusa-payment-paypal 1.2.4 → 1.2.5
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 +7 -7
- package/.medusa/server/src/admin/index.mjs +7 -7
- package/.medusa/server/src/api/store/payment-collections/[id]/payment-sessions/route.d.ts.map +1 -1
- package/.medusa/server/src/api/store/payment-collections/[id]/payment-sessions/route.js +6 -1
- package/.medusa/server/src/api/store/payment-collections/[id]/payment-sessions/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 +26 -6
- package/.medusa/server/src/api/store/paypal/create-order/route.js.map +1 -1
- package/.medusa/server/src/api/store/paypal-complete/route.d.ts.map +1 -1
- package/.medusa/server/src/api/store/paypal-complete/route.js +22 -2
- package/.medusa/server/src/api/store/paypal-complete/route.js.map +1 -1
- package/.medusa/server/src/modules/paypal/payment-provider/base-provider.d.ts +24 -1
- 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 +296 -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 +1 -2
- 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 +3 -184
- 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 +1 -2
- package/.medusa/server/src/modules/paypal/payment-provider/service.d.ts.map +1 -1
- package/.medusa/server/src/modules/paypal/payment-provider/service.js +3 -182
- package/.medusa/server/src/modules/paypal/payment-provider/service.js.map +1 -1
- package/.medusa/server/src/modules/paypal/payment-provider/status-utils.d.ts +21 -0
- package/.medusa/server/src/modules/paypal/payment-provider/status-utils.d.ts.map +1 -1
- package/.medusa/server/src/modules/paypal/payment-provider/status-utils.js +54 -0
- package/.medusa/server/src/modules/paypal/payment-provider/status-utils.js.map +1 -1
- package/.medusa/server/src/modules/paypal/utils/credential-resolver.d.ts +10 -0
- package/.medusa/server/src/modules/paypal/utils/credential-resolver.d.ts.map +1 -1
- package/.medusa/server/src/modules/paypal/utils/credential-resolver.js +42 -0
- package/.medusa/server/src/modules/paypal/utils/credential-resolver.js.map +1 -1
- package/CHANGELOG.md +54 -0
- package/package.json +1 -1
- package/src/api/store/payment-collections/[id]/payment-sessions/route.ts +7 -1
- package/src/api/store/paypal/create-order/route.ts +31 -6
- package/src/api/store/paypal-complete/route.ts +30 -3
- package/src/modules/paypal/payment-provider/base-provider.ts +417 -4
- package/src/modules/paypal/payment-provider/card-service.ts +4 -238
- package/src/modules/paypal/payment-provider/service.ts +4 -237
- package/src/modules/paypal/payment-provider/status-utils.ts +57 -0
- package/src/modules/paypal/utils/credential-resolver.ts +40 -0
|
@@ -2,8 +2,6 @@ import { MedusaError } from "@medusajs/framework/utils"
|
|
|
2
2
|
import type {
|
|
3
3
|
AuthorizePaymentInput,
|
|
4
4
|
AuthorizePaymentOutput,
|
|
5
|
-
CapturePaymentInput,
|
|
6
|
-
CapturePaymentOutput,
|
|
7
5
|
CancelPaymentInput,
|
|
8
6
|
CancelPaymentOutput,
|
|
9
7
|
GetPaymentStatusInput,
|
|
@@ -24,11 +22,7 @@ import {
|
|
|
24
22
|
} from "../utils/currencies"
|
|
25
23
|
import { PAYPAL_PARTNER_ATTRIBUTION_ID } from "../utils/partner"
|
|
26
24
|
import { paypalFetch, paypalFetchWithRetry } from "../utils/paypal-fetch"
|
|
27
|
-
import {
|
|
28
|
-
extractCaptureStatus,
|
|
29
|
-
isCaptureCompleted,
|
|
30
|
-
isRefundFailureStatus,
|
|
31
|
-
} from "./status-utils"
|
|
25
|
+
import { extractCaptureStatus, isRefundFailureStatus } from "./status-utils"
|
|
32
26
|
import { PayPalProviderBase } from "./base-provider"
|
|
33
27
|
|
|
34
28
|
/**
|
|
@@ -352,237 +346,6 @@ class PayPalAdvancedCardProvider extends PayPalProviderBase {
|
|
|
352
346
|
)
|
|
353
347
|
}
|
|
354
348
|
|
|
355
|
-
async capturePayment(
|
|
356
|
-
input: CapturePaymentInput
|
|
357
|
-
): Promise<CapturePaymentOutput> {
|
|
358
|
-
const data = (input.data || {}) as Record<string, any>
|
|
359
|
-
const paypalData = (data.paypal || {}) as Record<string, any>
|
|
360
|
-
const orderId = String(paypalData.order_id || data.order_id || "")
|
|
361
|
-
let authorizationId = String(
|
|
362
|
-
paypalData.authorization_id || data.authorization_id || ""
|
|
363
|
-
)
|
|
364
|
-
if (!orderId) {
|
|
365
|
-
throw new Error("PayPal order_id is required to capture payment")
|
|
366
|
-
}
|
|
367
|
-
|
|
368
|
-
if (paypalData.capture_id || paypalData.capture) {
|
|
369
|
-
return {
|
|
370
|
-
data: {
|
|
371
|
-
...(data || {}),
|
|
372
|
-
paypal: {
|
|
373
|
-
...paypalData,
|
|
374
|
-
capture_id: paypalData.capture_id,
|
|
375
|
-
capture: paypalData.capture,
|
|
376
|
-
},
|
|
377
|
-
captured_at: new Date().toISOString(),
|
|
378
|
-
},
|
|
379
|
-
}
|
|
380
|
-
}
|
|
381
|
-
|
|
382
|
-
const { amount: sessionAmount, currencyCode } =
|
|
383
|
-
await this.normalizePaymentData(input)
|
|
384
|
-
// The requested (possibly partial) capture amount lives on the Medusa
|
|
385
|
-
// capture row, not in the provider input — resolve it so partial captures
|
|
386
|
-
// don't charge the full session total.
|
|
387
|
-
const amount = await this.resolveRequestedCaptureAmount(
|
|
388
|
-
input,
|
|
389
|
-
sessionAmount
|
|
390
|
-
)
|
|
391
|
-
// Include the amount in the idempotency suffix: PayPal deduplicates by
|
|
392
|
-
// PayPal-Request-Id, so two sequential partial captures of the same order
|
|
393
|
-
// that share an upstream idempotency_key would otherwise collide and the
|
|
394
|
-
// second capture would silently return the first one's result.
|
|
395
|
-
const requestId = this.getIdempotencyKey(
|
|
396
|
-
input,
|
|
397
|
-
`capture-${orderId}-${amount}`
|
|
398
|
-
)
|
|
399
|
-
let debugId: string | null = null
|
|
400
|
-
|
|
401
|
-
try {
|
|
402
|
-
const { accessToken, base } = await this.getPayPalAccessToken()
|
|
403
|
-
const order = await this.getOrderDetails(orderId).catch(() => null)
|
|
404
|
-
const existingCapture =
|
|
405
|
-
order?.purchase_units?.[0]?.payments?.captures?.[0]
|
|
406
|
-
if (existingCapture?.id && isCaptureCompleted(existingCapture)) {
|
|
407
|
-
return {
|
|
408
|
-
data: {
|
|
409
|
-
...(data || {}),
|
|
410
|
-
paypal: {
|
|
411
|
-
...paypalData,
|
|
412
|
-
capture_id: existingCapture.id,
|
|
413
|
-
capture: existingCapture,
|
|
414
|
-
},
|
|
415
|
-
captured_at: new Date().toISOString(),
|
|
416
|
-
},
|
|
417
|
-
}
|
|
418
|
-
}
|
|
419
|
-
|
|
420
|
-
const resolvedIntent = String(
|
|
421
|
-
order?.intent || paypalData.order?.intent || data.intent || ""
|
|
422
|
-
).toUpperCase()
|
|
423
|
-
if (!authorizationId && resolvedIntent === "AUTHORIZE") {
|
|
424
|
-
const authorizeResp = await paypalFetch(
|
|
425
|
-
`${base}/v2/checkout/orders/${encodeURIComponent(orderId)}/authorize`,
|
|
426
|
-
{
|
|
427
|
-
method: "POST",
|
|
428
|
-
headers: {
|
|
429
|
-
Authorization: `Bearer ${accessToken}`,
|
|
430
|
-
"Content-Type": "application/json",
|
|
431
|
-
"PayPal-Request-Id": `${requestId}-auth`,
|
|
432
|
-
"PayPal-Partner-Attribution-Id": PAYPAL_PARTNER_ATTRIBUTION_ID,
|
|
433
|
-
},
|
|
434
|
-
}
|
|
435
|
-
)
|
|
436
|
-
const authorizeText = await authorizeResp.text()
|
|
437
|
-
debugId = authorizeResp.headers.get("paypal-debug-id")
|
|
438
|
-
if (!authorizeResp.ok) {
|
|
439
|
-
throw new Error(
|
|
440
|
-
`PayPal authorize order error (${authorizeResp.status}): ${authorizeText}${
|
|
441
|
-
debugId ? ` debug_id=${debugId}` : ""
|
|
442
|
-
}`
|
|
443
|
-
)
|
|
444
|
-
}
|
|
445
|
-
const authorization = JSON.parse(authorizeText)
|
|
446
|
-
authorizationId =
|
|
447
|
-
authorization?.purchase_units?.[0]?.payments?.authorizations?.[0]?.id
|
|
448
|
-
}
|
|
449
|
-
|
|
450
|
-
const isFinalCapture =
|
|
451
|
-
paypalData.is_final_capture ??
|
|
452
|
-
data.is_final_capture ??
|
|
453
|
-
data.final_capture ??
|
|
454
|
-
undefined
|
|
455
|
-
const captureValue =
|
|
456
|
-
amount > 0 ? formatAmountForPayPal(amount, currencyCode || "EUR") : null
|
|
457
|
-
|
|
458
|
-
// `amount` and `is_final_capture` are only honored on the authorizations
|
|
459
|
-
// capture endpoint. The orders capture endpoint always captures the FULL
|
|
460
|
-
// order and silently ignores an `amount` body — so a partial amount there
|
|
461
|
-
// would over-capture while we record the smaller requested value. Route
|
|
462
|
-
// partial captures through the authorization, and fail closed if a partial
|
|
463
|
-
// capture is attempted against a capture-intent order.
|
|
464
|
-
let capturePayload: Record<string, unknown>
|
|
465
|
-
let captureUrl: string
|
|
466
|
-
if (authorizationId) {
|
|
467
|
-
captureUrl = `${base}/v2/payments/authorizations/${encodeURIComponent(authorizationId)}/capture`
|
|
468
|
-
capturePayload = {
|
|
469
|
-
...(captureValue
|
|
470
|
-
? {
|
|
471
|
-
amount: {
|
|
472
|
-
currency_code: currencyCode || "EUR",
|
|
473
|
-
value: captureValue,
|
|
474
|
-
},
|
|
475
|
-
}
|
|
476
|
-
: {}),
|
|
477
|
-
...(typeof isFinalCapture === "boolean"
|
|
478
|
-
? { is_final_capture: isFinalCapture }
|
|
479
|
-
: {}),
|
|
480
|
-
}
|
|
481
|
-
} else {
|
|
482
|
-
captureUrl = `${base}/v2/checkout/orders/${encodeURIComponent(orderId)}/capture`
|
|
483
|
-
capturePayload = {}
|
|
484
|
-
const orderTotal = order?.purchase_units?.[0]?.amount?.value
|
|
485
|
-
if (captureValue && orderTotal && captureValue !== String(orderTotal)) {
|
|
486
|
-
throw new Error(
|
|
487
|
-
`PayPal partial capture (${captureValue} ${currencyCode || "EUR"}) is not supported for ` +
|
|
488
|
-
`capture-intent orders (order total ${orderTotal}). Create the order with intent ` +
|
|
489
|
-
`AUTHORIZE to capture a partial amount.`
|
|
490
|
-
)
|
|
491
|
-
}
|
|
492
|
-
}
|
|
493
|
-
|
|
494
|
-
// Retry transient 5xx/429/timeout: the PayPal-Request-Id makes the capture
|
|
495
|
-
// idempotent, so a retry after a network blip re-uses the same capture
|
|
496
|
-
// instead of double-charging.
|
|
497
|
-
const ppResp = await paypalFetchWithRetry(captureUrl, {
|
|
498
|
-
method: "POST",
|
|
499
|
-
headers: {
|
|
500
|
-
Authorization: `Bearer ${accessToken}`,
|
|
501
|
-
"Content-Type": "application/json",
|
|
502
|
-
"PayPal-Request-Id": requestId,
|
|
503
|
-
"PayPal-Partner-Attribution-Id": PAYPAL_PARTNER_ATTRIBUTION_ID,
|
|
504
|
-
},
|
|
505
|
-
body: JSON.stringify(capturePayload),
|
|
506
|
-
})
|
|
507
|
-
|
|
508
|
-
const ppText = await ppResp.text()
|
|
509
|
-
debugId = ppResp.headers.get("paypal-debug-id")
|
|
510
|
-
if (!ppResp.ok) {
|
|
511
|
-
throw new Error(
|
|
512
|
-
`PayPal capture error (${ppResp.status}): ${ppText}${
|
|
513
|
-
debugId ? ` debug_id=${debugId}` : ""
|
|
514
|
-
}`
|
|
515
|
-
)
|
|
516
|
-
}
|
|
517
|
-
|
|
518
|
-
const capture = JSON.parse(ppText)
|
|
519
|
-
|
|
520
|
-
// A 2xx response does NOT mean the funds were captured. PayPal returns 201
|
|
521
|
-
// for captures that are PENDING (pending review / eCheck), DECLINED, or
|
|
522
|
-
// FAILED. Recording any of these as "captured" books money that never
|
|
523
|
-
// settled, so only a COMPLETED capture is treated as success.
|
|
524
|
-
const captureStatus = extractCaptureStatus(capture)
|
|
525
|
-
if (captureStatus !== "COMPLETED") {
|
|
526
|
-
throw new Error(
|
|
527
|
-
`PayPal capture did not complete (status=${captureStatus || "UNKNOWN"}). ` +
|
|
528
|
-
`The payment was not captured.${debugId ? ` debug_id=${debugId}` : ""}`
|
|
529
|
-
)
|
|
530
|
-
}
|
|
531
|
-
|
|
532
|
-
const captureId =
|
|
533
|
-
capture?.id || capture?.purchase_units?.[0]?.payments?.captures?.[0]?.id
|
|
534
|
-
const existingCaptures = Array.isArray(paypalData.captures)
|
|
535
|
-
? paypalData.captures
|
|
536
|
-
: []
|
|
537
|
-
const captureEntry = {
|
|
538
|
-
id: captureId,
|
|
539
|
-
status: capture?.status,
|
|
540
|
-
amount: capture?.amount,
|
|
541
|
-
raw: capture,
|
|
542
|
-
}
|
|
543
|
-
|
|
544
|
-
await this.recordSuccess("capture_success")
|
|
545
|
-
await this.recordPaymentEvent("capture", {
|
|
546
|
-
order_id: orderId,
|
|
547
|
-
capture_id: captureId,
|
|
548
|
-
authorization_id: authorizationId || undefined,
|
|
549
|
-
amount,
|
|
550
|
-
currency_code: currencyCode,
|
|
551
|
-
request_id: requestId,
|
|
552
|
-
})
|
|
553
|
-
|
|
554
|
-
return {
|
|
555
|
-
data: {
|
|
556
|
-
...(data || {}),
|
|
557
|
-
paypal: {
|
|
558
|
-
...paypalData,
|
|
559
|
-
order_id: orderId,
|
|
560
|
-
capture_id: captureId,
|
|
561
|
-
capture,
|
|
562
|
-
authorization_id: authorizationId || paypalData.authorization_id,
|
|
563
|
-
captures: [...existingCaptures, captureEntry],
|
|
564
|
-
},
|
|
565
|
-
captured_at: new Date().toISOString(),
|
|
566
|
-
},
|
|
567
|
-
}
|
|
568
|
-
} catch (error: any) {
|
|
569
|
-
await this.recordFailure("capture_failed", {
|
|
570
|
-
order_id: orderId,
|
|
571
|
-
request_id: requestId,
|
|
572
|
-
debug_id: debugId,
|
|
573
|
-
message: error?.message,
|
|
574
|
-
})
|
|
575
|
-
// Surface the real reason: Medusa masks non-MedusaErrors as a generic
|
|
576
|
-
// "unknown error" in production, hiding the PayPal failure.
|
|
577
|
-
throw error instanceof MedusaError
|
|
578
|
-
? error
|
|
579
|
-
: new MedusaError(
|
|
580
|
-
MedusaError.Types.INVALID_DATA,
|
|
581
|
-
error?.message || "PayPal capture failed."
|
|
582
|
-
)
|
|
583
|
-
}
|
|
584
|
-
}
|
|
585
|
-
|
|
586
349
|
async cancelPayment(input: CancelPaymentInput): Promise<CancelPaymentOutput> {
|
|
587
350
|
const data = (input.data || {}) as Record<string, any>
|
|
588
351
|
const paypalData = (data.paypal || {}) as Record<string, any>
|
|
@@ -777,6 +540,9 @@ class PayPalAdvancedCardProvider extends PayPalProviderBase {
|
|
|
777
540
|
headers: {
|
|
778
541
|
Authorization: `Bearer ${accessToken}`,
|
|
779
542
|
"Content-Type": "application/json",
|
|
543
|
+
// Full refund resource (amount, status, …) instead of the
|
|
544
|
+
// id/status/links stub, so the stored refund entry is usable.
|
|
545
|
+
Prefer: "return=representation",
|
|
780
546
|
"PayPal-Request-Id": requestId,
|
|
781
547
|
"PayPal-Partner-Attribution-Id": PAYPAL_PARTNER_ATTRIBUTION_ID,
|
|
782
548
|
},
|
|
@@ -2,8 +2,6 @@ import { MedusaError } from "@medusajs/framework/utils"
|
|
|
2
2
|
import type {
|
|
3
3
|
AuthorizePaymentInput,
|
|
4
4
|
AuthorizePaymentOutput,
|
|
5
|
-
CapturePaymentInput,
|
|
6
|
-
CapturePaymentOutput,
|
|
7
5
|
CancelPaymentInput,
|
|
8
6
|
CancelPaymentOutput,
|
|
9
7
|
GetPaymentStatusInput,
|
|
@@ -24,11 +22,7 @@ import {
|
|
|
24
22
|
} from "../utils/currencies"
|
|
25
23
|
import { PAYPAL_PARTNER_ATTRIBUTION_ID } from "../utils/partner"
|
|
26
24
|
import { paypalFetch, paypalFetchWithRetry } from "../utils/paypal-fetch"
|
|
27
|
-
import {
|
|
28
|
-
extractCaptureStatus,
|
|
29
|
-
isCaptureCompleted,
|
|
30
|
-
isRefundFailureStatus,
|
|
31
|
-
} from "./status-utils"
|
|
25
|
+
import { extractCaptureStatus, isRefundFailureStatus } from "./status-utils"
|
|
32
26
|
import { PayPalProviderBase } from "./base-provider"
|
|
33
27
|
|
|
34
28
|
/**
|
|
@@ -367,236 +361,6 @@ class PayPalPaymentProvider extends PayPalProviderBase {
|
|
|
367
361
|
}
|
|
368
362
|
}
|
|
369
363
|
|
|
370
|
-
async capturePayment(
|
|
371
|
-
input: CapturePaymentInput
|
|
372
|
-
): Promise<CapturePaymentOutput> {
|
|
373
|
-
const data = (input.data || {}) as Record<string, any>
|
|
374
|
-
const paypalData = (data.paypal || {}) as Record<string, any>
|
|
375
|
-
const orderId = String(paypalData.order_id || data.order_id || "")
|
|
376
|
-
let authorizationId = String(
|
|
377
|
-
paypalData.authorization_id || data.authorization_id || ""
|
|
378
|
-
)
|
|
379
|
-
if (!orderId) {
|
|
380
|
-
throw new Error("PayPal order_id is required to capture payment")
|
|
381
|
-
}
|
|
382
|
-
|
|
383
|
-
if (paypalData.capture_id || paypalData.capture) {
|
|
384
|
-
return {
|
|
385
|
-
data: {
|
|
386
|
-
...(input.data || {}),
|
|
387
|
-
paypal: {
|
|
388
|
-
...((input.data || {}).paypal as Record<string, unknown>),
|
|
389
|
-
capture_id: paypalData.capture_id,
|
|
390
|
-
capture: paypalData.capture,
|
|
391
|
-
},
|
|
392
|
-
captured_at: new Date().toISOString(),
|
|
393
|
-
},
|
|
394
|
-
}
|
|
395
|
-
}
|
|
396
|
-
|
|
397
|
-
const { amount: sessionAmount, currencyCode } =
|
|
398
|
-
await this.normalizePaymentData(input)
|
|
399
|
-
// The requested (possibly partial) capture amount lives on the Medusa
|
|
400
|
-
// capture row, not in the provider input — resolve it so partial captures
|
|
401
|
-
// don't charge the full session total.
|
|
402
|
-
const amount = await this.resolveRequestedCaptureAmount(
|
|
403
|
-
input,
|
|
404
|
-
sessionAmount
|
|
405
|
-
)
|
|
406
|
-
// Include the amount in the idempotency suffix: PayPal deduplicates by
|
|
407
|
-
// PayPal-Request-Id, so two sequential partial captures of the same order
|
|
408
|
-
// that share an upstream idempotency_key would otherwise collide and the
|
|
409
|
-
// second capture would silently return the first one's result.
|
|
410
|
-
const requestId = this.getIdempotencyKey(
|
|
411
|
-
input,
|
|
412
|
-
`capture-${orderId}-${amount}`
|
|
413
|
-
)
|
|
414
|
-
let debugId: string | null = null
|
|
415
|
-
|
|
416
|
-
try {
|
|
417
|
-
const { accessToken, base } = await this.getPayPalAccessToken()
|
|
418
|
-
const order = await this.getOrderDetails(orderId).catch(() => null)
|
|
419
|
-
const existingCapture =
|
|
420
|
-
order?.purchase_units?.[0]?.payments?.captures?.[0]
|
|
421
|
-
if (existingCapture?.id && isCaptureCompleted(existingCapture)) {
|
|
422
|
-
return {
|
|
423
|
-
data: {
|
|
424
|
-
...(input.data || {}),
|
|
425
|
-
paypal: {
|
|
426
|
-
...((input.data || {}).paypal as Record<string, unknown>),
|
|
427
|
-
capture_id: existingCapture.id,
|
|
428
|
-
capture: existingCapture,
|
|
429
|
-
},
|
|
430
|
-
captured_at: new Date().toISOString(),
|
|
431
|
-
},
|
|
432
|
-
}
|
|
433
|
-
}
|
|
434
|
-
|
|
435
|
-
const resolvedIntent = String(
|
|
436
|
-
order?.intent || paypalData.order?.intent || data.intent || ""
|
|
437
|
-
).toUpperCase()
|
|
438
|
-
|
|
439
|
-
if (!authorizationId && resolvedIntent === "AUTHORIZE") {
|
|
440
|
-
const authorizeResp = await paypalFetch(
|
|
441
|
-
`${base}/v2/checkout/orders/${encodeURIComponent(orderId)}/authorize`,
|
|
442
|
-
{
|
|
443
|
-
method: "POST",
|
|
444
|
-
headers: {
|
|
445
|
-
Authorization: `Bearer ${accessToken}`,
|
|
446
|
-
"Content-Type": "application/json",
|
|
447
|
-
"PayPal-Request-Id": `${requestId}-auth`,
|
|
448
|
-
"PayPal-Partner-Attribution-Id": PAYPAL_PARTNER_ATTRIBUTION_ID,
|
|
449
|
-
},
|
|
450
|
-
}
|
|
451
|
-
)
|
|
452
|
-
const authorizeText = await authorizeResp.text()
|
|
453
|
-
debugId = authorizeResp.headers.get("paypal-debug-id")
|
|
454
|
-
if (!authorizeResp.ok) {
|
|
455
|
-
throw new Error(
|
|
456
|
-
`PayPal authorize order error (${authorizeResp.status}): ${authorizeText}${
|
|
457
|
-
debugId ? ` debug_id=${debugId}` : ""
|
|
458
|
-
}`
|
|
459
|
-
)
|
|
460
|
-
}
|
|
461
|
-
const authorization = JSON.parse(authorizeText)
|
|
462
|
-
authorizationId =
|
|
463
|
-
authorization?.purchase_units?.[0]?.payments?.authorizations?.[0]?.id
|
|
464
|
-
}
|
|
465
|
-
|
|
466
|
-
const isFinalCapture =
|
|
467
|
-
paypalData.is_final_capture ??
|
|
468
|
-
data.is_final_capture ??
|
|
469
|
-
data.final_capture ??
|
|
470
|
-
undefined
|
|
471
|
-
const captureValue =
|
|
472
|
-
amount > 0 ? formatAmountForPayPal(amount, currencyCode || "EUR") : null
|
|
473
|
-
|
|
474
|
-
// `amount` and `is_final_capture` are only valid on the authorizations
|
|
475
|
-
// capture endpoint. The orders capture endpoint always captures the FULL
|
|
476
|
-
// order and silently ignores an `amount` body — so sending a partial
|
|
477
|
-
// amount there would over-capture while we record the (smaller) requested
|
|
478
|
-
// value. Route partial captures to the authorization, and fail closed if a
|
|
479
|
-
// partial capture is attempted against a capture-intent order.
|
|
480
|
-
let capturePayload: Record<string, unknown>
|
|
481
|
-
let captureUrl: string
|
|
482
|
-
if (authorizationId) {
|
|
483
|
-
captureUrl = `${base}/v2/payments/authorizations/${encodeURIComponent(authorizationId)}/capture`
|
|
484
|
-
capturePayload = {
|
|
485
|
-
...(captureValue
|
|
486
|
-
? {
|
|
487
|
-
amount: {
|
|
488
|
-
currency_code: currencyCode || "EUR",
|
|
489
|
-
value: captureValue,
|
|
490
|
-
},
|
|
491
|
-
}
|
|
492
|
-
: {}),
|
|
493
|
-
...(typeof isFinalCapture === "boolean"
|
|
494
|
-
? { is_final_capture: isFinalCapture }
|
|
495
|
-
: {}),
|
|
496
|
-
}
|
|
497
|
-
} else {
|
|
498
|
-
captureUrl = `${base}/v2/checkout/orders/${encodeURIComponent(orderId)}/capture`
|
|
499
|
-
capturePayload = {}
|
|
500
|
-
const orderTotal = order?.purchase_units?.[0]?.amount?.value
|
|
501
|
-
if (captureValue && orderTotal && captureValue !== String(orderTotal)) {
|
|
502
|
-
throw new Error(
|
|
503
|
-
`PayPal partial capture (${captureValue} ${currencyCode || "EUR"}) is not supported for ` +
|
|
504
|
-
`capture-intent orders (order total ${orderTotal}). Create the order with intent ` +
|
|
505
|
-
`AUTHORIZE to capture a partial amount.`
|
|
506
|
-
)
|
|
507
|
-
}
|
|
508
|
-
}
|
|
509
|
-
|
|
510
|
-
// Retry transient 5xx/429/timeout: the PayPal-Request-Id makes the
|
|
511
|
-
// capture idempotent, so a retry after a network blip re-uses the same
|
|
512
|
-
// capture instead of double-charging.
|
|
513
|
-
const ppResp = await paypalFetchWithRetry(captureUrl, {
|
|
514
|
-
method: "POST",
|
|
515
|
-
headers: {
|
|
516
|
-
Authorization: `Bearer ${accessToken}`,
|
|
517
|
-
"Content-Type": "application/json",
|
|
518
|
-
"PayPal-Request-Id": requestId,
|
|
519
|
-
"PayPal-Partner-Attribution-Id": PAYPAL_PARTNER_ATTRIBUTION_ID,
|
|
520
|
-
},
|
|
521
|
-
body: JSON.stringify(capturePayload),
|
|
522
|
-
})
|
|
523
|
-
|
|
524
|
-
const ppText = await ppResp.text()
|
|
525
|
-
debugId = ppResp.headers.get("paypal-debug-id")
|
|
526
|
-
if (!ppResp.ok) {
|
|
527
|
-
throw new Error(
|
|
528
|
-
`PayPal capture error (${ppResp.status}): ${ppText}${
|
|
529
|
-
debugId ? ` debug_id=${debugId}` : ""
|
|
530
|
-
}`
|
|
531
|
-
)
|
|
532
|
-
}
|
|
533
|
-
|
|
534
|
-
const capture = JSON.parse(ppText)
|
|
535
|
-
|
|
536
|
-
// A 2xx response does NOT mean the funds were captured. PayPal returns 201
|
|
537
|
-
// for captures that are PENDING (e.g. pending review / eCheck), DECLINED,
|
|
538
|
-
// or FAILED. Recording any of these as "captured" books money that never
|
|
539
|
-
// settled, so only a COMPLETED capture is treated as success.
|
|
540
|
-
const captureStatus = extractCaptureStatus(capture)
|
|
541
|
-
if (captureStatus !== "COMPLETED") {
|
|
542
|
-
throw new Error(
|
|
543
|
-
`PayPal capture did not complete (status=${captureStatus || "UNKNOWN"}). ` +
|
|
544
|
-
`The payment was not captured.${debugId ? ` debug_id=${debugId}` : ""}`
|
|
545
|
-
)
|
|
546
|
-
}
|
|
547
|
-
|
|
548
|
-
const captureId =
|
|
549
|
-
capture?.id || capture?.purchase_units?.[0]?.payments?.captures?.[0]?.id
|
|
550
|
-
const existingCaptures = Array.isArray(paypalData.captures)
|
|
551
|
-
? paypalData.captures
|
|
552
|
-
: []
|
|
553
|
-
const captureEntry = {
|
|
554
|
-
id: captureId,
|
|
555
|
-
status: capture?.status,
|
|
556
|
-
amount: capture?.amount,
|
|
557
|
-
raw: capture,
|
|
558
|
-
}
|
|
559
|
-
|
|
560
|
-
await this.recordSuccess("capture_success")
|
|
561
|
-
await this.recordPaymentEvent("capture", {
|
|
562
|
-
order_id: orderId,
|
|
563
|
-
capture_id: captureId,
|
|
564
|
-
authorization_id: authorizationId || undefined,
|
|
565
|
-
amount,
|
|
566
|
-
currency_code: currencyCode,
|
|
567
|
-
request_id: requestId,
|
|
568
|
-
})
|
|
569
|
-
|
|
570
|
-
return {
|
|
571
|
-
data: {
|
|
572
|
-
...(input.data || {}),
|
|
573
|
-
paypal: {
|
|
574
|
-
...((input.data || {}).paypal as Record<string, unknown>),
|
|
575
|
-
order_id: orderId,
|
|
576
|
-
capture_id: captureId,
|
|
577
|
-
capture,
|
|
578
|
-
authorization_id: authorizationId || paypalData.authorization_id,
|
|
579
|
-
captures: [...existingCaptures, captureEntry],
|
|
580
|
-
},
|
|
581
|
-
captured_at: new Date().toISOString(),
|
|
582
|
-
},
|
|
583
|
-
}
|
|
584
|
-
} catch (error: any) {
|
|
585
|
-
await this.recordFailure("capture_failed", {
|
|
586
|
-
order_id: orderId,
|
|
587
|
-
request_id: requestId,
|
|
588
|
-
debug_id: debugId,
|
|
589
|
-
message: error?.message,
|
|
590
|
-
})
|
|
591
|
-
throw error instanceof MedusaError
|
|
592
|
-
? error
|
|
593
|
-
: new MedusaError(
|
|
594
|
-
MedusaError.Types.INVALID_DATA,
|
|
595
|
-
error?.message || "PayPal capture failed."
|
|
596
|
-
)
|
|
597
|
-
}
|
|
598
|
-
}
|
|
599
|
-
|
|
600
364
|
async refundPayment(input: RefundPaymentInput): Promise<RefundPaymentOutput> {
|
|
601
365
|
const data = (input.data || {}) as Record<string, any>
|
|
602
366
|
const paypalData = (data.paypal || {}) as Record<string, any>
|
|
@@ -668,6 +432,9 @@ class PayPalPaymentProvider extends PayPalProviderBase {
|
|
|
668
432
|
headers: {
|
|
669
433
|
Authorization: `Bearer ${accessToken}`,
|
|
670
434
|
"Content-Type": "application/json",
|
|
435
|
+
// Full refund resource (amount, status, …) instead of the
|
|
436
|
+
// id/status/links stub, so the stored refund entry is usable.
|
|
437
|
+
Prefer: "return=representation",
|
|
671
438
|
"PayPal-Request-Id": requestId,
|
|
672
439
|
"PayPal-Partner-Attribution-Id": PAYPAL_PARTNER_ATTRIBUTION_ID,
|
|
673
440
|
},
|
|
@@ -57,3 +57,60 @@ export function isRefundFailureStatus(status?: string): boolean {
|
|
|
57
57
|
String(status || "").toUpperCase()
|
|
58
58
|
)
|
|
59
59
|
}
|
|
60
|
+
|
|
61
|
+
/**
|
|
62
|
+
* Capture statuses that count toward the funds PayPal has already taken (or
|
|
63
|
+
* reserved) for an order. PENDING is included: a pending capture still holds
|
|
64
|
+
* the amount against the authorization, so a further capture must not exceed
|
|
65
|
+
* what is left. Refunded captures still count — a refund returns money to the
|
|
66
|
+
* buyer, it does not free the authorization for re-capture. DECLINED / FAILED
|
|
67
|
+
* captures took nothing.
|
|
68
|
+
*/
|
|
69
|
+
export const HELD_CAPTURE_STATUSES = [
|
|
70
|
+
"COMPLETED",
|
|
71
|
+
"PENDING",
|
|
72
|
+
"PARTIALLY_REFUNDED",
|
|
73
|
+
"REFUNDED",
|
|
74
|
+
] as const
|
|
75
|
+
|
|
76
|
+
/** Capture statuses whose funds actually settled (PENDING excluded). */
|
|
77
|
+
export const SETTLED_CAPTURE_STATUSES = [
|
|
78
|
+
"COMPLETED",
|
|
79
|
+
"PARTIALLY_REFUNDED",
|
|
80
|
+
"REFUNDED",
|
|
81
|
+
] as const
|
|
82
|
+
|
|
83
|
+
export function isCountedCaptureStatus(status?: string): boolean {
|
|
84
|
+
return (HELD_CAPTURE_STATUSES as readonly string[]).includes(
|
|
85
|
+
String(status || "").toUpperCase()
|
|
86
|
+
)
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
/**
|
|
90
|
+
* Sum of `amount.value` over the captures whose status is in `statuses`.
|
|
91
|
+
* Captures without a readable amount are ignored.
|
|
92
|
+
*/
|
|
93
|
+
export function sumCaptureAmounts(
|
|
94
|
+
captures: unknown,
|
|
95
|
+
statuses: readonly string[]
|
|
96
|
+
): number {
|
|
97
|
+
if (!Array.isArray(captures)) return 0
|
|
98
|
+
let total = 0
|
|
99
|
+
for (const capture of captures) {
|
|
100
|
+
const c = capture as { status?: string; amount?: { value?: unknown } }
|
|
101
|
+
if (!statuses.includes(String(c?.status || "").toUpperCase())) continue
|
|
102
|
+
const value = Number(c?.amount?.value)
|
|
103
|
+
if (Number.isFinite(value) && value > 0) total += value
|
|
104
|
+
}
|
|
105
|
+
return total
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
/** Funds PayPal holds for the order — settled plus still-pending captures. */
|
|
109
|
+
export function sumCountedCaptureAmounts(captures: unknown): number {
|
|
110
|
+
return sumCaptureAmounts(captures, HELD_CAPTURE_STATUSES)
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
/** Funds that demonstrably settled (COMPLETED, possibly refunded since). */
|
|
114
|
+
export function sumSettledCaptureAmounts(captures: unknown): number {
|
|
115
|
+
return sumCaptureAmounts(captures, SETTLED_CAPTURE_STATUSES)
|
|
116
|
+
}
|
|
@@ -90,6 +90,46 @@ export class PayPalCredentialResolver {
|
|
|
90
90
|
}
|
|
91
91
|
}
|
|
92
92
|
|
|
93
|
+
/**
|
|
94
|
+
* Sum of the capture amounts Medusa has already booked on the same payment
|
|
95
|
+
* as `captureRowId`, EXCLUDING that row (which Medusa creates before calling
|
|
96
|
+
* the provider). Lets `capturePayment` reconcile against Medusa's own ledger:
|
|
97
|
+
* whatever PayPal holds beyond this figure is a capture Medusa lost track of
|
|
98
|
+
* (its write failed and the admin is retrying with a fresh row) and must not
|
|
99
|
+
* be taken from the buyer a second time. Returns null when the row can't be
|
|
100
|
+
* resolved, in which case the caller falls back to PayPal's remaining amount.
|
|
101
|
+
*/
|
|
102
|
+
async getBookedCaptureTotal(captureRowId: string): Promise<number | null> {
|
|
103
|
+
try {
|
|
104
|
+
if (!captureRowId || typeof captureRowId !== "string") return null
|
|
105
|
+
const rows = await this.db("capture")
|
|
106
|
+
.select("payment_id")
|
|
107
|
+
.where("id", captureRowId)
|
|
108
|
+
.whereNull("deleted_at")
|
|
109
|
+
.limit(1)
|
|
110
|
+
const paymentId = rows?.[0]?.payment_id
|
|
111
|
+
if (!paymentId) return null
|
|
112
|
+
const others = await this.db("capture")
|
|
113
|
+
.select("amount", "raw_amount")
|
|
114
|
+
.where("payment_id", paymentId)
|
|
115
|
+
.whereNot("id", captureRowId)
|
|
116
|
+
.whereNull("deleted_at")
|
|
117
|
+
let total = 0
|
|
118
|
+
for (const row of others || []) {
|
|
119
|
+
const raw = row?.raw_amount
|
|
120
|
+
const fromRaw =
|
|
121
|
+
raw && typeof raw === "object" && raw.value !== undefined
|
|
122
|
+
? Number(raw.value)
|
|
123
|
+
: NaN
|
|
124
|
+
const v = Number.isFinite(fromRaw) ? fromRaw : Number(row?.amount)
|
|
125
|
+
if (Number.isFinite(v) && v > 0) total += v
|
|
126
|
+
}
|
|
127
|
+
return total
|
|
128
|
+
} catch {
|
|
129
|
+
return null
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
|
|
93
133
|
private getEnvCreds(
|
|
94
134
|
row: any,
|
|
95
135
|
env: Environment
|