@easypayment/medusa-payment-paypal 1.1.1 → 1.2.0

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 (90) hide show
  1. package/.medusa/server/src/admin/index.js +7 -7
  2. package/.medusa/server/src/admin/index.mjs +7 -7
  3. package/.medusa/server/src/api/hooks/paypal/onboard-return/route.d.ts +16 -0
  4. package/.medusa/server/src/api/hooks/paypal/onboard-return/route.d.ts.map +1 -0
  5. package/.medusa/server/src/api/hooks/paypal/onboard-return/route.js +20 -0
  6. package/.medusa/server/src/api/hooks/paypal/onboard-return/route.js.map +1 -0
  7. package/.medusa/server/src/api/hooks/paypal/webhook/route.d.ts +18 -0
  8. package/.medusa/server/src/api/hooks/paypal/webhook/route.d.ts.map +1 -0
  9. package/.medusa/server/src/api/hooks/paypal/webhook/route.js +22 -0
  10. package/.medusa/server/src/api/hooks/paypal/webhook/route.js.map +1 -0
  11. package/.medusa/server/src/api/middlewares.d.ts.map +1 -1
  12. package/.medusa/server/src/api/middlewares.js +24 -1
  13. package/.medusa/server/src/api/middlewares.js.map +1 -1
  14. package/.medusa/server/src/api/store/paypal/capture-order/route.d.ts.map +1 -1
  15. package/.medusa/server/src/api/store/paypal/capture-order/route.js +66 -13
  16. package/.medusa/server/src/api/store/paypal/capture-order/route.js.map +1 -1
  17. package/.medusa/server/src/api/store/paypal/config/route.d.ts.map +1 -1
  18. package/.medusa/server/src/api/store/paypal/config/route.js +8 -0
  19. package/.medusa/server/src/api/store/paypal/config/route.js.map +1 -1
  20. package/.medusa/server/src/api/store/paypal/create-order/route.d.ts.map +1 -1
  21. package/.medusa/server/src/api/store/paypal/create-order/route.js +63 -9
  22. package/.medusa/server/src/api/store/paypal/create-order/route.js.map +1 -1
  23. package/.medusa/server/src/api/store/paypal-complete/route.js +1 -1
  24. package/.medusa/server/src/api/store/paypal-complete/route.js.map +1 -1
  25. package/.medusa/server/src/api/utils/rate-limit.d.ts +13 -1
  26. package/.medusa/server/src/api/utils/rate-limit.d.ts.map +1 -1
  27. package/.medusa/server/src/api/utils/rate-limit.js +18 -7
  28. package/.medusa/server/src/api/utils/rate-limit.js.map +1 -1
  29. package/.medusa/server/src/jobs/paypal-webhook-retry.d.ts.map +1 -1
  30. package/.medusa/server/src/jobs/paypal-webhook-retry.js +4 -0
  31. package/.medusa/server/src/jobs/paypal-webhook-retry.js.map +1 -1
  32. package/.medusa/server/src/modules/paypal/payment-provider/base-provider.d.ts +47 -3
  33. package/.medusa/server/src/modules/paypal/payment-provider/base-provider.d.ts.map +1 -1
  34. package/.medusa/server/src/modules/paypal/payment-provider/base-provider.js +73 -0
  35. package/.medusa/server/src/modules/paypal/payment-provider/base-provider.js.map +1 -1
  36. package/.medusa/server/src/modules/paypal/payment-provider/card-service.d.ts.map +1 -1
  37. package/.medusa/server/src/modules/paypal/payment-provider/card-service.js +415 -285
  38. package/.medusa/server/src/modules/paypal/payment-provider/card-service.js.map +1 -1
  39. package/.medusa/server/src/modules/paypal/payment-provider/service.d.ts +0 -4
  40. package/.medusa/server/src/modules/paypal/payment-provider/service.d.ts.map +1 -1
  41. package/.medusa/server/src/modules/paypal/payment-provider/service.js +140 -151
  42. package/.medusa/server/src/modules/paypal/payment-provider/service.js.map +1 -1
  43. package/.medusa/server/src/modules/paypal/service.d.ts +7 -0
  44. package/.medusa/server/src/modules/paypal/service.d.ts.map +1 -1
  45. package/.medusa/server/src/modules/paypal/service.js +135 -13
  46. package/.medusa/server/src/modules/paypal/service.js.map +1 -1
  47. package/.medusa/server/src/modules/paypal/types/config.d.ts.map +1 -1
  48. package/.medusa/server/src/modules/paypal/types/config.js +13 -0
  49. package/.medusa/server/src/modules/paypal/types/config.js.map +1 -1
  50. package/.medusa/server/src/modules/paypal/utils/amounts.d.ts +1 -1
  51. package/.medusa/server/src/modules/paypal/utils/credential-resolver.d.ts +10 -0
  52. package/.medusa/server/src/modules/paypal/utils/credential-resolver.d.ts.map +1 -1
  53. package/.medusa/server/src/modules/paypal/utils/credential-resolver.js +49 -34
  54. package/.medusa/server/src/modules/paypal/utils/credential-resolver.js.map +1 -1
  55. package/.medusa/server/src/modules/paypal/utils/metrics.d.ts +18 -0
  56. package/.medusa/server/src/modules/paypal/utils/metrics.d.ts.map +1 -0
  57. package/.medusa/server/src/modules/paypal/utils/metrics.js +45 -0
  58. package/.medusa/server/src/modules/paypal/utils/metrics.js.map +1 -0
  59. package/.medusa/server/src/modules/paypal/utils/paypal-fetch.d.ts.map +1 -1
  60. package/.medusa/server/src/modules/paypal/utils/paypal-fetch.js +45 -28
  61. package/.medusa/server/src/modules/paypal/utils/paypal-fetch.js.map +1 -1
  62. package/.medusa/server/src/modules/paypal/webhook-processor.d.ts +27 -0
  63. package/.medusa/server/src/modules/paypal/webhook-processor.d.ts.map +1 -1
  64. package/.medusa/server/src/modules/paypal/webhook-processor.js +170 -9
  65. package/.medusa/server/src/modules/paypal/webhook-processor.js.map +1 -1
  66. package/.medusa/server/src/subscribers/paypal-webhook-process.d.ts.map +1 -1
  67. package/.medusa/server/src/subscribers/paypal-webhook-process.js +4 -0
  68. package/.medusa/server/src/subscribers/paypal-webhook-process.js.map +1 -1
  69. package/CHANGELOG.md +208 -73
  70. package/README.md +175 -184
  71. package/package.json +91 -90
  72. package/src/api/hooks/paypal/onboard-return/route.ts +15 -0
  73. package/src/api/hooks/paypal/webhook/route.ts +17 -0
  74. package/src/api/middlewares.ts +24 -1
  75. package/src/api/store/paypal/capture-order/route.ts +83 -12
  76. package/src/api/store/paypal/config/route.ts +8 -0
  77. package/src/api/store/paypal/create-order/route.ts +73 -9
  78. package/src/api/store/paypal-complete/route.ts +1 -1
  79. package/src/api/utils/rate-limit.ts +31 -7
  80. package/src/jobs/paypal-webhook-retry.ts +4 -0
  81. package/src/modules/paypal/payment-provider/base-provider.ts +83 -0
  82. package/src/modules/paypal/payment-provider/card-service.ts +277 -136
  83. package/src/modules/paypal/payment-provider/service.ts +149 -186
  84. package/src/modules/paypal/service.ts +1703 -1554
  85. package/src/modules/paypal/types/config.ts +16 -0
  86. package/src/modules/paypal/utils/credential-resolver.ts +45 -36
  87. package/src/modules/paypal/utils/metrics.ts +48 -0
  88. package/src/modules/paypal/utils/paypal-fetch.ts +58 -29
  89. package/src/modules/paypal/webhook-processor.ts +195 -10
  90. package/src/subscribers/paypal-webhook-process.ts +4 -0
