@easypayment/medusa-payment-paypal 1.0.1 → 1.1.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 (84) hide show
  1. package/.medusa/server/src/api/admin/paypal/onboard-complete/route.d.ts +2 -2
  2. package/.medusa/server/src/api/admin/paypal/onboard-complete/route.d.ts.map +1 -1
  3. package/.medusa/server/src/api/admin/paypal/onboard-complete/route.js +4 -0
  4. package/.medusa/server/src/api/admin/paypal/onboard-complete/route.js.map +1 -1
  5. package/.medusa/server/src/api/middlewares.d.ts.map +1 -1
  6. package/.medusa/server/src/api/middlewares.js +16 -1
  7. package/.medusa/server/src/api/middlewares.js.map +1 -1
  8. package/.medusa/server/src/api/store/paypal/capture-order/route.d.ts.map +1 -1
  9. package/.medusa/server/src/api/store/paypal/capture-order/route.js +45 -16
  10. package/.medusa/server/src/api/store/paypal/capture-order/route.js.map +1 -1
  11. package/.medusa/server/src/api/store/paypal/config/route.d.ts.map +1 -1
  12. package/.medusa/server/src/api/store/paypal/config/route.js +7 -1
  13. package/.medusa/server/src/api/store/paypal/config/route.js.map +1 -1
  14. package/.medusa/server/src/api/store/paypal/onboard-return/route.d.ts.map +1 -1
  15. package/.medusa/server/src/api/store/paypal/onboard-return/route.js +24 -2
  16. package/.medusa/server/src/api/store/paypal/onboard-return/route.js.map +1 -1
  17. package/.medusa/server/src/api/store/paypal/webhook/route.d.ts.map +1 -1
  18. package/.medusa/server/src/api/store/paypal/webhook/route.js +22 -48
  19. package/.medusa/server/src/api/store/paypal/webhook/route.js.map +1 -1
  20. package/.medusa/server/src/api/utils/rate-limit.d.ts +3 -0
  21. package/.medusa/server/src/api/utils/rate-limit.d.ts.map +1 -0
  22. package/.medusa/server/src/api/utils/rate-limit.js +92 -0
  23. package/.medusa/server/src/api/utils/rate-limit.js.map +1 -0
  24. package/.medusa/server/src/jobs/paypal-webhook-retry.d.ts.map +1 -1
  25. package/.medusa/server/src/jobs/paypal-webhook-retry.js +115 -90
  26. package/.medusa/server/src/jobs/paypal-webhook-retry.js.map +1 -1
  27. package/.medusa/server/src/modules/paypal/payment-provider/base-provider.d.ts +48 -0
  28. package/.medusa/server/src/modules/paypal/payment-provider/base-provider.d.ts.map +1 -0
  29. package/.medusa/server/src/modules/paypal/payment-provider/base-provider.js +159 -0
  30. package/.medusa/server/src/modules/paypal/payment-provider/base-provider.js.map +1 -0
  31. package/.medusa/server/src/modules/paypal/payment-provider/card-service.d.ts +5 -20
  32. package/.medusa/server/src/modules/paypal/payment-provider/card-service.d.ts.map +1 -1
  33. package/.medusa/server/src/modules/paypal/payment-provider/card-service.js +27 -160
  34. package/.medusa/server/src/modules/paypal/payment-provider/card-service.js.map +1 -1
  35. package/.medusa/server/src/modules/paypal/payment-provider/service.d.ts +5 -20
  36. package/.medusa/server/src/modules/paypal/payment-provider/service.d.ts.map +1 -1
  37. package/.medusa/server/src/modules/paypal/payment-provider/service.js +21 -138
  38. package/.medusa/server/src/modules/paypal/payment-provider/service.js.map +1 -1
  39. package/.medusa/server/src/modules/paypal/utils/amounts.d.ts.map +1 -1
  40. package/.medusa/server/src/modules/paypal/utils/amounts.js +10 -0
  41. package/.medusa/server/src/modules/paypal/utils/amounts.js.map +1 -1
  42. package/.medusa/server/src/modules/paypal/utils/credential-resolver.d.ts +1 -1
  43. package/.medusa/server/src/modules/paypal/utils/credential-resolver.d.ts.map +1 -1
  44. package/.medusa/server/src/modules/paypal/utils/credential-resolver.js +27 -26
  45. package/.medusa/server/src/modules/paypal/utils/credential-resolver.js.map +1 -1
  46. package/.medusa/server/src/modules/paypal/utils/partner.d.ts +9 -0
  47. package/.medusa/server/src/modules/paypal/utils/partner.d.ts.map +1 -0
  48. package/.medusa/server/src/modules/paypal/utils/partner.js +12 -0
  49. package/.medusa/server/src/modules/paypal/utils/partner.js.map +1 -0
  50. package/.medusa/server/src/modules/paypal/utils/payment-session.d.ts +0 -5
  51. package/.medusa/server/src/modules/paypal/utils/payment-session.d.ts.map +1 -1
  52. package/.medusa/server/src/modules/paypal/utils/payment-session.js +37 -18
  53. package/.medusa/server/src/modules/paypal/utils/payment-session.js.map +1 -1
  54. package/.medusa/server/src/modules/paypal/utils/secret-crypto.d.ts.map +1 -1
  55. package/.medusa/server/src/modules/paypal/utils/secret-crypto.js +30 -1
  56. package/.medusa/server/src/modules/paypal/utils/secret-crypto.js.map +1 -1
  57. package/.medusa/server/src/subscribers/paypal-webhook-process.d.ts +19 -0
  58. package/.medusa/server/src/subscribers/paypal-webhook-process.d.ts.map +1 -0
  59. package/.medusa/server/src/subscribers/paypal-webhook-process.js +107 -0
  60. package/.medusa/server/src/subscribers/paypal-webhook-process.js.map +1 -0
  61. package/CHANGELOG.md +73 -0
  62. package/package.json +2 -1
  63. package/src/api/admin/paypal/onboard-complete/route.ts +10 -2
  64. package/src/api/middlewares.ts +16 -1
  65. package/src/api/store/paypal/capture-order/route.ts +60 -22
  66. package/src/api/store/paypal/config/route.ts +8 -1
  67. package/src/api/store/paypal/onboard-return/route.ts +31 -6
  68. package/src/api/store/paypal/webhook/route.ts +24 -60
  69. package/src/api/utils/rate-limit.ts +105 -0
  70. package/src/jobs/paypal-webhook-retry.ts +132 -94
  71. package/src/modules/paypal/payment-provider/base-provider.ts +192 -0
  72. package/src/modules/paypal/payment-provider/card-service.ts +28 -196
  73. package/src/modules/paypal/payment-provider/service.ts +23 -164
  74. package/src/modules/paypal/utils/amounts.ts +10 -0
  75. package/src/modules/paypal/utils/credential-resolver.ts +32 -27
  76. package/src/modules/paypal/utils/partner.ts +8 -0
  77. package/src/modules/paypal/utils/payment-session.ts +44 -19
  78. package/src/modules/paypal/utils/secret-crypto.ts +36 -1
  79. package/src/subscribers/paypal-webhook-process.ts +127 -0
  80. package/.medusa/server/src/modules/paypal/clients/paypal-seller.client.d.ts +0 -15
  81. package/.medusa/server/src/modules/paypal/clients/paypal-seller.client.d.ts.map +0 -1
  82. package/.medusa/server/src/modules/paypal/clients/paypal-seller.client.js +0 -68
  83. package/.medusa/server/src/modules/paypal/clients/paypal-seller.client.js.map +0 -1
  84. package/src/modules/paypal/clients/paypal-seller.client.ts +0 -64
