@easypayment/medusa-payment-paypal 1.1.0 → 1.1.2

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 (65) hide show
  1. package/.medusa/server/src/admin/index.js +73 -73
  2. package/.medusa/server/src/admin/index.mjs +73 -73
  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 +9 -0
  13. package/.medusa/server/src/api/middlewares.js.map +1 -1
  14. package/.medusa/server/src/api/store/paypal/config/route.d.ts.map +1 -1
  15. package/.medusa/server/src/api/store/paypal/config/route.js +8 -0
  16. package/.medusa/server/src/api/store/paypal/config/route.js.map +1 -1
  17. package/.medusa/server/src/api/store/paypal/create-order/route.d.ts.map +1 -1
  18. package/.medusa/server/src/api/store/paypal/create-order/route.js +53 -4
  19. package/.medusa/server/src/api/store/paypal/create-order/route.js.map +1 -1
  20. package/.medusa/server/src/api/store/paypal-complete/route.js +1 -1
  21. package/.medusa/server/src/api/store/paypal-complete/route.js.map +1 -1
  22. package/.medusa/server/src/api/utils/rate-limit.d.ts.map +1 -1
  23. package/.medusa/server/src/api/utils/rate-limit.js +11 -2
  24. package/.medusa/server/src/api/utils/rate-limit.js.map +1 -1
  25. package/.medusa/server/src/modules/paypal/payment-provider/base-provider.d.ts +32 -3
  26. package/.medusa/server/src/modules/paypal/payment-provider/base-provider.d.ts.map +1 -1
  27. package/.medusa/server/src/modules/paypal/payment-provider/base-provider.js +47 -0
  28. package/.medusa/server/src/modules/paypal/payment-provider/base-provider.js.map +1 -1
  29. package/.medusa/server/src/modules/paypal/payment-provider/card-service.d.ts.map +1 -1
  30. package/.medusa/server/src/modules/paypal/payment-provider/card-service.js +172 -117
  31. package/.medusa/server/src/modules/paypal/payment-provider/card-service.js.map +1 -1
  32. package/.medusa/server/src/modules/paypal/payment-provider/service.d.ts.map +1 -1
  33. package/.medusa/server/src/modules/paypal/payment-provider/service.js +132 -126
  34. package/.medusa/server/src/modules/paypal/payment-provider/service.js.map +1 -1
  35. package/.medusa/server/src/modules/paypal/service.d.ts +5 -0
  36. package/.medusa/server/src/modules/paypal/service.d.ts.map +1 -1
  37. package/.medusa/server/src/modules/paypal/service.js +82 -1
  38. package/.medusa/server/src/modules/paypal/service.js.map +1 -1
  39. package/.medusa/server/src/modules/paypal/utils/credential-resolver.d.ts +10 -0
  40. package/.medusa/server/src/modules/paypal/utils/credential-resolver.d.ts.map +1 -1
  41. package/.medusa/server/src/modules/paypal/utils/credential-resolver.js +39 -0
  42. package/.medusa/server/src/modules/paypal/utils/credential-resolver.js.map +1 -1
  43. package/.medusa/server/src/modules/paypal/utils/paypal-fetch.d.ts.map +1 -1
  44. package/.medusa/server/src/modules/paypal/utils/paypal-fetch.js +45 -28
  45. package/.medusa/server/src/modules/paypal/utils/paypal-fetch.js.map +1 -1
  46. package/.medusa/server/src/modules/paypal/webhook-processor.d.ts +11 -0
  47. package/.medusa/server/src/modules/paypal/webhook-processor.d.ts.map +1 -1
  48. package/.medusa/server/src/modules/paypal/webhook-processor.js +85 -7
  49. package/.medusa/server/src/modules/paypal/webhook-processor.js.map +1 -1
  50. package/CHANGELOG.md +73 -0
  51. package/package.json +4 -5
  52. package/src/api/hooks/paypal/onboard-return/route.ts +15 -0
  53. package/src/api/hooks/paypal/webhook/route.ts +17 -0
  54. package/src/api/middlewares.ts +9 -0
  55. package/src/api/store/paypal/config/route.ts +8 -0
  56. package/src/api/store/paypal/create-order/route.ts +64 -4
  57. package/src/api/store/paypal-complete/route.ts +1 -1
  58. package/src/api/utils/rate-limit.ts +11 -2
  59. package/src/modules/paypal/payment-provider/base-provider.ts +52 -0
  60. package/src/modules/paypal/payment-provider/card-service.ts +193 -136
  61. package/src/modules/paypal/payment-provider/service.ts +137 -156
  62. package/src/modules/paypal/service.ts +98 -1
  63. package/src/modules/paypal/utils/credential-resolver.ts +36 -0
  64. package/src/modules/paypal/utils/paypal-fetch.ts +58 -29
  65. package/src/modules/paypal/webhook-processor.ts +94 -8