@@ -37,36 +37,6 @@ class PayPalPaymentProvider extends PayPalProviderBase {
37
37
  protected readonly sessionPrefix = "pp"
38
38
  protected readonly idempotencyPrefix = "pp"
39
39
 
40
- private serializeError(error: unknown) {
41
- if (error instanceof Error) {
42
- const errorWithCause = error as Error & { cause?: unknown }
43
- const cause = errorWithCause.cause
44
- return {
45
- name: error.name,
46
- message: error.message,
47
- stack: error.stack,
48
- cause:
49
- cause instanceof Error
50
- ? { name: cause.name, message: cause.message, stack: cause.stack }
51
- : cause,
52
- }
53
- }
54
- return { message: String(error) }
55
- }
56
-
57
- private async recordFailure(eventType: string, metadata?: Record<string, unknown>) {
58
- await this.paypal.recordAuditEvent(eventType, metadata)
59
- await this.paypal.recordMetric(eventType, metadata)
60
- }
61
-
62
- private async recordSuccess(metricName: string) {
63
- await this.paypal.recordMetric(metricName)
64
- }
65
-
66
- private async recordPaymentEvent(eventType: string, metadata?: Record<string, unknown>) {
67
- await this.paypal.recordAuditEvent(eventType, metadata)
68
- }
69
-
70
40
  async initiatePayment(input: InitiatePaymentInput): Promise<InitiatePaymentOutput> {
71
41
  const providerId = (input.data as Record<string, any> | undefined)?.provider_id
72
42
  try {
@@ -112,6 +82,7 @@ class PayPalPaymentProvider extends PayPalProviderBase {
112
82
  return {
113
83
  data: {
114
84
  ...(input.data || {}),
85
+ ...this.invalidateStaleOrder(input, currencyCode),
115
86
  ...(providerId ? { provider_id: providerId } : {}),
116
87
  amount: input.amount,
117
88
  currency_code: currencyCode,
@@ -122,29 +93,22 @@ class PayPalPaymentProvider extends PayPalProviderBase {
122
93
  async authorizePayment(
123
94
  input: AuthorizePaymentInput
124
95
  ): Promise<AuthorizePaymentOutput> {
125
- const { data, amount, currencyCode } = await this.normalizePaymentData(input)
96
+ const { data } = await this.normalizePaymentData(input)
126
97
  const existingPayPal = (data.paypal || {}) as Record<string, any>
127
98
 
128
- const { additionalSettings } = await this.resolveSettings()
129
- const paymentActionRaw =
130
- typeof additionalSettings.paymentAction === "string"
131
- ? additionalSettings.paymentAction
132
- : "capture"
133
- const returnStatus = paymentActionRaw === "authorize" ? "authorized" : "captured"
134
- const timestampKey = paymentActionRaw === "authorize" ? "authorized_at" : "captured_at"
135
-
136
- if (
137
- existingPayPal.capture_id ||
138
- existingPayPal.authorization_id ||
139
- (data as any).authorized_at ||
140
- (data as any).captured_at
141
- ) {
142
- console.info("[PayPal] authorizePayment: session already processed, returning", returnStatus)
99
+ // Session already carries a settled capture: trust it without a network
100
+ // round-trip. The stored capture object is only written after a COMPLETED
101
+ // gate (capture-order route / capturePayment), but re-verify its status
102
+ // here so a PENDING/DECLINED capture patched in by a webhook is never
103
+ // booked as captured money.
104
+ const storedCaptureStatus = extractCaptureStatus(existingPayPal.capture)
105
+ if (storedCaptureStatus === "COMPLETED") {
106
+ console.info("[PayPal] authorizePayment: session already captured (COMPLETED)")
143
107
  return {
144
- status: returnStatus,
108
+ status: "captured",
145
109
  data: {
146
110
  ...(input.data || {}),
147
- [timestampKey]: (data as any)[timestampKey] || new Date().toISOString(),
111
+ captured_at: (data as any).captured_at || new Date().toISOString(),
148
112
  },
149
113
  }
150
114
  }
@@ -157,25 +121,92 @@ class PayPalPaymentProvider extends PayPalProviderBase {
157
121
  const capture = order?.purchase_units?.[0]?.payments?.captures?.[0]
158
122
  const authorization = order?.purchase_units?.[0]?.payments?.authorizations?.[0]
159
123
 
160
- if (capture?.id || authorization?.id) {
161
- console.info("[PayPal] authorizePayment: order already processed by PayPal, returning", returnStatus)
162
- return {
163
- status: returnStatus,
164
- data: {
165
- ...(input.data || {}),
166
- paypal: {
167
- ...existingPayPal,
168
- order_id: orderId,
169
- order,
170
- authorization_id: authorization?.id || existingPayPal.authorization_id,
171
- capture_id: capture?.id || existingPayPal.capture_id,
124
+ // Derive the returned status from what actually happened at PayPal —
125
+ // NOT from the mere presence of a capture/authorization id and NOT
126
+ // from the merchant's configured paymentAction. A PENDING capture
127
+ // (eCheck / pending review) must not be booked as captured, and a
128
+ // DENIED/DECLINED one must fail the authorization outright.
129
+ if (capture?.id) {
130
+ const captureStatus = this.mapCaptureStatus(capture?.status)
131
+ if (captureStatus === "captured") {
132
+ return {
133
+ status: "captured",
134
+ data: {
135
+ ...(input.data || {}),
136
+ paypal: {
137
+ ...existingPayPal,
138
+ order_id: orderId,
139
+ order,
140
+ authorization_id: authorization?.id || existingPayPal.authorization_id,
141
+ capture_id: capture.id,
142
+ capture,
143
+ },
144
+ captured_at: new Date().toISOString(),
172
145
  },
173
- [timestampKey]: new Date().toISOString(),
174
- },
146
+ }
147
+ }
148
+ if (captureStatus === "pending") {
149
+ // Funds are in flight (eCheck etc.): place the order as authorized
150
+ // so checkout completes, but never mark it captured — the
151
+ // CAPTURE.COMPLETED webhook settles it later.
152
+ return {
153
+ status: "authorized",
154
+ data: {
155
+ ...(input.data || {}),
156
+ paypal: {
157
+ ...existingPayPal,
158
+ order_id: orderId,
159
+ order,
160
+ capture_id: capture.id,
161
+ },
162
+ authorized_at: new Date().toISOString(),
163
+ },
164
+ }
165
+ }
166
+ if (captureStatus === "error" || captureStatus === "canceled") {
167
+ return {
168
+ status: "error",
169
+ data: {
170
+ ...(input.data || {}),
171
+ paypal: { ...existingPayPal, order_id: orderId, order },
172
+ },
173
+ }
174
+ }
175
+ }
176
+
177
+ if (authorization?.id) {
178
+ const authStatus = this.mapAuthorizationStatus(authorization?.status)
179
+ if (authStatus === "authorized") {
180
+ return {
181
+ status: "authorized",
182
+ data: {
183
+ ...(input.data || {}),
184
+ paypal: {
185
+ ...existingPayPal,
186
+ order_id: orderId,
187
+ order,
188
+ authorization_id: authorization.id,
189
+ },
190
+ authorized_at: new Date().toISOString(),
191
+ },
192
+ }
193
+ }
194
+ if (authStatus === "error" || authStatus === "canceled") {
195
+ return {
196
+ status: "error",
197
+ data: {
198
+ ...(input.data || {}),
199
+ paypal: { ...existingPayPal, order_id: orderId, order },
200
+ },
201
+ }
175
202
  }
176
203
  }
177
204
 
178
- if (["APPROVED", "CREATED", "SAVED"].includes(String(order?.status || "").toUpperCase())) {
205
+ // Only a buyer-APPROVED order counts as authorized. CREATED/SAVED
206
+ // means the buyer never approved the payment — treating those as
207
+ // authorized would let a cart complete with no funds authorized at
208
+ // PayPal at all.
209
+ if (String(order?.status || "").toUpperCase() === "APPROVED") {
179
210
  console.info("[PayPal] authorizePayment: order approved, marking authorized")
180
211
  return {
181
212
  status: "authorized",
@@ -192,133 +223,49 @@ class PayPalPaymentProvider extends PayPalProviderBase {
192
223
  }
193
224
  } catch (e: any) {
194
225
  console.warn("[PayPal] authorizePayment: order lookup failed:", e?.message)
195
- }
196
- }
197
-
198
- const requestId = this.getIdempotencyKey(input, "authorize")
199
- let debugId: string | null = null
200
- const orderIntent = paymentActionRaw === "authorize" ? "AUTHORIZE" : "CAPTURE"
201
-
202
- try {
203
- const { accessToken, base } = await this.getPayPalAccessToken()
204
- const value = formatAmountForPayPal(amount, currencyCode || "EUR")
205
-
206
- const orderPayload = {
207
- intent: orderIntent,
208
- purchase_units: [
209
- {
210
- reference_id: data.cart_id || data.payment_collection_id || undefined,
211
- custom_id:
212
- data.session_id || data.cart_id || data.payment_collection_id || undefined,
213
- amount: {
214
- currency_code: currencyCode || "EUR",
215
- value,
216
- },
217
- },
218
- ],
219
- custom_id:
220
- data.session_id || data.cart_id || data.payment_collection_id || undefined,
221
- }
222
-
223
- const ppResp = await paypalFetch(`${base}/v2/checkout/orders`, {
224
- method: "POST",
225
- headers: {
226
- Authorization: `Bearer ${accessToken}`,
227
- "Content-Type": "application/json",
228
- "PayPal-Request-Id": requestId,
229
- "PayPal-Partner-Attribution-Id": PAYPAL_PARTNER_ATTRIBUTION_ID,
230
- },
231
- body: JSON.stringify(orderPayload),
232
- })
233
-
234
- const ppText = await ppResp.text()
235
- debugId = ppResp.headers.get("paypal-debug-id")
236
- if (!ppResp.ok) {
237
- throw new Error(
238
- `PayPal create order error (${ppResp.status}): ${ppText}${
239
- debugId ? ` debug_id=${debugId}` : ""
240
- }`
241
- )
242
- }
243
-
244
- const order = JSON.parse(ppText) as Record<string, any>
245
- const newOrderId = String(order.id || "")
246
-
247
- if (!order || !newOrderId) {
248
- throw new Error("Unable to resolve PayPal order details for authorization.")
249
- }
250
-
251
- const existingAuthorization =
252
- order?.purchase_units?.[0]?.payments?.authorizations?.[0] || null
253
-
254
- let authorization: any = null
255
- if (existingAuthorization) {
256
- authorization = order
257
- } else {
258
- const authorizeResp = await paypalFetch(
259
- `${base}/v2/checkout/orders/${encodeURIComponent(newOrderId)}/authorize`,
260
- {
261
- method: "POST",
262
- headers: {
263
- Authorization: `Bearer ${accessToken}`,
264
- "Content-Type": "application/json",
265
- "PayPal-Request-Id": `${requestId}-auth`,
266
- "PayPal-Partner-Attribution-Id": PAYPAL_PARTNER_ATTRIBUTION_ID,
226
+ // Fall back to the session's own record when PayPal is unreachable so a
227
+ // transient lookup error doesn't fail a checkout that already has a
228
+ // real authorization/capture behind it. `captured_at` is only ever
229
+ // stamped after a COMPLETED gate; a bare capture_id (e.g. patched in by
230
+ // a webhook) or authorization id maps to "authorized" — the order is
231
+ // placed without claiming settled funds.
232
+ if ((data as any).captured_at) {
233
+ return {
234
+ status: "captured",
235
+ data: { ...(input.data || {}), captured_at: (data as any).captured_at },
236
+ }
237
+ }
238
+ if (
239
+ existingPayPal.capture_id ||
240
+ existingPayPal.authorization_id ||
241
+ (data as any).authorized_at
242
+ ) {
243
+ return {
244
+ status: "authorized",
245
+ data: {
246
+ ...(input.data || {}),
247
+ authorized_at: (data as any).authorized_at || new Date().toISOString(),
267
248
  },
268
249
  }
269
- )
270
-
271
- const authorizeText = await authorizeResp.text()
272
- const authorizeDebugId = authorizeResp.headers.get("paypal-debug-id")
273
- if (!authorizeResp.ok) {
274
- throw new Error(
275
- `PayPal authorize order error (${authorizeResp.status}): ${authorizeText}${
276
- authorizeDebugId ? ` debug_id=${authorizeDebugId}` : ""
277
- }`
278
- )
279
250
  }
280
-
281
- authorization = JSON.parse(authorizeText)
282
251
  }
283
-
284
- const authorizationId =
285
- authorization?.purchase_units?.[0]?.payments?.authorizations?.[0]?.id ||
286
- existingAuthorization?.id
287
-
288
- await this.recordSuccess("authorize_success")
289
- await this.recordPaymentEvent("authorize", {
290
- order_id: newOrderId,
291
- authorization_id: authorizationId,
292
- amount,
293
- currency_code: currencyCode,
294
- request_id: requestId,
295
- })
296
-
297
- return {
298
- status: "authorized",
299
- data: {
300
- ...(input.data || {}),
301
- paypal: {
302
- ...((input.data || {}).paypal as Record<string, unknown>),
303
- order_id: newOrderId,
304
- order: order || authorization,
305
- authorization_id: authorizationId,
306
- authorizations:
307
- authorization?.purchase_units?.[0]?.payments?.authorizations || [],
308
- },
309
- authorized_at: new Date().toISOString(),
310
- },
311
- }
312
- } catch (error: any) {
313
- await this.recordFailure("authorize_failed", {
314
- request_id: requestId,
315
- cart_id: data.cart_id,
316
- payment_collection_id: data.payment_collection_id,
317
- debug_id: debugId,
318
- message: error?.message,
319
- })
320
- throw error
321
252
  }
253
+
254
+ // No usable PayPal order on the session: nothing can be authorized. The
255
+ // previous fallback created a brand-new PayPal order here and immediately
256
+ // called /v2/checkout/orders/{id}/authorize on it — but an order no buyer
257
+ // has approved can never be authorized (PayPal rejects it with
258
+ // ORDER_NOT_APPROVED), so that path only produced confusing 422s and
259
+ // orphaned PayPal orders. Fail with a clear, actionable error instead.
260
+ await this.recordFailure("authorize_failed", {
261
+ cart_id: data.cart_id,
262
+ payment_collection_id: data.payment_collection_id,
263
+ message: "no approved PayPal order on session",
264
+ })
265
+ throw new MedusaError(
266
+ MedusaError.Types.NOT_ALLOWED,
267
+ "No approved PayPal payment was found for this session. The buyer must approve the payment with PayPal before the cart can be completed."
268
+ )
322
269
  }
323
270
 
324
271
  async retrievePayment(input: RetrievePaymentInput): Promise<RetrievePaymentOutput> {
@@ -411,7 +358,11 @@ class PayPalPaymentProvider extends PayPalProviderBase {
411
358
  }
412
359
  }
413
360
 
414
- const { amount, currencyCode } = await this.normalizePaymentData(input)
361
+ const { amount: sessionAmount, currencyCode } = await this.normalizePaymentData(input)
362
+ // The requested (possibly partial) capture amount lives on the Medusa
363
+ // capture row, not in the provider input — resolve it so partial captures
364
+ // don't charge the full session total.
365
+ const amount = await this.resolveRequestedCaptureAmount(input, sessionAmount)
415
366
  // Include the amount in the idempotency suffix: PayPal deduplicates by
416
367
  // PayPal-Request-Id, so two sequential partial captures of the same order
417
368
  // that share an upstream idempotency_key would otherwise collide and the
@@ -817,6 +768,18 @@ class PayPalPaymentProvider extends PayPalProviderBase {
817
768
  }
818
769
 
819
770
  const refund = await resp.json().catch(() => ({}))
771
+
772
+ // As with refundPayment: a 2xx response does not guarantee the refund
773
+ // stuck — FAILED / CANCELLED / DENIED refunds also return 2xx. Booking
774
+ // `canceled_at` for a refund that never went through would record a
775
+ // cancellation while the merchant keeps the funds.
776
+ const cancelRefundStatus = String(refund?.status || "").toUpperCase()
777
+ if (isRefundFailureStatus(cancelRefundStatus)) {
778
+ throw new Error(
779
+ `PayPal cancel-refund did not succeed (status=${cancelRefundStatus}). The payment was not canceled.`
780
+ )
781
+ }
782
+
820
783
  const existingRefunds = Array.isArray(paypalData.refunds) ? paypalData.refunds : []
821
784
  const refundEntry = {
822
785
  id: refund?.id,