@@ -0,0 +1,192 @@
1
+ import { AbstractPaymentProvider } from "@medusajs/framework/utils"
2
+ import { randomUUID } from "crypto"
3
+ import type {
4
+ CreateAccountHolderInput,
5
+ CreateAccountHolderOutput,
6
+ DeletePaymentInput,
7
+ DeletePaymentOutput,
8
+ ProviderWebhookPayload,
9
+ WebhookActionResult,
10
+ } from "@medusajs/framework/types"
11
+ import { formatAmountForPayPal, toAmountNumber } from "../utils/amounts"
12
+ import {
13
+ assertPayPalCurrencySupported,
14
+ normalizeCurrencyCode,
15
+ } from "../utils/currencies"
16
+ import { PayPalCredentialResolver } from "../utils/credential-resolver"
17
+ import { PAYPAL_PARTNER_ATTRIBUTION_ID } from "../utils/partner"
18
+ import { paypalFetch } from "../utils/paypal-fetch"
19
+ import { getPayPalWebhookActionAndData } from "./webhook-utils"
20
+ import { mapPayPalCaptureStatus } from "./status-utils"
21
+
22
+ export type Options = {}
23
+
24
+ /**
25
+ * Shared base for the two PayPal payment providers (wallet buttons and advanced
26
+ * card fields). Both providers ran nearly identical credential/token handling,
27
+ * order-detail fetching, idempotency-key generation, amount normalization, and
28
+ * PayPal→Medusa status mapping — that logic lives here once. Each provider
29
+ * supplies its own `sessionPrefix` / `idempotencyPrefix` and keeps the pieces
30
+ * that genuinely differ (create/authorize/capture/refund/cancel business logic,
31
+ * metric recording, 3-D Secure handling, provider-id passthrough).
32
+ */
33
+ export abstract class PayPalProviderBase extends AbstractPaymentProvider<Options> {
34
+ protected readonly options_: Options
35
+ protected paypal: PayPalCredentialResolver
36
+
37
+ /** Prefix for generated session ids (e.g. "pp" or "pp_card"). */
38
+ protected abstract readonly sessionPrefix: string
39
+ /** Prefix for generated idempotency keys (e.g. "pp" or "pp-card"). */
40
+ protected abstract readonly idempotencyPrefix: string
41
+
42
+ constructor(cradle: Record<string, any>, options: Options) {
43
+ super(cradle, options)
44
+ this.options_ = options
45
+ const pg = PayPalProviderBase.resolvePgConnection(cradle)
46
+ this.paypal = new PayPalCredentialResolver(pg)
47
+ }
48
+
49
+ protected static resolvePgConnection(cradle: Record<string, any>): any {
50
+ for (const key of ["__pg_connection__", "pgConnection", "pg_connection"]) {
51
+ try {
52
+ const val = cradle[key]
53
+ if (val) return val
54
+ } catch {}
55
+ }
56
+ throw new Error(
57
+ "Could not resolve pgConnection from the payment module container. " +
58
+ "Ensure the paypal module is registered in medusa-config and the database is accessible."
59
+ )
60
+ }
61
+
62
+ protected generateSessionId(): string {
63
+ try {
64
+ return randomUUID()
65
+ } catch {
66
+ return `${this.sessionPrefix}_${Date.now()}_${Math.random().toString(16).slice(2)}`
67
+ }
68
+ }
69
+
70
+ async resolveSettings() {
71
+ return this.paypal.getSettings()
72
+ }
73
+
74
+ protected async resolveCurrencyOverride(): Promise<string> {
75
+ const { apiDetails } = await this.resolveSettings()
76
+ const code = apiDetails.currency_code
77
+ if (typeof code === "string" && code.trim()) {
78
+ return normalizeCurrencyCode(code)
79
+ }
80
+ return normalizeCurrencyCode(process.env.PAYPAL_CURRENCY || "EUR")
81
+ }
82
+
83
+ protected async getPayPalAccessToken() {
84
+ return this.paypal.getAccessToken()
85
+ }
86
+
87
+ protected async getOrderDetails(orderId: string) {
88
+ const { accessToken, base } = await this.getPayPalAccessToken()
89
+ const resp = await paypalFetch(
90
+ `${base}/v2/checkout/orders/${encodeURIComponent(orderId)}`,
91
+ {
92
+ method: "GET",
93
+ headers: {
94
+ Authorization: `Bearer ${accessToken}`,
95
+ "Content-Type": "application/json",
96
+ "PayPal-Partner-Attribution-Id": PAYPAL_PARTNER_ATTRIBUTION_ID,
97
+ },
98
+ }
99
+ )
100
+
101
+ const text = await resp.text()
102
+ if (!resp.ok) {
103
+ throw new Error(`PayPal get order error (${resp.status}): ${text}`)
104
+ }
105
+
106
+ return JSON.parse(text)
107
+ }
108
+
109
+ protected getIdempotencyKey(
110
+ input: { context?: { idempotency_key?: string } },
111
+ suffix: string
112
+ ): string {
113
+ const key = input?.context?.idempotency_key?.trim()
114
+ if (key) {
115
+ return `${key}-${suffix}`
116
+ }
117
+ return `${this.idempotencyPrefix}-${suffix}-${this.generateSessionId()}`
118
+ }
119
+
120
+ protected async normalizePaymentData(input: { data?: Record<string, unknown> }) {
121
+ const data = (input.data || {}) as Record<string, any>
122
+ const amount = toAmountNumber(data.amount)
123
+ const currencyOverride = await this.resolveCurrencyOverride()
124
+ const currencyCode = normalizeCurrencyCode(
125
+ data.currency_code || currencyOverride || "EUR"
126
+ )
127
+ assertPayPalCurrencySupported({
128
+ currencyCode,
129
+ paypalCurrencyOverride: currencyOverride,
130
+ })
131
+ return { data, amount, currencyCode }
132
+ }
133
+
134
+ protected formatAmount(amount: number, currencyCode?: string): string {
135
+ return formatAmountForPayPal(amount, currencyCode || "EUR")
136
+ }
137
+
138
+ protected mapCaptureStatus(status?: string) {
139
+ // Delegate to the shared, unit-tested mapping so the card and wallet
140
+ // providers agree with each other and with the webhook processor. Notably a
141
+ // PARTIALLY_REFUNDED capture must stay "captured" (only part of the funds
142
+ // were returned) — mapping it to "canceled" would wrongly unwind a live
143
+ // capture.
144
+ return mapPayPalCaptureStatus(status)
145
+ }
146
+
147
+ protected mapAuthorizationStatus(status?: string) {
148
+ const normalized = String(status || "").toUpperCase()
149
+ if (!normalized) return null
150
+ if (["CREATED", "APPROVED", "PENDING"].includes(normalized)) return "authorized"
151
+ if (["VOIDED", "EXPIRED"].includes(normalized)) return "canceled"
152
+ if (["DENIED", "DECLINED", "FAILED"].includes(normalized)) return "error"
153
+ return null
154
+ }
155
+
156
+ protected mapOrderStatus(status?: string) {
157
+ const normalized = String(status || "").toUpperCase()
158
+ if (!normalized) return "pending"
159
+ if (normalized === "COMPLETED") return "captured"
160
+ if (normalized === "APPROVED") return "authorized"
161
+ if (["VOIDED", "CANCELLED"].includes(normalized)) return "canceled"
162
+ if (["CREATED", "SAVED", "PAYER_ACTION_REQUIRED"].includes(normalized)) return "pending"
163
+ if (["FAILED", "EXPIRED"].includes(normalized)) return "error"
164
+ return "pending"
165
+ }
166
+
167
+ async createAccountHolder(
168
+ input: CreateAccountHolderInput
169
+ ): Promise<CreateAccountHolderOutput> {
170
+ const customerId = input.context?.customer?.id
171
+ const externalId = customerId
172
+ ? `paypal_${customerId}`
173
+ : `paypal_${this.generateSessionId()}`
174
+ return {
175
+ id: externalId,
176
+ data: {
177
+ email: input.context?.customer?.email || null,
178
+ customer_id: customerId || null,
179
+ },
180
+ }
181
+ }
182
+
183
+ async deletePayment(_input: DeletePaymentInput): Promise<DeletePaymentOutput> {
184
+ return { data: {} }
185
+ }
186
+
187
+ async getWebhookActionAndData(
188
+ payload: ProviderWebhookPayload["payload"]
189
+ ): Promise<WebhookActionResult> {
190
+ return getPayPalWebhookActionAndData(payload)
191
+ }
192
+ }
@@ -1,5 +1,4 @@
1
- import { AbstractPaymentProvider, MedusaError } from "@medusajs/framework/utils"
2
- import { randomUUID } from "crypto"
1
+ import { MedusaError } from "@medusajs/framework/utils"
3
2
  import type {
4
3
  AuthorizePaymentInput,
5
4
  AuthorizePaymentOutput,
@@ -7,10 +6,6 @@ import type {
7
6
  CapturePaymentOutput,
8
7
  CancelPaymentInput,
9
8
  CancelPaymentOutput,
10
- CreateAccountHolderInput,
11
- CreateAccountHolderOutput,
12
- DeletePaymentInput,
13
- DeletePaymentOutput,
14
9
  GetPaymentStatusInput,
15
10
  GetPaymentStatusOutput,
16
11
  InitiatePaymentInput,
@@ -21,190 +16,26 @@ import type {
21
16
  RetrievePaymentOutput,
22
17
  UpdatePaymentInput,
23
18
  UpdatePaymentOutput,
24
- ProviderWebhookPayload,
25
- WebhookActionResult,
26
19
  } from "@medusajs/framework/types"
27
- import { getPayPalWebhookActionAndData } from "./webhook-utils"
28
20
  import { formatAmountForPayPal, toAmountNumber } from "../utils/amounts"
29
- import { paypalFetch } from "../utils/paypal-fetch"
30
21
  import {
31
22
  assertPayPalCurrencySupported,
32
23
  normalizeCurrencyCode,
33
24
  } from "../utils/currencies"
25
+ import { PAYPAL_PARTNER_ATTRIBUTION_ID } from "../utils/partner"
26
+ import { paypalFetch, paypalFetchWithRetry } from "../utils/paypal-fetch"
34
27
  import {
35
28
  extractCaptureStatus,
36
29
  isCaptureCompleted,
37
30
  isRefundFailureStatus,
38
- mapPayPalCaptureStatus,
39
31
  } from "./status-utils"
40
- import { PayPalCredentialResolver } from "../utils/credential-resolver"
32
+ import { PayPalProviderBase } from "./base-provider"
41
33
 
42
- type Options = {}
43
-
44
- const BN_CODE = "MBJTechnolabs_SI_SPB"
45
-
46
- function generateSessionId() {
47
- try {
48
- return randomUUID()
49
- } catch {
50
- return `pp_card_${Date.now()}_${Math.random().toString(16).slice(2)}`
51
- }
52
- }
53
-
54
- class PayPalAdvancedCardProvider extends AbstractPaymentProvider<Options> {
34
+ class PayPalAdvancedCardProvider extends PayPalProviderBase {
55
35
  static identifier = "paypal_card"
56
36
 
57
- protected readonly options_: Options
58
- private paypal: PayPalCredentialResolver
59
-
60
- constructor(cradle: Record<string, any>, options: Options) {
61
- super(cradle, options)
62
- this.options_ = options
63
- const pg = PayPalAdvancedCardProvider.resolvePgConnection(cradle)
64
- this.paypal = new PayPalCredentialResolver(pg)
65
- }
66
-
67
- private static resolvePgConnection(cradle: Record<string, any>): any {
68
- for (const key of ["__pg_connection__", "pgConnection", "pg_connection"]) {
69
- try {
70
- const val = cradle[key]
71
- if (val) return val
72
- } catch {}
73
- }
74
- throw new Error(
75
- "Could not resolve pgConnection from the payment module container. " +
76
- "Ensure the paypal module is registered in medusa-config and the database is accessible."
77
- )
78
- }
79
-
80
- private async resolveSettings() {
81
- const settings = await this.paypal.getSettings()
82
- return {
83
- additionalSettings: settings.additionalSettings as Record<string, any>,
84
- advancedCardSettings: settings.advancedCardSettings as Record<string, any>,
85
- apiDetails: settings.apiDetails as Record<string, any>,
86
- }
87
- }
88
-
89
- private async resolveCurrencyOverride() {
90
- const { apiDetails } = await this.resolveSettings()
91
- if (typeof apiDetails.currency_code === "string" && apiDetails.currency_code.trim()) {
92
- return normalizeCurrencyCode(apiDetails.currency_code)
93
- }
94
- return normalizeCurrencyCode(process.env.PAYPAL_CURRENCY || "EUR")
95
- }
96
-
97
- private async getPayPalAccessToken() {
98
- return this.paypal.getAccessToken()
99
- }
100
-
101
- private async getOrderDetails(orderId: string) {
102
- const { accessToken, base } = await this.getPayPalAccessToken()
103
- const resp = await paypalFetch(`${base}/v2/checkout/orders/${encodeURIComponent(orderId)}`, {
104
- method: "GET",
105
- headers: {
106
- Authorization: `Bearer ${accessToken}`,
107
- "Content-Type": "application/json",
108
- "PayPal-Partner-Attribution-Id": BN_CODE,
109
- },
110
- })
111
-
112
- const text = await resp.text()
113
- if (!resp.ok) {
114
- throw new Error(`PayPal get order error (${resp.status}): ${text}`)
115
- }
116
-
117
- return JSON.parse(text)
118
- }
119
-
120
- private getIdempotencyKey(
121
- input: { context?: { idempotency_key?: string } },
122
- suffix: string
123
- ) {
124
- const key = input?.context?.idempotency_key?.trim()
125
- if (key) {
126
- return `${key}-${suffix}`
127
- }
128
- return `pp-card-${suffix}-${generateSessionId()}`
129
- }
130
-
131
- private async normalizePaymentData(input: { data?: Record<string, unknown> }) {
132
- const data = (input.data || {}) as Record<string, any>
133
- const amount = toAmountNumber(data.amount)
134
- const currencyOverride = await this.resolveCurrencyOverride()
135
- const currencyCode = normalizeCurrencyCode(
136
- data.currency_code || currencyOverride || "EUR"
137
- )
138
- assertPayPalCurrencySupported({
139
- currencyCode,
140
- paypalCurrencyOverride: currencyOverride,
141
- })
142
- return { data, amount, currencyCode }
143
- }
144
-
145
- private mapCaptureStatus(status?: string) {
146
- // Delegate to the shared, unit-tested mapping so the card provider agrees
147
- // with the wallet provider and the webhook processor. In particular a
148
- // PARTIALLY_REFUNDED capture must stay "captured" (only part of the funds
149
- // were returned) — mapping it to "canceled" would wrongly unwind a live
150
- // capture.
151
- return mapPayPalCaptureStatus(status)
152
- }
153
-
154
- private mapAuthorizationStatus(status?: string) {
155
- const normalized = String(status || "").toUpperCase()
156
- if (!normalized) {
157
- return null
158
- }
159
- if (["CREATED", "APPROVED", "PENDING"].includes(normalized)) {
160
- return "authorized"
161
- }
162
- if (["VOIDED", "EXPIRED"].includes(normalized)) {
163
- return "canceled"
164
- }
165
- if (["DENIED", "DECLINED", "FAILED"].includes(normalized)) {
166
- return "error"
167
- }
168
- return null
169
- }
170
-
171
- private mapOrderStatus(status?: string) {
172
- const normalized = String(status || "").toUpperCase()
173
- if (!normalized) {
174
- return "pending"
175
- }
176
- if (normalized === "COMPLETED") {
177
- return "captured"
178
- }
179
- if (normalized === "APPROVED") {
180
- return "authorized"
181
- }
182
- if (["VOIDED", "CANCELLED"].includes(normalized)) {
183
- return "canceled"
184
- }
185
- if (["CREATED", "SAVED", "PAYER_ACTION_REQUIRED"].includes(normalized)) {
186
- return "pending"
187
- }
188
- if (["FAILED", "EXPIRED"].includes(normalized)) {
189
- return "error"
190
- }
191
- return "pending"
192
- }
193
-
194
- async createAccountHolder(
195
- input: CreateAccountHolderInput
196
- ): Promise<CreateAccountHolderOutput> {
197
- const customerId = input.context?.customer?.id
198
- const externalId = customerId ? `paypal_${customerId}` : `paypal_${generateSessionId()}`
199
-
200
- return {
201
- id: externalId,
202
- data: {
203
- email: input.context?.customer?.email || null,
204
- customer_id: customerId || null,
205
- },
206
- }
207
- }
37
+ protected readonly sessionPrefix = "pp_card"
38
+ protected readonly idempotencyPrefix = "pp-card"
208
39
 
209
40
  async initiatePayment(input: InitiatePaymentInput): Promise<InitiatePaymentOutput> {
210
41
  const currencyOverride = await this.resolveCurrencyOverride()
@@ -217,7 +48,7 @@ class PayPalAdvancedCardProvider extends AbstractPaymentProvider<Options> {
217
48
  })
218
49
 
219
50
  return {
220
- id: generateSessionId(),
51
+ id: this.generateSessionId(),
221
52
  data: {
222
53
  ...(input.data || {}),
223
54
  amount: input.amount,
@@ -335,7 +166,7 @@ class PayPalAdvancedCardProvider extends AbstractPaymentProvider<Options> {
335
166
  Authorization: `Bearer ${accessToken}`,
336
167
  "Content-Type": "application/json",
337
168
  "PayPal-Request-Id": requestId,
338
- "PayPal-Partner-Attribution-Id": BN_CODE,
169
+ "PayPal-Partner-Attribution-Id": PAYPAL_PARTNER_ATTRIBUTION_ID,
339
170
  },
340
171
  body: JSON.stringify(orderPayload),
341
172
  })
@@ -389,7 +220,7 @@ class PayPalAdvancedCardProvider extends AbstractPaymentProvider<Options> {
389
220
  Authorization: `Bearer ${accessToken}`,
390
221
  "Content-Type": "application/json",
391
222
  "PayPal-Request-Id": `${requestId}-auth`,
392
- "PayPal-Partner-Attribution-Id": BN_CODE,
223
+ "PayPal-Partner-Attribution-Id": PAYPAL_PARTNER_ATTRIBUTION_ID,
393
224
  },
394
225
  })
395
226
 
@@ -449,8 +280,12 @@ class PayPalAdvancedCardProvider extends AbstractPaymentProvider<Options> {
449
280
  }
450
281
  }
451
282
 
452
- const requestId = this.getIdempotencyKey(_input, `capture-${orderId}`)
453
283
  const { amount, currencyCode } = await this.normalizePaymentData(_input)
284
+ // Include the amount in the idempotency suffix: PayPal deduplicates by
285
+ // PayPal-Request-Id, so two sequential partial captures of the same order
286
+ // that share an upstream idempotency_key would otherwise collide and the
287
+ // second capture would silently return the first one's result.
288
+ const requestId = this.getIdempotencyKey(_input, `capture-${orderId}-${amount}`)
454
289
  let debugId: string | null = null
455
290
 
456
291
  const { accessToken, base } = await this.getPayPalAccessToken()
@@ -480,7 +315,7 @@ class PayPalAdvancedCardProvider extends AbstractPaymentProvider<Options> {
480
315
  Authorization: `Bearer ${accessToken}`,
481
316
  "Content-Type": "application/json",
482
317
  "PayPal-Request-Id": `${requestId}-auth`,
483
- "PayPal-Partner-Attribution-Id": BN_CODE,
318
+ "PayPal-Partner-Attribution-Id": PAYPAL_PARTNER_ATTRIBUTION_ID,
484
319
  },
485
320
  })