@@ -70,6 +70,7 @@ class PayPalAdvancedCardProvider extends PayPalProviderBase {
70
70
  return {
71
71
  data: {
72
72
  ...(input.data || {}),
73
+ ...this.invalidateStaleOrder(input, currencyCode),
73
74
  amount: input.amount,
74
75
  currency_code: currencyCode,
75
76
  },
@@ -77,27 +78,9 @@ class PayPalAdvancedCardProvider extends PayPalProviderBase {
77
78
  }
78
79
 
79
80
  async authorizePayment(_input: AuthorizePaymentInput): Promise<AuthorizePaymentOutput> {
80
- const { data, amount, currencyCode } = await this.normalizePaymentData(_input)
81
+ const { data } = await this.normalizePaymentData(_input)
81
82
  const requestId = this.getIdempotencyKey(_input, "authorize")
82
- let debugId: string | null = null
83
- const { additionalSettings, advancedCardSettings } = await this.resolveSettings()
84
- const paymentActionRaw =
85
- typeof additionalSettings.paymentAction === "string"
86
- ? additionalSettings.paymentAction
87
- : "capture"
88
- const orderIntent = paymentActionRaw === "authorize" ? "AUTHORIZE" : "CAPTURE"
89
- const returnStatus = paymentActionRaw === "authorize" ? "authorized" : "captured"
90
- const timestampKey = paymentActionRaw === "authorize" ? "authorized_at" : "captured_at"
91
- const threeDsRaw =
92
- typeof advancedCardSettings.threeDS === "string"
93
- ? advancedCardSettings.threeDS
94
- : "when_required"
95
- const threeDsMethod =
96
- threeDsRaw === "always"
97
- ? "SCA_ALWAYS"
98
- : threeDsRaw === "when_required" || threeDsRaw === "sli"
99
- ? "SCA_WHEN_REQUIRED"
100
- : null
83
+ const { advancedCardSettings } = await this.resolveSettings()
101
84
  const disabledCards = Array.isArray(advancedCardSettings.disabledCards)
102
85
  ? advancedCardSettings.disabledCards.map((card: string) => String(card).toLowerCase())
103
86
  : []
@@ -110,151 +93,221 @@ class PayPalAdvancedCardProvider extends PayPalProviderBase {
110
93
 
111
94
  const existingPayPal = (data.paypal || {}) as Record<string, any>
112
95
 
113
- if (
114
- existingPayPal.capture_id ||
115
- existingPayPal.authorization_id ||
116
- (data as any).authorized_at ||
117
- (data as any).captured_at
118
- ) {
96
+ // Session already carries a settled capture: trust it without a network
97
+ // round-trip, but only when the stored capture is actually COMPLETED — a
98
+ // PENDING/DECLINED capture must never be booked as captured money.
99
+ const storedCaptureStatus = extractCaptureStatus(existingPayPal.capture)
100
+ if (storedCaptureStatus === "COMPLETED") {
119
101
  return {
120
- status: returnStatus,
102
+ status: "captured",
121
103
  data: {
122
104
  ...(_input.data || {}),
123
- [timestampKey]: (data as any)[timestampKey] || new Date().toISOString(),
105
+ captured_at: (data as any).captured_at || new Date().toISOString(),
124
106
  },
125
107
  }
126
108
  }
127
109
 
128
- const { accessToken, base } = await this.getPayPalAccessToken()
129
- let orderId = String(existingPayPal.order_id || data.order_id || "")
130
- let order: Record<string, any> | null = null
131
- let authorization: Record<string, any> | null = null
132
-
110
+ const orderId = String(existingPayPal.order_id || data.order_id || "")
133
111
  if (!orderId) {
134
- const value = formatAmountForPayPal(amount, currencyCode || "EUR")
135
- const orderPayload = {
136
- intent: orderIntent,
137
- purchase_units: [
138
- {
139
- reference_id: data.cart_id || data.payment_collection_id || undefined,
140
- custom_id: data.session_id || data.cart_id || data.payment_collection_id || undefined,
141
- amount: {
142
- currency_code: currencyCode || "EUR",
143
- value,
144
- },
112
+ // Nothing to authorize: a PayPal order only exists after the buyer
113
+ // submitted their card via the storefront (create-order + card fields).
114
+ // The previous fallback created a fresh order here and immediately
115
+ // called /authorize on it, which PayPal always rejects (no payment
116
+ // source, and 422 UNSUPPORTED_INTENT for CAPTURE-intent orders).
117
+ throw new MedusaError(
118
+ MedusaError.Types.NOT_ALLOWED,
119
+ "No PayPal order was found for this payment session. The buyer must submit and approve their card payment before the cart can be completed."
120
+ )
121
+ }
122
+
123
+ let order: Record<string, any> | null = null
124
+ try {
125
+ order = (await this.getOrderDetails(orderId)) as Record<string, any> | null
126
+ } catch (e: any) {
127
+ console.warn("[PayPal] card authorizePayment: order lookup failed:", e?.message)
128
+ // Fall back to the session's own record on a transient lookup failure so
129
+ // checkout isn't blocked when a real authorization/capture exists.
130
+ if ((data as any).captured_at) {
131
+ return {
132
+ status: "captured",
133
+ data: { ...(_input.data || {}), captured_at: (data as any).captured_at },
134
+ }
135
+ }
136
+ if (
137
+ existingPayPal.capture_id ||
138
+ existingPayPal.authorization_id ||
139
+ (data as any).authorized_at
140
+ ) {
141
+ return {
142
+ status: "authorized",
143
+ data: {
144
+ ...(_input.data || {}),
145
+ authorized_at: (data as any).authorized_at || new Date().toISOString(),
145
146
  },
146
- ],
147
- custom_id: data.session_id || data.cart_id || data.payment_collection_id || undefined,
148
- ...(threeDsMethod
149
- ? {
150
- payment_source: {
151
- card: {
152
- attributes: {
153
- verification: {
154
- method: threeDsMethod,
155
- },
156
- },
157
- },
158
- },
159
- }
160
- : {}),
147
+ }
161
148
  }
149
+ throw e
150
+ }
162
151
 
163
- const ppResp = await paypalFetch(`${base}/v2/checkout/orders`, {
164
- method: "POST",
165
- headers: {
166
- Authorization: `Bearer ${accessToken}`,
167
- "Content-Type": "application/json",
168
- "PayPal-Request-Id": requestId,
169
- "PayPal-Partner-Attribution-Id": PAYPAL_PARTNER_ATTRIBUTION_ID,
170
- },
171
- body: JSON.stringify(orderPayload),
172
- })
152
+ if (!order) {
153
+ throw new Error("Unable to resolve PayPal order details for authorization.")
154
+ }
173
155
 
174
- const ppText = await ppResp.text()
175
- debugId = ppResp.headers.get("paypal-debug-id")
176
- if (!ppResp.ok) {
177
- throw new Error(
178
- `PayPal create order error (${ppResp.status}): ${ppText}${
179
- debugId ? ` debug_id=${debugId}` : ""
180
- }`
181
- )
182
- }
156
+ const capture = order?.purchase_units?.[0]?.payments?.captures?.[0]
157
+ const authorization = order?.purchase_units?.[0]?.payments?.authorizations?.[0]
183
158
 
184
- order = JSON.parse(ppText) as Record<string, any>
185
- orderId = String(order.id || "")
186
- } else {
187
- order = (await this.getOrderDetails(orderId)) as Record<string, any> | null
159
+ // Derive the status from what actually happened at PayPal, never from the
160
+ // mere presence of a capture/authorization or from the configured
161
+ // paymentAction: a PENDING (eCheck) capture is not settled money and a
162
+ // DENIED/DECLINED one must fail the authorization.
163
+ if (capture?.id) {
164
+ const captureStatus = this.mapCaptureStatus(capture?.status)
165
+ if (captureStatus === "captured") {
166
+ return {
167
+ status: "captured",
168
+ data: {
169
+ ...(data || {}),
170
+ paypal: {
171
+ ...existingPayPal,
172
+ order_id: orderId,
173
+ order,
174
+ capture_id: capture.id,
175
+ capture,
176
+ },
177
+ captured_at: new Date().toISOString(),
178
+ },
179
+ }
180
+ }
181
+ if (captureStatus === "pending") {
182
+ return {
183
+ status: "authorized",
184
+ data: {
185
+ ...(data || {}),
186
+ paypal: {
187
+ ...existingPayPal,
188
+ order_id: orderId,
189
+ order,
190
+ capture_id: capture.id,
191
+ },
192
+ authorized_at: new Date().toISOString(),
193
+ },
194
+ }
195
+ }
196
+ if (captureStatus === "error" || captureStatus === "canceled") {
197
+ return {
198
+ status: "error",
199
+ data: {
200
+ ...(data || {}),
201
+ paypal: { ...existingPayPal, order_id: orderId, order },
202
+ },
203
+ }
204
+ }
188
205
  }
189
206
 
190
- if (!order || !orderId) {
191
- throw new Error("Unable to resolve PayPal order details for authorization.")
207
+ if (authorization?.id) {
208
+ const authStatus = this.mapAuthorizationStatus(authorization?.status)
209
+ if (authStatus === "authorized") {
210
+ return {
211
+ status: "authorized",
212
+ data: {
213
+ ...(data || {}),
214
+ paypal: {
215
+ ...existingPayPal,
216
+ order_id: orderId,
217
+ order,
218
+ authorization_id: authorization.id,
219
+ authorizations:
220
+ order?.purchase_units?.[0]?.payments?.authorizations || [],
221
+ },
222
+ authorized_at: new Date().toISOString(),
223
+ },
224
+ }
225
+ }
226
+ if (authStatus === "error" || authStatus === "canceled") {
227
+ return {
228
+ status: "error",
229
+ data: {
230
+ ...(data || {}),
231
+ paypal: { ...existingPayPal, order_id: orderId, order },
232
+ },
233
+ }
234
+ }
192
235
  }
193
236
 
194
- const existingAuthorization =
195
- order?.purchase_units?.[0]?.payments?.authorizations?.[0] || null
196
- const existingCapture =
197
- order?.purchase_units?.[0]?.payments?.captures?.[0] || null
237
+ const orderStatus = String(order?.status || "").toUpperCase()
238
+ const orderIntent = String(order?.intent || "").toUpperCase()
198
239
 
199
- if (existingAuthorization) {
200
- authorization = order
201
- } else if (existingCapture) {
240
+ if (orderStatus === "APPROVED") {
241
+ if (orderIntent === "AUTHORIZE") {
242
+ // Approved AUTHORIZE-intent order with no authorization yet: create it.
243
+ const { accessToken, base } = await this.getPayPalAccessToken()
244
+ const authorizeResp = await paypalFetch(
245
+ `${base}/v2/checkout/orders/${encodeURIComponent(orderId)}/authorize`,
246
+ {
247
+ method: "POST",
248
+ headers: {
249
+ Authorization: `Bearer ${accessToken}`,
250
+ "Content-Type": "application/json",
251
+ "PayPal-Request-Id": `${requestId}-auth`,
252
+ "PayPal-Partner-Attribution-Id": PAYPAL_PARTNER_ATTRIBUTION_ID,
253
+ },
254
+ }
255
+ )
256
+ const authorizeText = await authorizeResp.text()
257
+ const authorizeDebugId = authorizeResp.headers.get("paypal-debug-id")
258
+ if (!authorizeResp.ok) {
259
+ throw new Error(
260
+ `PayPal authorize order error (${authorizeResp.status}): ${authorizeText}${
261
+ authorizeDebugId ? ` debug_id=${authorizeDebugId}` : ""
262
+ }`
263
+ )
264
+ }
265
+ const authorized = JSON.parse(authorizeText) as Record<string, any>
266
+ const authorizationId =
267
+ authorized?.purchase_units?.[0]?.payments?.authorizations?.[0]?.id
268
+ return {
269
+ status: "authorized",
270
+ data: {
271
+ ...(data || {}),
272
+ paypal: {
273
+ ...existingPayPal,
274
+ order_id: orderId,
275
+ order: authorized || order,
276
+ authorization_id: authorizationId,
277
+ authorizations:
278
+ authorized?.purchase_units?.[0]?.payments?.authorizations || [],
279
+ },
280
+ authorized_at: new Date().toISOString(),
281
+ },
282
+ }
283
+ }
284
+
285
+ // Approved CAPTURE-intent order: the buyer approved but the capture has
286
+ // not happened yet (e.g. the storefront capture call failed). Report
287
+ // "authorized" so the order can complete; capturePayment then routes the
288
+ // actual capture by intent. Calling /authorize here — as the previous
289
+ // code did for every intent — always fails with 422 UNSUPPORTED_INTENT
290
+ // and permanently stuck the checkout.
202
291
  return {
203
- status: returnStatus,
292
+ status: "authorized",
204
293
  data: {
205
294
  ...(data || {}),
206
295
  paypal: {
207
296
  ...existingPayPal,
208
297
  order_id: orderId,
209
298
  order,
210
- capture_id: existingCapture.id,
211
- capture: existingCapture,
212
299
  },
213
- [timestampKey]: new Date().toISOString(),
214
- },
215
- }
216
- } else {
217
- const authorizeResp = await paypalFetch(`${base}/v2/checkout/orders/${encodeURIComponent(orderId)}/authorize`, {
218
- method: "POST",
219
- headers: {
220
- Authorization: `Bearer ${accessToken}`,
221
- "Content-Type": "application/json",
222
- "PayPal-Request-Id": `${requestId}-auth`,
223
- "PayPal-Partner-Attribution-Id": PAYPAL_PARTNER_ATTRIBUTION_ID,
300
+ authorized_at: new Date().toISOString(),
224
301
  },
225
- })
226
-
227
- const authorizeText = await authorizeResp.text()
228
- const authorizeDebugId = authorizeResp.headers.get("paypal-debug-id")
229
- if (!authorizeResp.ok) {
230
- throw new Error(
231
- `PayPal authorize order error (${authorizeResp.status}): ${authorizeText}${
232
- authorizeDebugId ? ` debug_id=${authorizeDebugId}` : ""
233
- }`
234
- )
235
302
  }
236
-
237
- authorization = JSON.parse(authorizeText)
238
303
  }
239
304
 
240
- const authorizationId =
241
- authorization?.purchase_units?.[0]?.payments?.authorizations?.[0]?.id ||
242
- existingAuthorization?.id
243
-
244
- return {
245
- status: "authorized",
246
- data: {
247
- ...(data || {}),
248
- paypal: {
249
- ...existingPayPal,
250
- order_id: orderId,
251
- order: order || authorization,
252
- authorization_id: authorizationId,
253
- authorizations: authorization?.purchase_units?.[0]?.payments?.authorizations || [],
254
- },
255
- authorized_at: new Date().toISOString(),
256
- },
257
- }
305
+ // CREATED / SAVED / PAYER_ACTION_REQUIRED etc.: the buyer never approved
306
+ // the payment — nothing is authorized at PayPal.
307
+ throw new MedusaError(
308
+ MedusaError.Types.NOT_ALLOWED,
309
+ `PayPal order ${orderId} has not been approved by the buyer (status ${orderStatus || "UNKNOWN"}). The payment cannot be authorized.`
310
+ )
258
311
  }
259
312
 
260
313
  async capturePayment(_input: CapturePaymentInput): Promise<CapturePaymentOutput> {
@@ -280,7 +333,11 @@ class PayPalAdvancedCardProvider extends PayPalProviderBase {
280
333
  }
281
334
  }
282
335
 
283
- const { amount, currencyCode } = await this.normalizePaymentData(_input)
336
+ const { amount: sessionAmount, currencyCode } = await this.normalizePaymentData(_input)
337
+ // The requested (possibly partial) capture amount lives on the Medusa
338
+ // capture row, not in the provider input — resolve it so partial captures
339
+ // don't charge the full session total.
340
+ const amount = await this.resolveRequestedCaptureAmount(_input, sessionAmount)
284
341
  // Include the amount in the idempotency suffix: PayPal deduplicates by
285
342
  // PayPal-Request-Id, so two sequential partial captures of the same order
286
343
  // that share an upstream idempotency_key would otherwise collide and the