@easypayment/medusa-payment-paypal 1.0.2 → 1.1.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 +7 -7
- package/.medusa/server/src/admin/index.mjs +7 -7
- package/.medusa/server/src/api/admin/paypal/onboard-complete/route.d.ts +2 -2
- package/.medusa/server/src/api/admin/paypal/onboard-complete/route.d.ts.map +1 -1
- package/.medusa/server/src/api/admin/paypal/onboard-complete/route.js +4 -0
- package/.medusa/server/src/api/admin/paypal/onboard-complete/route.js.map +1 -1
- package/.medusa/server/src/api/middlewares.d.ts.map +1 -1
- package/.medusa/server/src/api/middlewares.js +16 -1
- 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 +45 -16
- package/.medusa/server/src/api/store/paypal/capture-order/route.js.map +1 -1
- package/.medusa/server/src/api/store/paypal/config/route.d.ts.map +1 -1
- package/.medusa/server/src/api/store/paypal/config/route.js +7 -1
- package/.medusa/server/src/api/store/paypal/config/route.js.map +1 -1
- package/.medusa/server/src/api/store/paypal/onboard-return/route.d.ts.map +1 -1
- package/.medusa/server/src/api/store/paypal/onboard-return/route.js +24 -2
- package/.medusa/server/src/api/store/paypal/onboard-return/route.js.map +1 -1
- package/.medusa/server/src/api/store/paypal/webhook/route.d.ts.map +1 -1
- package/.medusa/server/src/api/store/paypal/webhook/route.js +22 -48
- package/.medusa/server/src/api/store/paypal/webhook/route.js.map +1 -1
- package/.medusa/server/src/api/utils/rate-limit.d.ts +3 -0
- package/.medusa/server/src/api/utils/rate-limit.d.ts.map +1 -0
- package/.medusa/server/src/api/utils/rate-limit.js +92 -0
- package/.medusa/server/src/api/utils/rate-limit.js.map +1 -0
- package/.medusa/server/src/jobs/paypal-webhook-retry.d.ts.map +1 -1
- package/.medusa/server/src/jobs/paypal-webhook-retry.js +115 -90
- package/.medusa/server/src/jobs/paypal-webhook-retry.js.map +1 -1
- package/.medusa/server/src/modules/paypal/payment-provider/base-provider.d.ts +48 -0
- package/.medusa/server/src/modules/paypal/payment-provider/base-provider.d.ts.map +1 -0
- package/.medusa/server/src/modules/paypal/payment-provider/base-provider.js +159 -0
- package/.medusa/server/src/modules/paypal/payment-provider/base-provider.js.map +1 -0
- package/.medusa/server/src/modules/paypal/payment-provider/card-service.d.ts +5 -20
- 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 +27 -160
- 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 +5 -20
- package/.medusa/server/src/modules/paypal/payment-provider/service.d.ts.map +1 -1
- package/.medusa/server/src/modules/paypal/payment-provider/service.js +21 -138
- package/.medusa/server/src/modules/paypal/payment-provider/service.js.map +1 -1
- package/.medusa/server/src/modules/paypal/utils/amounts.d.ts.map +1 -1
- package/.medusa/server/src/modules/paypal/utils/amounts.js +10 -0
- package/.medusa/server/src/modules/paypal/utils/amounts.js.map +1 -1
- package/.medusa/server/src/modules/paypal/utils/credential-resolver.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 +27 -26
- package/.medusa/server/src/modules/paypal/utils/credential-resolver.js.map +1 -1
- package/.medusa/server/src/modules/paypal/utils/partner.d.ts +9 -0
- package/.medusa/server/src/modules/paypal/utils/partner.d.ts.map +1 -0
- package/.medusa/server/src/modules/paypal/utils/partner.js +12 -0
- package/.medusa/server/src/modules/paypal/utils/partner.js.map +1 -0
- package/.medusa/server/src/modules/paypal/utils/payment-session.d.ts +0 -5
- package/.medusa/server/src/modules/paypal/utils/payment-session.d.ts.map +1 -1
- package/.medusa/server/src/modules/paypal/utils/payment-session.js +37 -18
- package/.medusa/server/src/modules/paypal/utils/payment-session.js.map +1 -1
- package/.medusa/server/src/modules/paypal/utils/secret-crypto.d.ts.map +1 -1
- package/.medusa/server/src/modules/paypal/utils/secret-crypto.js +30 -1
- package/.medusa/server/src/modules/paypal/utils/secret-crypto.js.map +1 -1
- package/.medusa/server/src/subscribers/paypal-webhook-process.d.ts +19 -0
- package/.medusa/server/src/subscribers/paypal-webhook-process.d.ts.map +1 -0
- package/.medusa/server/src/subscribers/paypal-webhook-process.js +107 -0
- package/.medusa/server/src/subscribers/paypal-webhook-process.js.map +1 -0
- package/CHANGELOG.md +73 -0
- package/package.json +4 -2
- package/src/api/admin/paypal/onboard-complete/route.ts +10 -2
- package/src/api/middlewares.ts +16 -1
- package/src/api/store/paypal/capture-order/route.ts +60 -22
- package/src/api/store/paypal/config/route.ts +8 -1
- package/src/api/store/paypal/onboard-return/route.ts +31 -6
- package/src/api/store/paypal/webhook/route.ts +24 -60
- package/src/api/utils/rate-limit.ts +105 -0
- package/src/jobs/paypal-webhook-retry.ts +132 -94
- package/src/modules/paypal/payment-provider/base-provider.ts +192 -0
- package/src/modules/paypal/payment-provider/card-service.ts +28 -196
- package/src/modules/paypal/payment-provider/service.ts +23 -164
- package/src/modules/paypal/utils/amounts.ts +10 -0
- package/src/modules/paypal/utils/credential-resolver.ts +32 -27
- package/src/modules/paypal/utils/partner.ts +8 -0
- package/src/modules/paypal/utils/payment-session.ts +44 -19
- package/src/modules/paypal/utils/secret-crypto.ts +36 -1
- package/src/subscribers/paypal-webhook-process.ts +127 -0
- package/.medusa/server/src/modules/paypal/clients/paypal-seller.client.d.ts +0 -15
- package/.medusa/server/src/modules/paypal/clients/paypal-seller.client.d.ts.map +0 -1
- package/.medusa/server/src/modules/paypal/clients/paypal-seller.client.js +0 -68
- package/.medusa/server/src/modules/paypal/clients/paypal-seller.client.js.map +0 -1
- package/src/modules/paypal/clients/paypal-seller.client.ts +0 -64
|
@@ -53,14 +53,38 @@ export async function GET(req: MedusaRequest, res: MedusaResponse) {
|
|
|
53
53
|
}
|
|
54
54
|
}
|
|
55
55
|
|
|
56
|
+
// Restrict the postMessage target to the configured admin origin instead of
|
|
57
|
+
// the "*" wildcard (which would deliver the relayed onboarding params to any
|
|
58
|
+
// origin that happens to open this popup). Prefer PAYPAL_ADMIN_ORIGIN, then
|
|
59
|
+
// the first entry of ADMIN_CORS; fall back to "*" only when neither is set,
|
|
60
|
+
// logging a warning so operators know to lock it down.
|
|
61
|
+
const resolveAdminOrigin = (): string => {
|
|
62
|
+
const explicit = (process.env.PAYPAL_ADMIN_ORIGIN || "").trim()
|
|
63
|
+
if (explicit) return explicit
|
|
64
|
+
const firstCors = (process.env.ADMIN_CORS || "")
|
|
65
|
+
.split(",")
|
|
66
|
+
.map((s) => s.trim())
|
|
67
|
+
.find(Boolean)
|
|
68
|
+
if (firstCors) return firstCors
|
|
69
|
+
console.warn(
|
|
70
|
+
"[PayPal] onboard-return: PAYPAL_ADMIN_ORIGIN/ADMIN_CORS not set \u2014 relaying onboarding result to postMessage origin '*'. Set PAYPAL_ADMIN_ORIGIN to your admin URL to restrict it."
|
|
71
|
+
)
|
|
72
|
+
return "*"
|
|
73
|
+
}
|
|
74
|
+
const targetOrigin = resolveAdminOrigin()
|
|
75
|
+
|
|
56
76
|
// JSON-encode then escape the characters that could break out of the inline
|
|
57
77
|
// <script> string/tag (including the U+2028/U+2029 separators that are legal in
|
|
58
78
|
// JSON but illegal in a JS string literal), so the relayed params embed safely.
|
|
59
|
-
const
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
79
|
+
const escapeForScript = (value: string) =>
|
|
80
|
+
value
|
|
81
|
+
.replace(/</g, "\\u003c")
|
|
82
|
+
.replace(/>/g, "\\u003e")
|
|
83
|
+
.replace(/&/g, "\\u0026")
|
|
84
|
+
.replace(/[\u2028\u2029]/g, (c) => "\\u" + c.charCodeAt(0).toString(16).padStart(4, "0"))
|
|
85
|
+
|
|
86
|
+
const safePayload = escapeForScript(JSON.stringify(params))
|
|
87
|
+
const safeTargetOrigin = escapeForScript(JSON.stringify(targetOrigin))
|
|
64
88
|
|
|
65
89
|
const html = `<!doctype html>
|
|
66
90
|
<html lang="en">
|
|
@@ -71,8 +95,9 @@ export async function GET(req: MedusaRequest, res: MedusaResponse) {
|
|
|
71
95
|
(function () {
|
|
72
96
|
try {
|
|
73
97
|
var message = { source: "paypal-onboarding-return", params: ${safePayload} };
|
|
98
|
+
var targetOrigin = ${safeTargetOrigin};
|
|
74
99
|
if (window.opener && !window.opener.closed) {
|
|
75
|
-
try { window.opener.postMessage(message,
|
|
100
|
+
try { window.opener.postMessage(message, targetOrigin); } catch (e) {}
|
|
76
101
|
}
|
|
77
102
|
} catch (e) {}
|
|
78
103
|
// Give the opener a moment to react, then close the popup.
|
|
@@ -1,13 +1,13 @@
|
|
|
1
1
|
import type { MedusaRequest, MedusaResponse } from "@medusajs/framework/http"
|
|
2
|
+
import { Modules } from "@medusajs/framework/utils"
|
|
3
|
+
import type { IEventBusModuleService } from "@medusajs/framework/types"
|
|
2
4
|
import type PayPalModuleService from "../../../../modules/paypal/service"
|
|
3
5
|
import { paypalFetch } from "../../../../modules/paypal/utils/paypal-fetch"
|
|
4
6
|
import {
|
|
5
|
-
computeNextRetryAt,
|
|
6
7
|
isAllowedEventType,
|
|
7
|
-
isRetryableError,
|
|
8
8
|
normalizeEventVersion,
|
|
9
|
-
processPayPalWebhookEvent,
|
|
10
9
|
} from "../../../../modules/paypal/webhook-processor"
|
|
10
|
+
import { PAYPAL_WEBHOOK_RECEIVED_EVENT } from "../../../../subscribers/paypal-webhook-process"
|
|
11
11
|
import {
|
|
12
12
|
composeVerifyRequestBody,
|
|
13
13
|
rawBodyToString,
|
|
@@ -280,71 +280,35 @@ export async function POST(req: MedusaRequest, res: MedusaResponse) {
|
|
|
280
280
|
return res.json({ ok: true, ignored: true })
|
|
281
281
|
}
|
|
282
282
|
|
|
283
|
+
// Process the verified, persisted event asynchronously: emit an event and
|
|
284
|
+
// return 200 immediately so PayPal's ~15s webhook delivery timeout is never
|
|
285
|
+
// tripped by slow downstream work (the audit's synchronous-processing
|
|
286
|
+
// bottleneck). The `paypal-webhook-process` subscriber does the actual work
|
|
287
|
+
// off the request path; if the event bus drops the message, the webhook retry
|
|
288
|
+
// cron recovers events left in "processing" past a staleness threshold, so the
|
|
289
|
+
// event is never lost. The record is already persisted as "processing" above.
|
|
283
290
|
try {
|
|
284
|
-
const
|
|
285
|
-
|
|
286
|
-
|
|
287
|
-
|
|
288
|
-
|
|
289
|
-
|
|
290
|
-
status: "processed",
|
|
291
|
-
processed_at: new Date(),
|
|
292
|
-
resource_id:
|
|
293
|
-
processed.refundId || processed.captureId || processed.orderId || null,
|
|
294
|
-
})
|
|
295
|
-
.catch(() => {})
|
|
296
|
-
}
|
|
297
|
-
|
|
298
|
-
console.info("[PayPal] webhook: processed", {
|
|
291
|
+
const eventBus = req.scope.resolve<IEventBusModuleService>(Modules.EVENT_BUS)
|
|
292
|
+
await eventBus.emit({
|
|
293
|
+
name: PAYPAL_WEBHOOK_RECEIVED_EVENT,
|
|
294
|
+
data: { id: recordId },
|
|
295
|
+
})
|
|
296
|
+
console.info("[PayPal] webhook: accepted for async processing", {
|
|
299
297
|
event_id: eventId,
|
|
300
298
|
event_type: eventType,
|
|
301
|
-
|
|
302
|
-
capture_id: processed.captureId,
|
|
303
|
-
refund_id: processed.refundId,
|
|
304
|
-
cart_id: processed.cartId,
|
|
305
|
-
session_updated: processed.sessionUpdated,
|
|
299
|
+
record_id: recordId,
|
|
306
300
|
})
|
|
307
|
-
|
|
308
|
-
await paypal.recordMetric("webhook_success").catch(() => {})
|
|
309
|
-
return res.json({ ok: true })
|
|
310
301
|
} catch (e: any) {
|
|
311
|
-
|
|
302
|
+
// The event was persisted as "processing"; the retry cron's stale-processing
|
|
303
|
+
// recovery will pick it up even though the emit failed. Ack PayPal anyway so
|
|
304
|
+
// it doesn't re-deliver (which would just dedupe).
|
|
305
|
+
console.error("[PayPal] webhook: failed to enqueue async processing (retry cron will recover)", {
|
|
312
306
|
event_id: eventId,
|
|
313
307
|
event_type: eventType,
|
|
308
|
+
record_id: recordId,
|
|
314
309
|
error: e?.message,
|
|
315
310
|
})
|
|
316
|
-
|
|
317
|
-
const retryable = isRetryableError(e)
|
|
318
|
-
const nextStatus = retryable ? "failed" : "dead_letter"
|
|
319
|
-
|
|
320
|
-
if (recordId) {
|
|
321
|
-
await paypal
|
|
322
|
-
.updateWebhookEventRecord({
|
|
323
|
-
id: recordId,
|
|
324
|
-
status: nextStatus,
|
|
325
|
-
attempt_count: 1,
|
|
326
|
-
next_retry_at: retryable ? computeNextRetryAt(1) : null,
|
|
327
|
-
last_error: e?.message || String(e),
|
|
328
|
-
})
|
|
329
|
-
.catch(() => {})
|
|
330
|
-
}
|
|
331
|
-
|
|
332
|
-
await paypal
|
|
333
|
-
.recordAuditEvent("webhook_processing_failed", {
|
|
334
|
-
event_id: eventId,
|
|
335
|
-
event_type: eventType,
|
|
336
|
-
retryable,
|
|
337
|
-
message: e?.message || String(e),
|
|
338
|
-
})
|
|
339
|
-
.catch(() => {})
|
|
340
|
-
|
|
341
|
-
await paypal.recordMetric("webhook_failed").catch(() => {})
|
|
342
|
-
|
|
343
|
-
if (!retryable) {
|
|
344
|
-
return res.status(200).json({ ok: false, message: "Webhook processing failed" })
|
|
345
|
-
}
|
|
346
|
-
return res
|
|
347
|
-
.status(500)
|
|
348
|
-
.json({ message: "PayPal webhook processing error" })
|
|
349
311
|
}
|
|
312
|
+
|
|
313
|
+
return res.json({ ok: true, accepted: true })
|
|
350
314
|
}
|
|
@@ -0,0 +1,105 @@
|
|
|
1
|
+
import type { MedusaNextFunction, MedusaRequest, MedusaResponse } from "@medusajs/framework/http"
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Lightweight in-memory rate limiter for the public store payment routes.
|
|
5
|
+
*
|
|
6
|
+
* The store PayPal routes (create-order, capture-order, paypal-complete) are
|
|
7
|
+
* unauthenticated by necessity, so without a limit a caller can hammer them —
|
|
8
|
+
* e.g. enumerate cart ids and create unbounded PayPal orders against the
|
|
9
|
+
* merchant account. This applies a fixed-window per-client cap.
|
|
10
|
+
*
|
|
11
|
+
* OPT-IN: disabled unless `PAYPAL_RATE_LIMIT_MAX` is set to a positive number.
|
|
12
|
+
* This is deliberate — behind a load balancer / CDN that doesn't forward the
|
|
13
|
+
* real client IP, every request would share one bucket and a low limit could
|
|
14
|
+
* block legitimate checkouts. Merchants opt in once they've confirmed the real
|
|
15
|
+
* client IP reaches the app (e.g. `x-forwarded-for` is set correctly).
|
|
16
|
+
*
|
|
17
|
+
* NOTE: the counter lives in process memory, so the limit is enforced per
|
|
18
|
+
* server instance, not globally across a horizontally-scaled deployment. It is
|
|
19
|
+
* a pragmatic first line of defense and a backstop; a shared store (Redis) or
|
|
20
|
+
* an edge/CDN limiter is the right tool for a hard global guarantee. Tunable via
|
|
21
|
+
* PAYPAL_RATE_LIMIT_MAX (requests) and PAYPAL_RATE_LIMIT_WINDOW_MS (window).
|
|
22
|
+
*/
|
|
23
|
+
|
|
24
|
+
const DEFAULT_WINDOW_MS = 60_000
|
|
25
|
+
|
|
26
|
+
// Cap the number of distinct client buckets we retain so a flood of unique
|
|
27
|
+
// client keys can't grow the map unbounded (a memory-exhaustion vector of its
|
|
28
|
+
// own). Oldest buckets are evicted first once the cap is hit.
|
|
29
|
+
const MAX_BUCKETS = 10_000
|
|
30
|
+
|
|
31
|
+
type Bucket = { count: number; resetAt: number }
|
|
32
|
+
|
|
33
|
+
function readEnvInt(name: string, fallback: number): number {
|
|
34
|
+
const v = Number(process.env[name])
|
|
35
|
+
return Number.isFinite(v) && v > 0 ? v : fallback
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/** The configured max, or null when rate limiting is disabled (opt-in). */
|
|
39
|
+
function readConfiguredMax(): number | null {
|
|
40
|
+
const raw = process.env.PAYPAL_RATE_LIMIT_MAX
|
|
41
|
+
if (raw === undefined || raw === "") return null
|
|
42
|
+
const v = Number(raw)
|
|
43
|
+
return Number.isFinite(v) && v > 0 ? v : null
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
function clientKey(req: MedusaRequest): string {
|
|
47
|
+
const fwd = req.headers["x-forwarded-for"]
|
|
48
|
+
const fwdIp = Array.isArray(fwd) ? fwd[0] : fwd
|
|
49
|
+
const ip =
|
|
50
|
+
(fwdIp ? fwdIp.split(",")[0].trim() : undefined) ||
|
|
51
|
+
req.socket?.remoteAddress ||
|
|
52
|
+
"unknown"
|
|
53
|
+
return ip
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
export function createRateLimiter(scope: string) {
|
|
57
|
+
const buckets = new Map<string, Bucket>()
|
|
58
|
+
|
|
59
|
+
return function rateLimit(
|
|
60
|
+
req: MedusaRequest,
|
|
61
|
+
res: MedusaResponse,
|
|
62
|
+
next: MedusaNextFunction
|
|
63
|
+
) {
|
|
64
|
+
// Opt-in: with no configured max, this middleware is a pass-through so
|
|
65
|
+
// existing deployments (especially behind a shared-IP proxy) are unaffected.
|
|
66
|
+
const max = readConfiguredMax()
|
|
67
|
+
if (max === null) {
|
|
68
|
+
return next()
|
|
69
|
+
}
|
|
70
|
+
const windowMs = readEnvInt("PAYPAL_RATE_LIMIT_WINDOW_MS", DEFAULT_WINDOW_MS)
|
|
71
|
+
const now = Date.now()
|
|
72
|
+
const key = `${scope}:${clientKey(req)}`
|
|
73
|
+
|
|
74
|
+
let bucket = buckets.get(key)
|
|
75
|
+
if (!bucket || bucket.resetAt <= now) {
|
|
76
|
+
bucket = { count: 0, resetAt: now + windowMs }
|
|
77
|
+
buckets.set(key, bucket)
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
bucket.count += 1
|
|
81
|
+
|
|
82
|
+
if (buckets.size > MAX_BUCKETS) {
|
|
83
|
+
// Evict expired buckets first; if still over, drop the oldest inserted.
|
|
84
|
+
for (const [k, b] of buckets) {
|
|
85
|
+
if (b.resetAt <= now) buckets.delete(k)
|
|
86
|
+
if (buckets.size <= MAX_BUCKETS) break
|
|
87
|
+
}
|
|
88
|
+
while (buckets.size > MAX_BUCKETS) {
|
|
89
|
+
const oldest = buckets.keys().next().value
|
|
90
|
+
if (oldest === undefined) break
|
|
91
|
+
buckets.delete(oldest)
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
if (bucket.count > max) {
|
|
96
|
+
const retryAfterSec = Math.max(1, Math.ceil((bucket.resetAt - now) / 1000))
|
|
97
|
+
res.setHeader("Retry-After", String(retryAfterSec))
|
|
98
|
+
return res
|
|
99
|
+
.status(429)
|
|
100
|
+
.json({ message: "Too many requests. Please slow down and try again." })
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
return next()
|
|
104
|
+
}
|
|
105
|
+
}
|
|
@@ -13,6 +13,15 @@ import {
|
|
|
13
13
|
// unbounded backlog into memory.
|
|
14
14
|
const RETRY_BATCH_SIZE = 100
|
|
15
15
|
|
|
16
|
+
// Events are persisted as "processing" and handed to the async subscriber. If
|
|
17
|
+
// the subscriber never runs (bus dropped the message, process restarted
|
|
18
|
+
// mid-flight), the event would otherwise sit in "processing" forever. Recover
|
|
19
|
+
// any left in "processing" past this age so async delivery is guaranteed.
|
|
20
|
+
const STALE_PROCESSING_MS = (() => {
|
|
21
|
+
const v = Number(process.env.PAYPAL_WEBHOOK_STALE_PROCESSING_MS)
|
|
22
|
+
return Number.isFinite(v) && v > 0 ? v : 5 * 60 * 1000
|
|
23
|
+
})()
|
|
24
|
+
|
|
16
25
|
// Stable key for the Postgres advisory lock that serializes this cron across
|
|
17
26
|
// instances. pg_try_advisory_xact_lock auto-releases at transaction end, so
|
|
18
27
|
// there is no unlock to pair (and no risk of a leaked lock).
|
|
@@ -59,136 +68,165 @@ async function runRetrySweep(container: MedusaContainer) {
|
|
|
59
68
|
const paypal = container.resolve<PayPalModuleService>("paypal_onboarding")
|
|
60
69
|
const now = Date.now()
|
|
61
70
|
|
|
62
|
-
|
|
71
|
+
// 1. Failed events whose backoff has elapsed.
|
|
72
|
+
const failed = await paypal.listPayPalWebhookEvents(
|
|
63
73
|
{ status: "failed" },
|
|
64
74
|
{ take: RETRY_BATCH_SIZE, order: { next_retry_at: "ASC" } }
|
|
65
75
|
)
|
|
66
|
-
|
|
76
|
+
const dueFailed = (failed || []).filter((event: any) => {
|
|
77
|
+
const nextRetryAt = event?.next_retry_at
|
|
78
|
+
? new Date(event.next_retry_at).getTime()
|
|
79
|
+
: null
|
|
80
|
+
return nextRetryAt !== null && nextRetryAt <= now
|
|
81
|
+
})
|
|
82
|
+
|
|
83
|
+
// 2. Events stuck in "processing" past the staleness threshold — the async
|
|
84
|
+
// subscriber never finished them (dropped bus message / restart), so recover.
|
|
85
|
+
const processing = await paypal.listPayPalWebhookEvents(
|
|
86
|
+
{ status: "processing" },
|
|
87
|
+
{ take: RETRY_BATCH_SIZE, order: { updated_at: "ASC" } }
|
|
88
|
+
)
|
|
89
|
+
const staleProcessing = (processing || []).filter((event: any) => {
|
|
90
|
+
const stamp = event?.updated_at || event?.created_at
|
|
91
|
+
const ageMs = stamp ? now - new Date(stamp).getTime() : Infinity
|
|
92
|
+
return ageMs >= STALE_PROCESSING_MS
|
|
93
|
+
})
|
|
94
|
+
if (staleProcessing.length) {
|
|
95
|
+
console.warn(
|
|
96
|
+
`[PayPal] webhook-retry: recovering ${staleProcessing.length} stale "processing" event(s)`
|
|
97
|
+
)
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
const candidates = [...dueFailed, ...staleProcessing]
|
|
101
|
+
if (!candidates.length) return
|
|
67
102
|
|
|
68
103
|
console.info(
|
|
69
|
-
`[PayPal] webhook-retry: evaluating ${candidates.length}
|
|
104
|
+
`[PayPal] webhook-retry: evaluating ${candidates.length} event(s) (${dueFailed.length} failed, ${staleProcessing.length} stale)`
|
|
70
105
|
)
|
|
71
106
|
|
|
72
107
|
for (const event of candidates) {
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
if (!nextRetryAt || nextRetryAt > now) continue
|
|
108
|
+
await attemptRetry(paypal, container, event)
|
|
109
|
+
}
|
|
110
|
+
}
|
|
77
111
|
|
|
78
|
-
|
|
112
|
+
async function attemptRetry(
|
|
113
|
+
paypal: PayPalModuleService,
|
|
114
|
+
container: MedusaContainer,
|
|
115
|
+
event: any
|
|
116
|
+
) {
|
|
117
|
+
const attemptCount = Number(event.attempt_count || 0)
|
|
79
118
|
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
id: event.id,
|
|
84
|
-
status: "dead_letter",
|
|
85
|
-
next_retry_at: null,
|
|
86
|
-
last_error: `Exceeded max attempts (${MAX_WEBHOOK_ATTEMPTS})`,
|
|
87
|
-
})
|
|
88
|
-
.catch(() => {})
|
|
89
|
-
console.warn("[PayPal] webhook-retry: dead-lettered (max attempts)", {
|
|
119
|
+
if (attemptCount >= MAX_WEBHOOK_ATTEMPTS) {
|
|
120
|
+
await paypal
|
|
121
|
+
.updateWebhookEventRecord({
|
|
90
122
|
id: event.id,
|
|
91
|
-
|
|
92
|
-
|
|
123
|
+
status: "dead_letter",
|
|
124
|
+
next_retry_at: null,
|
|
125
|
+
last_error: `Exceeded max attempts (${MAX_WEBHOOK_ATTEMPTS})`,
|
|
93
126
|
})
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
127
|
+
.catch(() => {})
|
|
128
|
+
console.warn("[PayPal] webhook-retry: dead-lettered (max attempts)", {
|
|
129
|
+
id: event.id,
|
|
130
|
+
event_type: event.event_type,
|
|
131
|
+
attempts: attemptCount,
|
|
132
|
+
})
|
|
133
|
+
await paypal.recordMetric("webhook_dead_letter").catch(() => {})
|
|
134
|
+
return
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
await paypal
|
|
138
|
+
.updateWebhookEventRecord({
|
|
139
|
+
id: event.id,
|
|
140
|
+
status: "processing",
|
|
141
|
+
attempt_count: attemptCount + 1,
|
|
142
|
+
next_retry_at: null,
|
|
143
|
+
last_error: null,
|
|
144
|
+
})
|
|
145
|
+
.catch(() => {})
|
|
146
|
+
|
|
147
|
+
const eventType = String(event.event_type || "")
|
|
97
148
|
|
|
149
|
+
if (!isAllowedEventType(eventType)) {
|
|
98
150
|
await paypal
|
|
99
151
|
.updateWebhookEventRecord({
|
|
100
152
|
id: event.id,
|
|
101
|
-
status: "
|
|
102
|
-
|
|
103
|
-
next_retry_at: null,
|
|
104
|
-
last_error: null,
|
|
153
|
+
status: "ignored",
|
|
154
|
+
processed_at: new Date(),
|
|
105
155
|
})
|
|
106
156
|
.catch(() => {})
|
|
157
|
+
console.info("[PayPal] webhook-retry: ignored unsupported event type", {
|
|
158
|
+
id: event.id,
|
|
159
|
+
event_type: eventType,
|
|
160
|
+
})
|
|
161
|
+
return
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
try {
|
|
165
|
+
const payload = (event.payload || {}) as Record<string, any>
|
|
166
|
+
const processed = await processPayPalWebhookEvent(container, { eventType, payload })
|
|
107
167
|
|
|
108
|
-
|
|
168
|
+
await paypal
|
|
169
|
+
.updateWebhookEventRecord({
|
|
170
|
+
id: event.id,
|
|
171
|
+
status: "processed",
|
|
172
|
+
processed_at: new Date(),
|
|
173
|
+
resource_id:
|
|
174
|
+
processed.refundId || processed.captureId || processed.orderId || null,
|
|
175
|
+
})
|
|
176
|
+
.catch(() => {})
|
|
177
|
+
|
|
178
|
+
console.info("[PayPal] webhook-retry: processed successfully", {
|
|
179
|
+
id: event.id,
|
|
180
|
+
event_type: eventType,
|
|
181
|
+
attempt: attemptCount + 1,
|
|
182
|
+
order_id: processed.orderId,
|
|
183
|
+
capture_id: processed.captureId,
|
|
184
|
+
cart_id: processed.cartId,
|
|
185
|
+
session_updated: processed.sessionUpdated,
|
|
186
|
+
})
|
|
109
187
|
|
|
110
|
-
|
|
188
|
+
await paypal.recordMetric("webhook_retry_success").catch(() => {})
|
|
189
|
+
} catch (error: any) {
|
|
190
|
+
const retryable = isRetryableError(error)
|
|
191
|
+
const nextAttempt = attemptCount + 1
|
|
192
|
+
|
|
193
|
+
if (!retryable || nextAttempt >= MAX_WEBHOOK_ATTEMPTS) {
|
|
111
194
|
await paypal
|
|
112
195
|
.updateWebhookEventRecord({
|
|
113
196
|
id: event.id,
|
|
114
|
-
status: "
|
|
115
|
-
|
|
197
|
+
status: "dead_letter",
|
|
198
|
+
attempt_count: nextAttempt,
|
|
199
|
+
next_retry_at: null,
|
|
200
|
+
last_error: error?.message || String(error),
|
|
116
201
|
})
|
|
117
202
|
.catch(() => {})
|
|
118
|
-
console.
|
|
203
|
+
console.error("[PayPal] webhook-retry: dead-lettered after error", {
|
|
119
204
|
id: event.id,
|
|
120
205
|
event_type: eventType,
|
|
206
|
+
attempt: nextAttempt,
|
|
207
|
+
retryable,
|
|
208
|
+
error: error?.message,
|
|
121
209
|
})
|
|
122
|
-
|
|
123
|
-
}
|
|
124
|
-
|
|
125
|
-
try {
|
|
126
|
-
const payload = (event.payload || {}) as Record<string, any>
|
|
127
|
-
const processed = await processPayPalWebhookEvent(container, { eventType, payload })
|
|
128
|
-
|
|
210
|
+
await paypal.recordMetric("webhook_dead_letter").catch(() => {})
|
|
211
|
+
} else {
|
|
212
|
+
const nextRetry = computeNextRetryAt(nextAttempt)
|
|
129
213
|
await paypal
|
|
130
214
|
.updateWebhookEventRecord({
|
|
131
215
|
id: event.id,
|
|
132
|
-
status: "
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
216
|
+
status: "failed",
|
|
217
|
+
attempt_count: nextAttempt,
|
|
218
|
+
next_retry_at: nextRetry,
|
|
219
|
+
last_error: error?.message || String(error),
|
|
136
220
|
})
|
|
137
221
|
.catch(() => {})
|
|
138
|
-
|
|
139
|
-
console.info("[PayPal] webhook-retry: processed successfully", {
|
|
222
|
+
console.warn("[PayPal] webhook-retry: scheduled retry", {
|
|
140
223
|
id: event.id,
|
|
141
224
|
event_type: eventType,
|
|
142
|
-
attempt:
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
cart_id: processed.cartId,
|
|
146
|
-
session_updated: processed.sessionUpdated,
|
|
225
|
+
attempt: nextAttempt,
|
|
226
|
+
next_retry_at: nextRetry?.toISOString(),
|
|
227
|
+
error: error?.message,
|
|
147
228
|
})
|
|
148
|
-
|
|
149
|
-
await paypal.recordMetric("webhook_retry_success").catch(() => {})
|
|
150
|
-
} catch (error: any) {
|
|
151
|
-
const retryable = isRetryableError(error)
|
|
152
|
-
const nextAttempt = attemptCount + 1
|
|
153
|
-
|
|
154
|
-
if (!retryable || nextAttempt >= MAX_WEBHOOK_ATTEMPTS) {
|
|
155
|
-
await paypal
|
|
156
|
-
.updateWebhookEventRecord({
|
|
157
|
-
id: event.id,
|
|
158
|
-
status: "dead_letter",
|
|
159
|
-
attempt_count: nextAttempt,
|
|
160
|
-
next_retry_at: null,
|
|
161
|
-
last_error: error?.message || String(error),
|
|
162
|
-
})
|
|
163
|
-
.catch(() => {})
|
|
164
|
-
console.error("[PayPal] webhook-retry: dead-lettered after error", {
|
|
165
|
-
id: event.id,
|
|
166
|
-
event_type: eventType,
|
|
167
|
-
attempt: nextAttempt,
|
|
168
|
-
retryable,
|
|
169
|
-
error: error?.message,
|
|
170
|
-
})
|
|
171
|
-
await paypal.recordMetric("webhook_dead_letter").catch(() => {})
|
|
172
|
-
} else {
|
|
173
|
-
const nextRetry = computeNextRetryAt(nextAttempt)
|
|
174
|
-
await paypal
|
|
175
|
-
.updateWebhookEventRecord({
|
|
176
|
-
id: event.id,
|
|
177
|
-
status: "failed",
|
|
178
|
-
attempt_count: nextAttempt,
|
|
179
|
-
next_retry_at: nextRetry,
|
|
180
|
-
last_error: error?.message || String(error),
|
|
181
|
-
})
|
|
182
|
-
.catch(() => {})
|
|
183
|
-
console.warn("[PayPal] webhook-retry: scheduled retry", {
|
|
184
|
-
id: event.id,
|
|
185
|
-
event_type: eventType,
|
|
186
|
-
attempt: nextAttempt,
|
|
187
|
-
next_retry_at: nextRetry?.toISOString(),
|
|
188
|
-
error: error?.message,
|
|
189
|
-
})
|
|
190
|
-
await paypal.recordMetric("webhook_retry_failed").catch(() => {})
|
|
191
|
-
}
|
|
229
|
+
await paypal.recordMetric("webhook_retry_failed").catch(() => {})
|
|
192
230
|
}
|
|
193
231
|
}
|
|
194
232
|
}
|