486
321
  const authorizeText = await authorizeResp.text()
@@ -535,13 +370,16 @@ class PayPalAdvancedCardProvider extends AbstractPaymentProvider<Options> {
535
370
  }
536
371
  }
537
372
 
538
- const ppResp = await paypalFetch(captureUrl, {
373
+ // Retry transient 5xx/429/timeout: the PayPal-Request-Id makes the capture
374
+ // idempotent, so a retry after a network blip re-uses the same capture
375
+ // instead of double-charging.
376
+ const ppResp = await paypalFetchWithRetry(captureUrl, {
539
377
  method: "POST",
540
378
  headers: {
541
379
  Authorization: `Bearer ${accessToken}`,
542
380
  "Content-Type": "application/json",
543
381
  "PayPal-Request-Id": requestId,
544
- "PayPal-Partner-Attribution-Id": BN_CODE,
382
+ "PayPal-Partner-Attribution-Id": PAYPAL_PARTNER_ATTRIBUTION_ID,
545
383
  },
546
384
  body: JSON.stringify(capturePayload),
547
385
  })
@@ -623,7 +461,7 @@ class PayPalAdvancedCardProvider extends AbstractPaymentProvider<Options> {
623
461
  Authorization: `Bearer ${accessToken}`,
624
462
  "Content-Type": "application/json",
625
463
  "PayPal-Request-Id": requestId,
626
- "PayPal-Partner-Attribution-Id": BN_CODE,
464
+ "PayPal-Partner-Attribution-Id": PAYPAL_PARTNER_ATTRIBUTION_ID,
627
465
  },
628
466
  }
629
467
  )
@@ -649,7 +487,7 @@ class PayPalAdvancedCardProvider extends AbstractPaymentProvider<Options> {
649
487
  Authorization: `Bearer ${accessToken}`,
650
488
  "Content-Type": "application/json",
651
489
  "PayPal-Request-Id": requestId,
652
- "PayPal-Partner-Attribution-Id": BN_CODE,
490
+ "PayPal-Partner-Attribution-Id": PAYPAL_PARTNER_ATTRIBUTION_ID,
653
491
  },
654
492
  body: JSON.stringify({}),
655
493
  }
@@ -740,13 +578,16 @@ class PayPalAdvancedCardProvider extends AbstractPaymentProvider<Options> {
740
578
  }
741
579
  : {}
742
580
 
743
- const resp = await paypalFetch(`${base}/v2/payments/captures/${encodeURIComponent(captureId)}/refund`, {
581
+ // Retry transient 5xx/429/timeout: the PayPal-Request-Id (which includes
582
+ // the refund amount) makes the refund idempotent, so a retry after a
583
+ // network blip re-uses the same refund instead of double-refunding.
584
+ const resp = await paypalFetchWithRetry(`${base}/v2/payments/captures/${encodeURIComponent(captureId)}/refund`, {
744
585
  method: "POST",
745
586
  headers: {
746
587
  Authorization: `Bearer ${accessToken}`,
747
588
  "Content-Type": "application/json",
748
589
  "PayPal-Request-Id": requestId,
749
- "PayPal-Partner-Attribution-Id": BN_CODE,
590
+ "PayPal-Partner-Attribution-Id": PAYPAL_PARTNER_ATTRIBUTION_ID,
750
591
  },
751
592
  body: JSON.stringify(refundPayload),
752
593
  })
@@ -867,15 +708,6 @@ class PayPalAdvancedCardProvider extends AbstractPaymentProvider<Options> {
867
708
  }
868
709
  }
869
710
 
870
- async deletePayment(_input: DeletePaymentInput): Promise<DeletePaymentOutput> {
871
- return { data: {} }
872
- }
873
-
874
- async getWebhookActionAndData(
875
- payload: ProviderWebhookPayload["payload"]
876
- ): Promise<WebhookActionResult> {
877
- return getPayPalWebhookActionAndData(payload)
878
- }
879
711
  }
880
712
 
881
713
  export default PayPalAdvancedCardProvider