@easypayment/medusa-payment-paypal 1.2.3 → 1.2.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (274) hide show
  1. package/.medusa/server/src/admin/index.js +392 -138
  2. package/.medusa/server/src/admin/index.mjs +392 -138
  3. package/.medusa/server/src/api/admin/payment-collections/[id]/payment-sessions/route.d.ts +1 -0
  4. package/.medusa/server/src/api/admin/payment-collections/[id]/payment-sessions/route.d.ts.map +1 -1
  5. package/.medusa/server/src/api/admin/payment-collections/[id]/payment-sessions/route.js +5 -1
  6. package/.medusa/server/src/api/admin/payment-collections/[id]/payment-sessions/route.js.map +1 -1
  7. package/.medusa/server/src/api/admin/paypal/disconnect/route.d.ts +1 -0
  8. package/.medusa/server/src/api/admin/paypal/disconnect/route.d.ts.map +1 -1
  9. package/.medusa/server/src/api/admin/paypal/disconnect/route.js +1 -0
  10. package/.medusa/server/src/api/admin/paypal/disconnect/route.js.map +1 -1
  11. package/.medusa/server/src/api/admin/paypal/environment/route.d.ts +2 -0
  12. package/.medusa/server/src/api/admin/paypal/environment/route.d.ts.map +1 -1
  13. package/.medusa/server/src/api/admin/paypal/environment/route.js +2 -0
  14. package/.medusa/server/src/api/admin/paypal/environment/route.js.map +1 -1
  15. package/.medusa/server/src/api/admin/paypal/onboard-complete/route.d.ts +9 -0
  16. package/.medusa/server/src/api/admin/paypal/onboard-complete/route.d.ts.map +1 -1
  17. package/.medusa/server/src/api/admin/paypal/onboard-complete/route.js +9 -4
  18. package/.medusa/server/src/api/admin/paypal/onboard-complete/route.js.map +1 -1
  19. package/.medusa/server/src/api/admin/paypal/onboarding-link/route.d.ts +7 -1
  20. package/.medusa/server/src/api/admin/paypal/onboarding-link/route.d.ts.map +1 -1
  21. package/.medusa/server/src/api/admin/paypal/onboarding-link/route.js +9 -2
  22. package/.medusa/server/src/api/admin/paypal/onboarding-link/route.js.map +1 -1
  23. package/.medusa/server/src/api/admin/paypal/onboarding-status/route.d.ts +1 -0
  24. package/.medusa/server/src/api/admin/paypal/onboarding-status/route.d.ts.map +1 -1
  25. package/.medusa/server/src/api/admin/paypal/onboarding-status/route.js +1 -0
  26. package/.medusa/server/src/api/admin/paypal/onboarding-status/route.js.map +1 -1
  27. package/.medusa/server/src/api/admin/paypal/save-credentials/route.d.ts +1 -0
  28. package/.medusa/server/src/api/admin/paypal/save-credentials/route.d.ts.map +1 -1
  29. package/.medusa/server/src/api/admin/paypal/save-credentials/route.js +10 -3
  30. package/.medusa/server/src/api/admin/paypal/save-credentials/route.js.map +1 -1
  31. package/.medusa/server/src/api/admin/paypal/settings/route.d.ts +2 -0
  32. package/.medusa/server/src/api/admin/paypal/settings/route.d.ts.map +1 -1
  33. package/.medusa/server/src/api/admin/paypal/settings/route.js +9 -2
  34. package/.medusa/server/src/api/admin/paypal/settings/route.js.map +1 -1
  35. package/.medusa/server/src/api/admin/paypal/status/route.d.ts +4 -0
  36. package/.medusa/server/src/api/admin/paypal/status/route.d.ts.map +1 -1
  37. package/.medusa/server/src/api/admin/paypal/status/route.js +9 -1
  38. package/.medusa/server/src/api/admin/paypal/status/route.js.map +1 -1
  39. package/.medusa/server/src/api/store/payment-collections/[id]/payment-sessions/route.d.ts +4 -0
  40. package/.medusa/server/src/api/store/payment-collections/[id]/payment-sessions/route.d.ts.map +1 -1
  41. package/.medusa/server/src/api/store/payment-collections/[id]/payment-sessions/route.js +11 -1
  42. package/.medusa/server/src/api/store/payment-collections/[id]/payment-sessions/route.js.map +1 -1
  43. package/.medusa/server/src/api/store/paypal/capture-order/route.d.ts +8 -0
  44. package/.medusa/server/src/api/store/paypal/capture-order/route.d.ts.map +1 -1
  45. package/.medusa/server/src/api/store/paypal/capture-order/route.js +23 -3
  46. package/.medusa/server/src/api/store/paypal/capture-order/route.js.map +1 -1
  47. package/.medusa/server/src/api/store/paypal/config/route.d.ts +5 -0
  48. package/.medusa/server/src/api/store/paypal/config/route.d.ts.map +1 -1
  49. package/.medusa/server/src/api/store/paypal/config/route.js +12 -5
  50. package/.medusa/server/src/api/store/paypal/config/route.js.map +1 -1
  51. package/.medusa/server/src/api/store/paypal/create-order/route.d.ts +8 -0
  52. package/.medusa/server/src/api/store/paypal/create-order/route.d.ts.map +1 -1
  53. package/.medusa/server/src/api/store/paypal/create-order/route.js +80 -26
  54. package/.medusa/server/src/api/store/paypal/create-order/route.js.map +1 -1
  55. package/.medusa/server/src/api/store/paypal/onboard-return/route.d.ts.map +1 -1
  56. package/.medusa/server/src/api/store/paypal/onboard-return/route.js +19 -19
  57. package/.medusa/server/src/api/store/paypal/onboard-return/route.js.map +1 -1
  58. package/.medusa/server/src/api/store/paypal/settings/route.d.ts +1 -0
  59. package/.medusa/server/src/api/store/paypal/settings/route.d.ts.map +1 -1
  60. package/.medusa/server/src/api/store/paypal/settings/route.js +4 -1
  61. package/.medusa/server/src/api/store/paypal/settings/route.js.map +1 -1
  62. package/.medusa/server/src/api/store/paypal/webhook/route.d.ts +7 -0
  63. package/.medusa/server/src/api/store/paypal/webhook/route.d.ts.map +1 -1
  64. package/.medusa/server/src/api/store/paypal/webhook/route.js +34 -3
  65. package/.medusa/server/src/api/store/paypal/webhook/route.js.map +1 -1
  66. package/.medusa/server/src/api/store/paypal-complete/route.d.ts +8 -0
  67. package/.medusa/server/src/api/store/paypal-complete/route.d.ts.map +1 -1
  68. package/.medusa/server/src/api/store/paypal-complete/route.js +55 -8
  69. package/.medusa/server/src/api/store/paypal-complete/route.js.map +1 -1
  70. package/.medusa/server/src/api/utils/rate-limit.d.ts +4 -0
  71. package/.medusa/server/src/api/utils/rate-limit.d.ts.map +1 -1
  72. package/.medusa/server/src/api/utils/rate-limit.js +9 -4
  73. package/.medusa/server/src/api/utils/rate-limit.js.map +1 -1
  74. package/.medusa/server/src/jobs/paypal-webhook-retry.d.ts +5 -0
  75. package/.medusa/server/src/jobs/paypal-webhook-retry.d.ts.map +1 -1
  76. package/.medusa/server/src/jobs/paypal-webhook-retry.js +13 -2
  77. package/.medusa/server/src/jobs/paypal-webhook-retry.js.map +1 -1
  78. package/.medusa/server/src/modules/paypal/index.d.ts +1 -0
  79. package/.medusa/server/src/modules/paypal/index.d.ts.map +1 -1
  80. package/.medusa/server/src/modules/paypal/index.js +1 -0
  81. package/.medusa/server/src/modules/paypal/index.js.map +1 -1
  82. package/.medusa/server/src/modules/paypal/migrations/20260115120000_create_paypal_connection.js +22 -22
  83. package/.medusa/server/src/modules/paypal/migrations/20260123090000_create_paypal_settings.js +11 -11
  84. package/.medusa/server/src/modules/paypal/migrations/20260201090000_create_paypal_webhook_event.js +18 -18
  85. package/.medusa/server/src/modules/paypal/migrations/20260401090000_create_paypal_metric.js +16 -16
  86. package/.medusa/server/src/modules/paypal/migrations/20260701090000_add_paypal_webhook_event_processing.js +20 -20
  87. package/.medusa/server/src/modules/paypal/migrations/20261101090000_remove_paypal_reconciliation_status.js +14 -14
  88. package/.medusa/server/src/modules/paypal/migrations/20261201090000_remove_paypal_audit_log.js +15 -15
  89. package/.medusa/server/src/modules/paypal/migrations/20270101090000_set_paypal_environment_default_live.d.ts.map +1 -1
  90. package/.medusa/server/src/modules/paypal/migrations/20270101090000_set_paypal_environment_default_live.js.map +1 -1
  91. package/.medusa/server/src/modules/paypal/migrations/20270102090000_add_paypal_seller_email.d.ts.map +1 -1
  92. package/.medusa/server/src/modules/paypal/migrations/20270102090000_add_paypal_seller_email.js.map +1 -1
  93. package/.medusa/server/src/modules/paypal/migrations/20270103090000_add_paypal_seller_merchant_id.d.ts.map +1 -1
  94. package/.medusa/server/src/modules/paypal/migrations/20270103090000_add_paypal_seller_merchant_id.js.map +1 -1
  95. package/.medusa/server/src/modules/paypal/migrations/20270201000000_add_webhook_dead_letter.js +6 -6
  96. package/.medusa/server/src/modules/paypal/models/paypal_connection.d.ts +5 -0
  97. package/.medusa/server/src/modules/paypal/models/paypal_connection.d.ts.map +1 -1
  98. package/.medusa/server/src/modules/paypal/models/paypal_connection.js +5 -0
  99. package/.medusa/server/src/modules/paypal/models/paypal_connection.js.map +1 -1
  100. package/.medusa/server/src/modules/paypal/models/paypal_metric.d.ts +4 -0
  101. package/.medusa/server/src/modules/paypal/models/paypal_metric.d.ts.map +1 -1
  102. package/.medusa/server/src/modules/paypal/models/paypal_metric.js +4 -0
  103. package/.medusa/server/src/modules/paypal/models/paypal_metric.js.map +1 -1
  104. package/.medusa/server/src/modules/paypal/models/paypal_settings.d.ts +5 -0
  105. package/.medusa/server/src/modules/paypal/models/paypal_settings.d.ts.map +1 -1
  106. package/.medusa/server/src/modules/paypal/models/paypal_settings.js +5 -0
  107. package/.medusa/server/src/modules/paypal/models/paypal_settings.js.map +1 -1
  108. package/.medusa/server/src/modules/paypal/models/paypal_webhook_event.d.ts +7 -0
  109. package/.medusa/server/src/modules/paypal/models/paypal_webhook_event.d.ts.map +1 -1
  110. package/.medusa/server/src/modules/paypal/models/paypal_webhook_event.js +7 -0
  111. package/.medusa/server/src/modules/paypal/models/paypal_webhook_event.js.map +1 -1
  112. package/.medusa/server/src/modules/paypal/payment-provider/base-provider.d.ts +24 -1
  113. package/.medusa/server/src/modules/paypal/payment-provider/base-provider.d.ts.map +1 -1
  114. package/.medusa/server/src/modules/paypal/payment-provider/base-provider.js +296 -0
  115. package/.medusa/server/src/modules/paypal/payment-provider/base-provider.js.map +1 -1
  116. package/.medusa/server/src/modules/paypal/payment-provider/card-service.d.ts +14 -7
  117. package/.medusa/server/src/modules/paypal/payment-provider/card-service.d.ts.map +1 -1
  118. package/.medusa/server/src/modules/paypal/payment-provider/card-service.js +40 -198
  119. package/.medusa/server/src/modules/paypal/payment-provider/card-service.js.map +1 -1
  120. package/.medusa/server/src/modules/paypal/payment-provider/index.d.ts +6 -1
  121. package/.medusa/server/src/modules/paypal/payment-provider/index.d.ts.map +1 -1
  122. package/.medusa/server/src/modules/paypal/payment-provider/index.js +6 -4
  123. package/.medusa/server/src/modules/paypal/payment-provider/index.js.map +1 -1
  124. package/.medusa/server/src/modules/paypal/payment-provider/service.d.ts +9 -2
  125. package/.medusa/server/src/modules/paypal/payment-provider/service.d.ts.map +1 -1
  126. package/.medusa/server/src/modules/paypal/payment-provider/service.js +29 -181
  127. package/.medusa/server/src/modules/paypal/payment-provider/service.js.map +1 -1
  128. package/.medusa/server/src/modules/paypal/payment-provider/status-utils.d.ts +21 -0
  129. package/.medusa/server/src/modules/paypal/payment-provider/status-utils.d.ts.map +1 -1
  130. package/.medusa/server/src/modules/paypal/payment-provider/status-utils.js +54 -0
  131. package/.medusa/server/src/modules/paypal/payment-provider/status-utils.js.map +1 -1
  132. package/.medusa/server/src/modules/paypal/service.d.ts +72 -2
  133. package/.medusa/server/src/modules/paypal/service.d.ts.map +1 -1
  134. package/.medusa/server/src/modules/paypal/service.js +159 -33
  135. package/.medusa/server/src/modules/paypal/service.js.map +1 -1
  136. package/.medusa/server/src/modules/paypal/types/config.d.ts +2 -0
  137. package/.medusa/server/src/modules/paypal/types/config.d.ts.map +1 -1
  138. package/.medusa/server/src/modules/paypal/types/config.js +5 -2
  139. package/.medusa/server/src/modules/paypal/types/config.js.map +1 -1
  140. package/.medusa/server/src/modules/paypal/utils/amounts.d.ts +1 -0
  141. package/.medusa/server/src/modules/paypal/utils/amounts.d.ts.map +1 -1
  142. package/.medusa/server/src/modules/paypal/utils/amounts.js +15 -5
  143. package/.medusa/server/src/modules/paypal/utils/amounts.js.map +1 -1
  144. package/.medusa/server/src/modules/paypal/utils/credential-resolver.d.ts +10 -0
  145. package/.medusa/server/src/modules/paypal/utils/credential-resolver.d.ts.map +1 -1
  146. package/.medusa/server/src/modules/paypal/utils/credential-resolver.js +45 -1
  147. package/.medusa/server/src/modules/paypal/utils/credential-resolver.js.map +1 -1
  148. package/.medusa/server/src/modules/paypal/utils/currencies.d.ts +9 -0
  149. package/.medusa/server/src/modules/paypal/utils/currencies.d.ts.map +1 -1
  150. package/.medusa/server/src/modules/paypal/utils/currencies.js +13 -0
  151. package/.medusa/server/src/modules/paypal/utils/currencies.js.map +1 -1
  152. package/.medusa/server/src/modules/paypal/utils/payment-session.d.ts +12 -0
  153. package/.medusa/server/src/modules/paypal/utils/payment-session.d.ts.map +1 -1
  154. package/.medusa/server/src/modules/paypal/utils/payment-session.js +4 -3
  155. package/.medusa/server/src/modules/paypal/utils/payment-session.js.map +1 -1
  156. package/.medusa/server/src/modules/paypal/utils/paypal-auth.d.ts +1 -0
  157. package/.medusa/server/src/modules/paypal/utils/paypal-auth.d.ts.map +1 -1
  158. package/.medusa/server/src/modules/paypal/utils/paypal-auth.js +1 -0
  159. package/.medusa/server/src/modules/paypal/utils/paypal-auth.js.map +1 -1
  160. package/.medusa/server/src/modules/paypal/utils/paypal-fetch.d.ts +11 -0
  161. package/.medusa/server/src/modules/paypal/utils/paypal-fetch.d.ts.map +1 -1
  162. package/.medusa/server/src/modules/paypal/utils/paypal-fetch.js +17 -1
  163. package/.medusa/server/src/modules/paypal/utils/paypal-fetch.js.map +1 -1
  164. package/.medusa/server/src/modules/paypal/utils/provider-ids.d.ts +6 -0
  165. package/.medusa/server/src/modules/paypal/utils/provider-ids.d.ts.map +1 -1
  166. package/.medusa/server/src/modules/paypal/utils/provider-ids.js +6 -0
  167. package/.medusa/server/src/modules/paypal/utils/provider-ids.js.map +1 -1
  168. package/.medusa/server/src/modules/paypal/utils/secret-crypto.d.ts +2 -0
  169. package/.medusa/server/src/modules/paypal/utils/secret-crypto.d.ts.map +1 -1
  170. package/.medusa/server/src/modules/paypal/utils/secret-crypto.js +6 -1
  171. package/.medusa/server/src/modules/paypal/utils/secret-crypto.js.map +1 -1
  172. package/.medusa/server/src/modules/paypal/webhook-processor.d.ts +43 -0
  173. package/.medusa/server/src/modules/paypal/webhook-processor.d.ts.map +1 -1
  174. package/.medusa/server/src/modules/paypal/webhook-processor.js +57 -5
  175. package/.medusa/server/src/modules/paypal/webhook-processor.js.map +1 -1
  176. package/.medusa/server/src/providers/paypal/index.d.ts +1 -0
  177. package/.medusa/server/src/providers/paypal/index.d.ts.map +1 -1
  178. package/.medusa/server/src/providers/paypal/index.js +1 -0
  179. package/.medusa/server/src/providers/paypal/index.js.map +1 -1
  180. package/.medusa/server/src/providers/paypal_card/index.d.ts +1 -0
  181. package/.medusa/server/src/providers/paypal_card/index.d.ts.map +1 -1
  182. package/.medusa/server/src/providers/paypal_card/index.js +1 -0
  183. package/.medusa/server/src/providers/paypal_card/index.js.map +1 -1
  184. package/.medusa/server/src/subscribers/paypal-order-invoice.d.ts +6 -0
  185. package/.medusa/server/src/subscribers/paypal-order-invoice.d.ts.map +1 -1
  186. package/.medusa/server/src/subscribers/paypal-order-invoice.js +9 -1
  187. package/.medusa/server/src/subscribers/paypal-order-invoice.js.map +1 -1
  188. package/.medusa/server/src/subscribers/paypal-webhook-process.d.ts +1 -0
  189. package/.medusa/server/src/subscribers/paypal-webhook-process.d.ts.map +1 -1
  190. package/.medusa/server/src/subscribers/paypal-webhook-process.js +17 -4
  191. package/.medusa/server/src/subscribers/paypal-webhook-process.js.map +1 -1
  192. package/CHANGELOG.md +65 -0
  193. package/README.md +184 -184
  194. package/package.json +7 -4
  195. package/src/admin/index.ts +1 -1
  196. package/src/admin/routes/settings/paypal/_components/FieldRow.tsx +38 -29
  197. package/src/admin/routes/settings/paypal/_components/SectionCard.tsx +29 -26
  198. package/src/admin/routes/settings/paypal/_components/Tabs.tsx +49 -48
  199. package/src/admin/routes/settings/paypal/_components/Toast.tsx +63 -52
  200. package/src/admin/routes/settings/paypal/_utils/adminFetch.ts +52 -32
  201. package/src/admin/routes/settings/paypal/additional-settings/page.tsx +246 -139
  202. package/src/admin/routes/settings/paypal/advanced-card-payments/page.tsx +208 -123
  203. package/src/admin/routes/settings/paypal/apple-pay/page.tsx +9 -5
  204. package/src/admin/routes/settings/paypal/connection/page.tsx +974 -908
  205. package/src/admin/routes/settings/paypal/google-pay/page.tsx +9 -5
  206. package/src/admin/routes/settings/paypal/page.tsx +14 -13
  207. package/src/admin/routes/settings/paypal/pay-later-messaging/page.tsx +9 -5
  208. package/src/admin/routes/settings/paypal/paypal-settings/page.tsx +304 -273
  209. package/src/api/admin/payment-collections/[id]/payment-sessions/route.ts +48 -39
  210. package/src/api/admin/paypal/disconnect/route.ts +15 -14
  211. package/src/api/admin/paypal/environment/route.ts +34 -32
  212. package/src/api/admin/paypal/onboard-complete/route.ts +61 -50
  213. package/src/api/admin/paypal/onboarding-link/route.ts +91 -76
  214. package/src/api/admin/paypal/onboarding-status/route.ts +21 -20
  215. package/src/api/admin/paypal/save-credentials/route.ts +48 -37
  216. package/src/api/admin/paypal/settings/route.ts +63 -45
  217. package/src/api/admin/paypal/status/route.ts +29 -17
  218. package/src/api/hooks/paypal/onboard-return/route.ts +15 -15
  219. package/src/api/hooks/paypal/webhook/route.ts +17 -17
  220. package/src/api/middlewares.ts +61 -61
  221. package/src/api/store/payment-collections/[id]/payment-sessions/route.ts +69 -54
  222. package/src/api/store/paypal/capture-order/route.ts +416 -370
  223. package/src/api/store/paypal/config/route.ts +121 -115
  224. package/src/api/store/paypal/create-order/route.ts +611 -539
  225. package/src/api/store/paypal/onboard-return/route.ts +116 -113
  226. package/src/api/store/paypal/settings/route.ts +29 -19
  227. package/src/api/store/paypal/webhook/route.ts +380 -314
  228. package/src/api/store/paypal-complete/route.ts +184 -128
  229. package/src/api/utils/rate-limit.ts +143 -129
  230. package/src/index.ts +1 -1
  231. package/src/jobs/paypal-webhook-retry.ts +257 -241
  232. package/src/modules/paypal/index.ts +9 -8
  233. package/src/modules/paypal/migrations/20260115120000_create_paypal_connection.ts +33 -33
  234. package/src/modules/paypal/migrations/20260123090000_create_paypal_settings.ts +22 -22
  235. package/src/modules/paypal/migrations/20260201090000_create_paypal_webhook_event.ts +29 -29
  236. package/src/modules/paypal/migrations/20260401090000_create_paypal_metric.ts +27 -27
  237. package/src/modules/paypal/migrations/20260701090000_add_paypal_webhook_event_processing.ts +31 -31
  238. package/src/modules/paypal/migrations/20261101090000_remove_paypal_reconciliation_status.ts +25 -25
  239. package/src/modules/paypal/migrations/20261201090000_remove_paypal_audit_log.ts +26 -26
  240. package/src/modules/paypal/migrations/20270101090000_set_paypal_environment_default_live.ts +15 -11
  241. package/src/modules/paypal/migrations/20270102090000_add_paypal_seller_email.ts +15 -11
  242. package/src/modules/paypal/migrations/20270103090000_add_paypal_seller_merchant_id.ts +15 -11
  243. package/src/modules/paypal/migrations/20270201000000_add_webhook_dead_letter.ts +17 -17
  244. package/src/modules/paypal/migrations/20270202000000_align_nullable_defaults.ts +44 -44
  245. package/src/modules/paypal/migrations/20270301000000_add_webhook_transmission_id_index.ts +15 -15
  246. package/src/modules/paypal/models/paypal_connection.ts +28 -23
  247. package/src/modules/paypal/models/paypal_metric.ts +13 -9
  248. package/src/modules/paypal/models/paypal_settings.ts +13 -8
  249. package/src/modules/paypal/models/paypal_webhook_event.ts +26 -19
  250. package/src/modules/paypal/payment-provider/base-provider.ts +700 -275
  251. package/src/modules/paypal/payment-provider/card-service.ts +693 -855
  252. package/src/modules/paypal/payment-provider/index.ts +14 -15
  253. package/src/modules/paypal/payment-provider/service.ts +673 -836
  254. package/src/modules/paypal/payment-provider/status-utils.ts +116 -59
  255. package/src/modules/paypal/payment-provider/webhook-utils.ts +109 -109
  256. package/src/modules/paypal/service.ts +362 -115
  257. package/src/modules/paypal/types/config.ts +70 -65
  258. package/src/modules/paypal/utils/amounts.ts +123 -107
  259. package/src/modules/paypal/utils/core-workflow.ts +46 -46
  260. package/src/modules/paypal/utils/credential-resolver.ts +315 -271
  261. package/src/modules/paypal/utils/currencies.ts +97 -84
  262. package/src/modules/paypal/utils/partner.ts +8 -8
  263. package/src/modules/paypal/utils/payment-session.ts +144 -138
  264. package/src/modules/paypal/utils/paypal-auth.ts +6 -5
  265. package/src/modules/paypal/utils/paypal-fetch.ts +197 -181
  266. package/src/modules/paypal/utils/provider-ids.ts +21 -15
  267. package/src/modules/paypal/utils/secret-crypto.ts +226 -197
  268. package/src/modules/paypal/utils/webhook-verify.ts +61 -61
  269. package/src/modules/paypal/webhook-processor.ts +641 -573
  270. package/src/providers/paypal/index.ts +9 -8
  271. package/src/providers/paypal_card/index.ts +9 -8
  272. package/src/subscribers/paypal-order-invoice.ts +180 -173
  273. package/src/subscribers/paypal-webhook-process.ts +147 -131
  274. package/tsconfig.json +21 -31
@@ -1,275 +1,700 @@
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
- /** Serialize an error for audit metadata without losing cause chains. */
63
- protected serializeError(error: unknown) {
64
- if (error instanceof Error) {
65
- const errorWithCause = error as Error & { cause?: unknown }
66
- const cause = errorWithCause.cause
67
- return {
68
- name: error.name,
69
- message: error.message,
70
- stack: error.stack,
71
- cause:
72
- cause instanceof Error
73
- ? { name: cause.name, message: cause.message, stack: cause.stack }
74
- : cause,
75
- }
76
- }
77
- return { message: String(error) }
78
- }
79
-
80
- protected async recordFailure(eventType: string, metadata?: Record<string, unknown>) {
81
- await this.paypal.recordAuditEvent(eventType, metadata)
82
- await this.paypal.recordMetric(eventType, metadata)
83
- }
84
-
85
- protected async recordSuccess(metricName: string) {
86
- await this.paypal.recordMetric(metricName)
87
- }
88
-
89
- protected async recordPaymentEvent(eventType: string, metadata?: Record<string, unknown>) {
90
- await this.paypal.recordAuditEvent(eventType, metadata)
91
- }
92
-
93
- protected generateSessionId(): string {
94
- try {
95
- return randomUUID()
96
- } catch {
97
- return `${this.sessionPrefix}_${Date.now()}_${Math.random().toString(16).slice(2)}`
98
- }
99
- }
100
-
101
- async resolveSettings() {
102
- return this.paypal.getSettings()
103
- }
104
-
105
- protected async resolveCurrencyOverride(): Promise<string> {
106
- const { apiDetails } = await this.resolveSettings()
107
- const code = apiDetails.currency_code
108
- if (typeof code === "string" && code.trim()) {
109
- return normalizeCurrencyCode(code)
110
- }
111
- return normalizeCurrencyCode(process.env.PAYPAL_CURRENCY || "EUR")
112
- }
113
-
114
- protected async getPayPalAccessToken() {
115
- return this.paypal.getAccessToken()
116
- }
117
-
118
- protected async getOrderDetails(orderId: string) {
119
- const { accessToken, base } = await this.getPayPalAccessToken()
120
- const resp = await paypalFetch(
121
- `${base}/v2/checkout/orders/${encodeURIComponent(orderId)}`,
122
- {
123
- method: "GET",
124
- headers: {
125
- Authorization: `Bearer ${accessToken}`,
126
- "Content-Type": "application/json",
127
- "PayPal-Partner-Attribution-Id": PAYPAL_PARTNER_ATTRIBUTION_ID,
128
- },
129
- }
130
- )
131
-
132
- const text = await resp.text()
133
- if (!resp.ok) {
134
- throw new Error(`PayPal get order error (${resp.status}): ${text}`)
135
- }
136
-
137
- return JSON.parse(text)
138
- }
139
-
140
- protected getIdempotencyKey(
141
- input: { context?: { idempotency_key?: string } },
142
- suffix: string
143
- ): string {
144
- const key = input?.context?.idempotency_key?.trim()
145
- if (key) {
146
- return `${key}-${suffix}`
147
- }
148
- return `${this.idempotencyPrefix}-${suffix}-${this.generateSessionId()}`
149
- }
150
-
151
- protected async normalizePaymentData(input: { data?: Record<string, unknown> }) {
152
- const data = (input.data || {}) as Record<string, any>
153
- const amount = toAmountNumber(data.amount)
154
- const currencyOverride = await this.resolveCurrencyOverride()
155
- const currencyCode = normalizeCurrencyCode(
156
- data.currency_code || currencyOverride || "EUR"
157
- )
158
- assertPayPalCurrencySupported({
159
- currencyCode,
160
- paypalCurrencyOverride: currencyOverride,
161
- })
162
- return { data, amount, currencyCode }
163
- }
164
-
165
- protected formatAmount(amount: number, currencyCode?: string): string {
166
- return formatAmountForPayPal(amount, currencyCode || "EUR")
167
- }
168
-
169
- /**
170
- * Amount to send to PayPal for a capture. Medusa invokes the provider's
171
- * capturePayment with only `{ data, context: { idempotency_key } }` — the
172
- * admin's requested (possibly partial) capture amount is never passed in the
173
- * input. The idempotency_key IS the Medusa `capture` row id, so resolve the
174
- * requested amount from that row; otherwise a partial capture would silently
175
- * charge the buyer the full session total. Falls back to the session amount
176
- * when the row can't be resolved (preserving full-capture behavior), and
177
- * never returns more than the session amount.
178
- */
179
- protected async resolveRequestedCaptureAmount(
180
- input: { context?: { idempotency_key?: string } },
181
- sessionAmount: number
182
- ): Promise<number> {
183
- const captureRowId = input?.context?.idempotency_key?.trim()
184
- if (!captureRowId) return sessionAmount
185
- const requested = await this.paypal.getRequestedCaptureAmount(captureRowId)
186
- if (requested === null || !Number.isFinite(requested) || requested <= 0) {
187
- return sessionAmount
188
- }
189
- return Math.min(requested, sessionAmount)
190
- }
191
-
192
- /**
193
- * When the session amount or currency changes while a not-yet-approved PayPal
194
- * order is stored on the session, drop the stored order reference so the next
195
- * create-order call mints a fresh order at the correct total. Without this, a
196
- * buyer who opens PayPal (order created for the old total), backs out, and
197
- * changes the cart gets charged the stale amount. Returns a `{ paypal }`
198
- * patch to spread into the updated session data, or `{}` when nothing needs
199
- * invalidating. Sessions that already carry a capture/authorization are never
200
- * touched.
201
- */
202
- protected invalidateStaleOrder(
203
- input: { data?: Record<string, unknown>; amount?: unknown },
204
- nextCurrencyCode: string
205
- ): Record<string, unknown> {
206
- const data = (input.data || {}) as Record<string, any>
207
- const paypal = (data.paypal || {}) as Record<string, any>
208
- if (!paypal.order_id) return {}
209
- if (paypal.capture_id || paypal.authorization_id) return {}
210
- const prevAmount = toAmountNumber(data.amount)
211
- const nextAmount = toAmountNumber(input.amount)
212
- const prevCurrency = String(data.currency_code || "").toUpperCase()
213
- const amountChanged =
214
- prevAmount > 0 && nextAmount > 0 && prevAmount !== nextAmount
215
- const currencyChanged = !!prevCurrency && prevCurrency !== nextCurrencyCode
216
- if (!amountChanged && !currencyChanged) return {}
217
- const { order_id: _orderId, order: _order, ...rest } = paypal
218
- return { paypal: rest }
219
- }
220
-
221
- protected mapCaptureStatus(status?: string) {
222
- // Delegate to the shared, unit-tested mapping so the card and wallet
223
- // providers agree with each other and with the webhook processor. Notably a
224
- // PARTIALLY_REFUNDED capture must stay "captured" (only part of the funds
225
- // were returned) — mapping it to "canceled" would wrongly unwind a live
226
- // capture.
227
- return mapPayPalCaptureStatus(status)
228
- }
229
-
230
- protected mapAuthorizationStatus(status?: string) {
231
- const normalized = String(status || "").toUpperCase()
232
- if (!normalized) return null
233
- if (["CREATED", "APPROVED", "PENDING"].includes(normalized)) return "authorized"
234
- if (["VOIDED", "EXPIRED"].includes(normalized)) return "canceled"
235
- if (["DENIED", "DECLINED", "FAILED"].includes(normalized)) return "error"
236
- return null
237
- }
238
-
239
- protected mapOrderStatus(status?: string) {
240
- const normalized = String(status || "").toUpperCase()
241
- if (!normalized) return "pending"
242
- if (normalized === "COMPLETED") return "captured"
243
- if (normalized === "APPROVED") return "authorized"
244
- if (["VOIDED", "CANCELLED"].includes(normalized)) return "canceled"
245
- if (["CREATED", "SAVED", "PAYER_ACTION_REQUIRED"].includes(normalized)) return "pending"
246
- if (["FAILED", "EXPIRED"].includes(normalized)) return "error"
247
- return "pending"
248
- }
249
-
250
- async createAccountHolder(
251
- input: CreateAccountHolderInput
252
- ): Promise<CreateAccountHolderOutput> {
253
- const customerId = input.context?.customer?.id
254
- const externalId = customerId
255
- ? `paypal_${customerId}`
256
- : `paypal_${this.generateSessionId()}`
257
- return {
258
- id: externalId,
259
- data: {
260
- email: input.context?.customer?.email || null,
261
- customer_id: customerId || null,
262
- },
263
- }
264
- }
265
-
266
- async deletePayment(_input: DeletePaymentInput): Promise<DeletePaymentOutput> {
267
- return { data: {} }
268
- }
269
-
270
- async getWebhookActionAndData(
271
- payload: ProviderWebhookPayload["payload"]
272
- ): Promise<WebhookActionResult> {
273
- return getPayPalWebhookActionAndData(payload)
274
- }
275
- }
1
+ import { AbstractPaymentProvider, MedusaError } from "@medusajs/framework/utils"
2
+ import { randomUUID } from "crypto"
3
+ import type {
4
+ CapturePaymentInput,
5
+ CapturePaymentOutput,
6
+ CreateAccountHolderInput,
7
+ CreateAccountHolderOutput,
8
+ DeletePaymentInput,
9
+ DeletePaymentOutput,
10
+ ProviderWebhookPayload,
11
+ WebhookActionResult,
12
+ } from "@medusajs/framework/types"
13
+ import {
14
+ formatAmountForPayPal,
15
+ getCurrencyExponent,
16
+ toAmountNumber,
17
+ } from "../utils/amounts"
18
+ import {
19
+ assertPayPalCurrencySupported,
20
+ normalizeCurrencyCode,
21
+ } from "../utils/currencies"
22
+ import { PayPalCredentialResolver } from "../utils/credential-resolver"
23
+ import { PAYPAL_PARTNER_ATTRIBUTION_ID } from "../utils/partner"
24
+ import { paypalFetch, paypalFetchWithRetry } from "../utils/paypal-fetch"
25
+ import { getPayPalWebhookActionAndData } from "./webhook-utils"
26
+ import {
27
+ extractCaptureStatus,
28
+ isCaptureCompleted,
29
+ mapPayPalCaptureStatus,
30
+ sumCountedCaptureAmounts,
31
+ sumSettledCaptureAmounts,
32
+ } from "./status-utils"
33
+
34
+ /** Compact record of one PayPal capture kept on the session (`paypal.captures`). */
35
+ type StoredCaptureEntry = {
36
+ id?: string
37
+ status?: string
38
+ amount?: unknown
39
+ final_capture?: boolean
40
+ raw?: unknown
41
+ }
42
+
43
+ function toStoredCaptureEntry(capture: any): StoredCaptureEntry {
44
+ return {
45
+ id: capture?.id,
46
+ status: capture?.status,
47
+ amount: capture?.amount,
48
+ final_capture: capture?.final_capture,
49
+ raw: capture,
50
+ }
51
+ }
52
+
53
+ /** Merge capture entries by id — a later entry for the same id wins. */
54
+ function mergeCaptureEntries(
55
+ ...lists: (StoredCaptureEntry[] | undefined)[]
56
+ ): StoredCaptureEntry[] {
57
+ const byId = new Map<string, StoredCaptureEntry>()
58
+ const anonymous: StoredCaptureEntry[] = []
59
+ for (const list of lists) {
60
+ for (const entry of list || []) {
61
+ if (entry?.id) byId.set(String(entry.id), entry)
62
+ else if (entry) anonymous.push(entry)
63
+ }
64
+ }
65
+ return [...byId.values(), ...anonymous]
66
+ }
67
+
68
+ export type Options = {}
69
+
70
+ /**
71
+ * Shared base for the two PayPal payment providers (wallet buttons and advanced
72
+ * card fields). Both providers ran nearly identical credential/token handling,
73
+ * order-detail fetching, idempotency-key generation, amount normalization, and
74
+ * PayPal→Medusa status mapping — that logic lives here once. Each provider
75
+ * supplies its own `sessionPrefix` / `idempotencyPrefix` and keeps the pieces
76
+ * that genuinely differ (create/authorize/capture/refund/cancel business logic,
77
+ * metric recording, 3-D Secure handling, provider-id passthrough).
78
+ */
79
+ export abstract class PayPalProviderBase extends AbstractPaymentProvider<Options> {
80
+ protected readonly options_: Options
81
+ protected paypal: PayPalCredentialResolver
82
+
83
+ /** Prefix for generated session ids (e.g. "pp" or "pp_card"). */
84
+ protected abstract readonly sessionPrefix: string
85
+ /** Prefix for generated idempotency keys (e.g. "pp" or "pp-card"). */
86
+ protected abstract readonly idempotencyPrefix: string
87
+
88
+ constructor(cradle: Record<string, any>, options: Options) {
89
+ super(cradle, options)
90
+ this.options_ = options
91
+ const pg = PayPalProviderBase.resolvePgConnection(cradle)
92
+ this.paypal = new PayPalCredentialResolver(pg)
93
+ }
94
+
95
+ protected static resolvePgConnection(cradle: Record<string, any>): any {
96
+ for (const key of ["__pg_connection__", "pgConnection", "pg_connection"]) {
97
+ try {
98
+ const val = cradle[key]
99
+ if (val) return val
100
+ } catch {}
101
+ }
102
+ throw new Error(
103
+ "Could not resolve pgConnection from the payment module container. " +
104
+ "Ensure the paypal module is registered in medusa-config and the database is accessible."
105
+ )
106
+ }
107
+
108
+ /** Serialize an error for audit metadata without losing cause chains. */
109
+ protected serializeError(error: unknown) {
110
+ if (error instanceof Error) {
111
+ const errorWithCause = error as Error & { cause?: unknown }
112
+ const cause = errorWithCause.cause
113
+ return {
114
+ name: error.name,
115
+ message: error.message,
116
+ stack: error.stack,
117
+ cause:
118
+ cause instanceof Error
119
+ ? { name: cause.name, message: cause.message, stack: cause.stack }
120
+ : cause,
121
+ }
122
+ }
123
+ return { message: String(error) }
124
+ }
125
+
126
+ protected async recordFailure(
127
+ eventType: string,
128
+ metadata?: Record<string, unknown>
129
+ ) {
130
+ await this.paypal.recordAuditEvent(eventType, metadata)
131
+ await this.paypal.recordMetric(eventType, metadata)
132
+ }
133
+
134
+ protected async recordSuccess(metricName: string) {
135
+ await this.paypal.recordMetric(metricName)
136
+ }
137
+
138
+ protected async recordPaymentEvent(
139
+ eventType: string,
140
+ metadata?: Record<string, unknown>
141
+ ) {
142
+ await this.paypal.recordAuditEvent(eventType, metadata)
143
+ }
144
+
145
+ protected generateSessionId(): string {
146
+ try {
147
+ return randomUUID()
148
+ } catch {
149
+ return `${this.sessionPrefix}_${Date.now()}_${Math.random().toString(16).slice(2)}`
150
+ }
151
+ }
152
+
153
+ async resolveSettings() {
154
+ return this.paypal.getSettings()
155
+ }
156
+
157
+ protected async resolveCurrencyOverride(): Promise<string> {
158
+ const { apiDetails } = await this.resolveSettings()
159
+ const code = apiDetails.currency_code
160
+ if (typeof code === "string" && code.trim()) {
161
+ return normalizeCurrencyCode(code)
162
+ }
163
+ return normalizeCurrencyCode(process.env.PAYPAL_CURRENCY || "EUR")
164
+ }
165
+
166
+ protected async getPayPalAccessToken() {
167
+ return this.paypal.getAccessToken()
168
+ }
169
+
170
+ protected async getOrderDetails(orderId: string) {
171
+ const { accessToken, base } = await this.getPayPalAccessToken()
172
+ const resp = await paypalFetch(
173
+ `${base}/v2/checkout/orders/${encodeURIComponent(orderId)}`,
174
+ {
175
+ method: "GET",
176
+ headers: {
177
+ Authorization: `Bearer ${accessToken}`,
178
+ "Content-Type": "application/json",
179
+ "PayPal-Partner-Attribution-Id": PAYPAL_PARTNER_ATTRIBUTION_ID,
180
+ },
181
+ }
182
+ )
183
+
184
+ const text = await resp.text()
185
+ if (!resp.ok) {
186
+ throw new Error(`PayPal get order error (${resp.status}): ${text}`)
187
+ }
188
+
189
+ return JSON.parse(text)
190
+ }
191
+
192
+ protected getIdempotencyKey(
193
+ input: { context?: { idempotency_key?: string } },
194
+ suffix: string
195
+ ): string {
196
+ const key = input?.context?.idempotency_key?.trim()
197
+ if (key) {
198
+ return `${key}-${suffix}`
199
+ }
200
+ return `${this.idempotencyPrefix}-${suffix}-${this.generateSessionId()}`
201
+ }
202
+
203
+ protected async normalizePaymentData(input: {
204
+ data?: Record<string, unknown>
205
+ }) {
206
+ const data = (input.data || {}) as Record<string, any>
207
+ const amount = toAmountNumber(data.amount)
208
+ const currencyOverride = await this.resolveCurrencyOverride()
209
+ const currencyCode = normalizeCurrencyCode(
210
+ data.currency_code || currencyOverride || "EUR"
211
+ )
212
+ assertPayPalCurrencySupported({
213
+ currencyCode,
214
+ paypalCurrencyOverride: currencyOverride,
215
+ })
216
+ return { data, amount, currencyCode }
217
+ }
218
+
219
+ protected formatAmount(amount: number, currencyCode?: string): string {
220
+ return formatAmountForPayPal(amount, currencyCode || "EUR")
221
+ }
222
+
223
+ /**
224
+ * Amount to send to PayPal for a capture. Medusa invokes the provider's
225
+ * capturePayment with only `{ data, context: { idempotency_key } }` — the
226
+ * admin's requested (possibly partial) capture amount is never passed in the
227
+ * input. The idempotency_key IS the Medusa `capture` row id, so resolve the
228
+ * requested amount from that row; otherwise a partial capture would silently
229
+ * charge the buyer the full session total. Falls back to the session amount
230
+ * when the row can't be resolved (preserving full-capture behavior), and
231
+ * never returns more than the session amount.
232
+ */
233
+ protected async resolveRequestedCaptureAmount(
234
+ input: { context?: { idempotency_key?: string } },
235
+ sessionAmount: number
236
+ ): Promise<number> {
237
+ const captureRowId = input?.context?.idempotency_key?.trim()
238
+ if (!captureRowId) return sessionAmount
239
+ const requested = await this.paypal.getRequestedCaptureAmount(captureRowId)
240
+ if (requested === null || !Number.isFinite(requested) || requested <= 0) {
241
+ return sessionAmount
242
+ }
243
+ return Math.min(requested, sessionAmount)
244
+ }
245
+
246
+ /**
247
+ * When the session amount or currency changes while a not-yet-approved PayPal
248
+ * order is stored on the session, drop the stored order reference so the next
249
+ * create-order call mints a fresh order at the correct total. Without this, a
250
+ * buyer who opens PayPal (order created for the old total), backs out, and
251
+ * changes the cart gets charged the stale amount. Returns a `{ paypal }`
252
+ * patch to spread into the updated session data, or `{}` when nothing needs
253
+ * invalidating. Sessions that already carry a capture/authorization are never
254
+ * touched.
255
+ */
256
+ protected invalidateStaleOrder(
257
+ input: { data?: Record<string, unknown>; amount?: unknown },
258
+ nextCurrencyCode: string
259
+ ): Record<string, unknown> {
260
+ const data = (input.data || {}) as Record<string, any>
261
+ const paypal = (data.paypal || {}) as Record<string, any>
262
+ if (!paypal.order_id) return {}
263
+ if (paypal.capture_id || paypal.authorization_id) return {}
264
+ const prevAmount = toAmountNumber(data.amount)
265
+ const nextAmount = toAmountNumber(input.amount)
266
+ const prevCurrency = String(data.currency_code || "").toUpperCase()
267
+ const amountChanged =
268
+ prevAmount > 0 && nextAmount > 0 && prevAmount !== nextAmount
269
+ const currencyChanged = !!prevCurrency && prevCurrency !== nextCurrencyCode
270
+ if (!amountChanged && !currencyChanged) return {}
271
+ const { order_id: _orderId, order: _order, ...rest } = paypal
272
+ return { paypal: rest }
273
+ }
274
+
275
+ protected mapCaptureStatus(status?: string) {
276
+ // Delegate to the shared, unit-tested mapping so the card and wallet
277
+ // providers agree with each other and with the webhook processor. Notably a
278
+ // PARTIALLY_REFUNDED capture must stay "captured" (only part of the funds
279
+ // were returned) — mapping it to "canceled" would wrongly unwind a live
280
+ // capture.
281
+ return mapPayPalCaptureStatus(status)
282
+ }
283
+
284
+ protected mapAuthorizationStatus(status?: string) {
285
+ const normalized = String(status || "").toUpperCase()
286
+ if (!normalized) return null
287
+ if (["CREATED", "APPROVED", "PENDING"].includes(normalized))
288
+ return "authorized"
289
+ if (["VOIDED", "EXPIRED"].includes(normalized)) return "canceled"
290
+ if (["DENIED", "DECLINED", "FAILED"].includes(normalized)) return "error"
291
+ return null
292
+ }
293
+
294
+ protected mapOrderStatus(status?: string) {
295
+ const normalized = String(status || "").toUpperCase()
296
+ if (!normalized) return "pending"
297
+ if (normalized === "COMPLETED") return "captured"
298
+ if (normalized === "APPROVED") return "authorized"
299
+ if (["VOIDED", "CANCELLED"].includes(normalized)) return "canceled"
300
+ if (["CREATED", "SAVED", "PAYER_ACTION_REQUIRED"].includes(normalized))
301
+ return "pending"
302
+ if (["FAILED", "EXPIRED"].includes(normalized)) return "error"
303
+ return "pending"
304
+ }
305
+
306
+ /**
307
+ * Capture funds for a session — one PayPal capture per Medusa capture row.
308
+ *
309
+ * Medusa calls this once per admin capture (full or partial) with the
310
+ * requested amount living on the Medusa capture row (see
311
+ * `resolveRequestedCaptureAmount`). The decision to call PayPal is driven by
312
+ * what PayPal already holds for the order, NOT by whether the session happens
313
+ * to carry a `capture_id`: after a first partial capture the session always
314
+ * has one, and short-circuiting on it silently skipped every later capture
315
+ * (Medusa recorded the money, PayPal never took it).
316
+ *
317
+ * - Order already fully captured at PayPal → idempotent success with the
318
+ * latest COMPLETED capture (a retry after a crash between the PayPal call
319
+ * and the session write, or a storefront capture-order that Medusa never
320
+ * saw). If everything it holds is still PENDING, fail — funds in flight
321
+ * are not settled money.
322
+ * - Otherwise capture exactly the requested amount; refuse (rather than
323
+ * silently clamp) if more than what remains capturable is requested, since
324
+ * Medusa records the requested amount regardless of what is returned.
325
+ * - The last capture that exhausts the session amount closes the
326
+ * authorization (`final_capture`), unless the session says otherwise.
327
+ */
328
+ async capturePayment(
329
+ input: CapturePaymentInput
330
+ ): Promise<CapturePaymentOutput> {
331
+ const data = (input.data || {}) as Record<string, any>
332
+ const paypalData = (data.paypal || {}) as Record<string, any>
333
+ const orderId = String(paypalData.order_id || data.order_id || "")
334
+ let authorizationId = String(
335
+ paypalData.authorization_id || data.authorization_id || ""
336
+ )
337
+ if (!orderId) {
338
+ throw new MedusaError(
339
+ MedusaError.Types.INVALID_DATA,
340
+ "PayPal order_id is required to capture payment"
341
+ )
342
+ }
343
+
344
+ const { amount: sessionAmount, currencyCode } =
345
+ await this.normalizePaymentData(input)
346
+ const exponent = getCurrencyExponent(currencyCode)
347
+ const roundMoney = (value: number) => Number(value.toFixed(exponent))
348
+ // The requested (possibly partial) capture amount lives on the Medusa
349
+ // capture row, not in the provider input — resolve it so partial captures
350
+ // don't charge the full session total.
351
+ const amount = await this.resolveRequestedCaptureAmount(
352
+ input,
353
+ sessionAmount
354
+ )
355
+ // Include the amount in the idempotency suffix: PayPal deduplicates by
356
+ // PayPal-Request-Id, so two sequential partial captures of the same order
357
+ // that share an upstream idempotency_key would otherwise collide and the
358
+ // second capture would silently return the first one's result.
359
+ const requestId = this.getIdempotencyKey(
360
+ input,
361
+ `capture-${orderId}-${amount}`
362
+ )
363
+ let debugId: string | null = null
364
+
365
+ const storedCaptures: StoredCaptureEntry[] = Array.isArray(
366
+ paypalData.captures
367
+ )
368
+ ? paypalData.captures
369
+ : []
370
+
371
+ const successResult = (
372
+ capture: any,
373
+ liveCaptures: any[],
374
+ newEntry?: StoredCaptureEntry
375
+ ): CapturePaymentOutput => {
376
+ const captureId =
377
+ capture?.id || capture?.purchase_units?.[0]?.payments?.captures?.[0]?.id
378
+ return {
379
+ data: {
380
+ ...(input.data || {}),
381
+ paypal: {
382
+ ...paypalData,
383
+ order_id: orderId,
384
+ capture_id: captureId,
385
+ capture,
386
+ authorization_id: authorizationId || paypalData.authorization_id,
387
+ captures: mergeCaptureEntries(
388
+ storedCaptures,
389
+ liveCaptures.map(toStoredCaptureEntry),
390
+ newEntry ? [newEntry] : undefined
391
+ ),
392
+ },
393
+ captured_at: new Date().toISOString(),
394
+ },
395
+ }
396
+ }
397
+
398
+ try {
399
+ const { accessToken, base } = await this.getPayPalAccessToken()
400
+ const order = await this.getOrderDetails(orderId).catch(() => null)
401
+ const liveCaptures: any[] =
402
+ order?.purchase_units?.[0]?.payments?.captures ?? []
403
+
404
+ if (order) {
405
+ // What PayPal has already taken (or reserved) for this order, and how
406
+ // much of it is settled.
407
+ const alreadyCaptured = roundMoney(
408
+ sumCountedCaptureAmounts(liveCaptures)
409
+ )
410
+ const settled = roundMoney(sumSettledCaptureAmounts(liveCaptures))
411
+ const remaining = roundMoney(sessionAmount - alreadyCaptured)
412
+ const requested = roundMoney(amount)
413
+
414
+ // Reconcile against Medusa's own ledger. Medusa creates the capture row
415
+ // BEFORE calling us and deletes it when the call (or its follow-up
416
+ // write) fails, so a retry arrives with a fresh row and a fresh
417
+ // PayPal-Request-Id. Whatever PayPal holds beyond the captures Medusa
418
+ // has booked on this payment is therefore a capture Medusa lost —
419
+ // that money IS this capture, and must not be taken from the buyer a
420
+ // second time. (Also covers a storefront capture-order the session
421
+ // never recorded.) Falls through to the amount-based checks below when
422
+ // the ledger can't be read.
423
+ const captureRowId = input?.context?.idempotency_key?.trim() || ""
424
+ const booked = captureRowId
425
+ ? await this.paypal.getBookedCaptureTotal(captureRowId)
426
+ : null
427
+ const unbookedHeld =
428
+ booked === null ? 0 : roundMoney(alreadyCaptured - booked)
429
+ const unbookedSettled =
430
+ booked === null ? 0 : roundMoney(settled - booked)
431
+
432
+ const pickCompletedCapture = () =>
433
+ [...liveCaptures]
434
+ .reverse()
435
+ .find(
436
+ (c) =>
437
+ isCaptureCompleted(c) &&
438
+ roundMoney(Number(c?.amount?.value)) === requested
439
+ ) ?? [...liveCaptures].reverse().find((c) => isCaptureCompleted(c))
440
+
441
+ if (booked !== null && unbookedHeld >= requested && requested > 0) {
442
+ const completed = pickCompletedCapture()
443
+ if (!completed || unbookedSettled < requested) {
444
+ // The unbooked money is still PENDING (eCheck / review): not
445
+ // settled, so it can't be booked yet — the CAPTURE.COMPLETED
446
+ // webhook settles it later.
447
+ throw new Error(
448
+ `PayPal already holds ${formatAmountForPayPal(unbookedHeld, currencyCode)} ${currencyCode} for order ${orderId} that Medusa has not booked, ` +
449
+ `but only ${formatAmountForPayPal(unbookedSettled, currencyCode)} of it has COMPLETED (statuses: ${
450
+ liveCaptures.map((c) => c?.status).join(", ") || "none"
451
+ }). The payment was not recorded as captured.`
452
+ )
453
+ }
454
+ console.info(
455
+ `[PayPal] capturePayment: order ${orderId} already holds ${unbookedHeld} ${currencyCode} not booked in Medusa (PayPal ${alreadyCaptured}, Medusa ${booked}); returning capture ${completed.id} instead of capturing again`
456
+ )
457
+ return successResult(completed, liveCaptures)
458
+ }
459
+
460
+ if (remaining <= 0) {
461
+ // Nothing left to capture at PayPal. Only settled money may be
462
+ // booked: a PENDING capture that fills the remainder is not
463
+ // captured yet.
464
+ const completed = pickCompletedCapture()
465
+ if (!completed || settled < roundMoney(sessionAmount)) {
466
+ throw new Error(
467
+ `PayPal already holds captures covering the full amount for order ${orderId}, ` +
468
+ `but only ${formatAmountForPayPal(settled, currencyCode)} ${currencyCode} has COMPLETED (statuses: ${
469
+ liveCaptures.map((c) => c?.status).join(", ") || "none"
470
+ }). The payment was not recorded as captured.`
471
+ )
472
+ }
473
+ console.info(
474
+ `[PayPal] capturePayment: order ${orderId} is already fully captured at PayPal (${alreadyCaptured} ${currencyCode}); returning capture ${completed.id}`
475
+ )
476
+ return successResult(completed, liveCaptures)
477
+ }
478
+
479
+ if (requested > remaining) {
480
+ throw new Error(
481
+ `PayPal can only capture ${formatAmountForPayPal(remaining, currencyCode)} ${currencyCode} more for order ${orderId} ` +
482
+ `(${formatAmountForPayPal(alreadyCaptured, currencyCode)} of ${formatAmountForPayPal(sessionAmount, currencyCode)} already captured); ` +
483
+ `${formatAmountForPayPal(amount, currencyCode)} was requested.`
484
+ )
485
+ }
486
+ } else {
487
+ // PayPal unreachable for the order lookup: the only safe short-circuit
488
+ // is a stored capture that demonstrably COMPLETED for the full session
489
+ // amount. Anything else proceeds to the capture call below, where the
490
+ // PayPal-Request-Id keeps a retry idempotent and PayPal itself rejects
491
+ // an over-capture.
492
+ const stored = paypalData.capture
493
+ const storedAmount = Number(
494
+ stored?.amount?.value ??
495
+ stored?.purchase_units?.[0]?.payments?.captures?.[0]?.amount?.value
496
+ )
497
+ if (
498
+ stored &&
499
+ isCaptureCompleted(stored) &&
500
+ Number.isFinite(storedAmount) &&
501
+ roundMoney(storedAmount) >= roundMoney(sessionAmount)
502
+ ) {
503
+ return successResult(stored, [])
504
+ }
505
+ }
506
+
507
+ const resolvedIntent = String(
508
+ order?.intent || paypalData.order?.intent || data.intent || ""
509
+ ).toUpperCase()
510
+
511
+ if (!authorizationId && resolvedIntent === "AUTHORIZE") {
512
+ const liveAuthorizationId =
513
+ order?.purchase_units?.[0]?.payments?.authorizations?.[0]?.id
514
+ if (liveAuthorizationId) {
515
+ authorizationId = String(liveAuthorizationId)
516
+ } else {
517
+ const authorizeResp = await paypalFetch(
518
+ `${base}/v2/checkout/orders/${encodeURIComponent(orderId)}/authorize`,
519
+ {
520
+ method: "POST",
521
+ headers: {
522
+ Authorization: `Bearer ${accessToken}`,
523
+ "Content-Type": "application/json",
524
+ "PayPal-Request-Id": `${requestId}-auth`,
525
+ "PayPal-Partner-Attribution-Id": PAYPAL_PARTNER_ATTRIBUTION_ID,
526
+ },
527
+ }
528
+ )
529
+ const authorizeText = await authorizeResp.text()
530
+ debugId = authorizeResp.headers.get("paypal-debug-id")
531
+ if (!authorizeResp.ok) {
532
+ throw new Error(
533
+ `PayPal authorize order error (${authorizeResp.status}): ${authorizeText}${
534
+ debugId ? ` debug_id=${debugId}` : ""
535
+ }`
536
+ )
537
+ }
538
+ const authorization = JSON.parse(authorizeText)
539
+ authorizationId =
540
+ authorization?.purchase_units?.[0]?.payments?.authorizations?.[0]
541
+ ?.id
542
+ }
543
+ }
544
+
545
+ const explicitFinalCapture =
546
+ paypalData.is_final_capture ??
547
+ data.is_final_capture ??
548
+ data.final_capture ??
549
+ undefined
550
+ const captureValue =
551
+ amount > 0 ? formatAmountForPayPal(amount, currencyCode) : null
552
+
553
+ // `amount` and `final_capture` are only honored on the authorizations
554
+ // capture endpoint. The orders capture endpoint always captures the FULL
555
+ // order and silently ignores an `amount` body — so a partial amount there
556
+ // would over-capture while we record the smaller requested value. Route
557
+ // partial captures through the authorization, and fail closed if a
558
+ // partial capture is attempted against a capture-intent order.
559
+ let capturePayload: Record<string, unknown>
560
+ let captureUrl: string
561
+ if (authorizationId) {
562
+ captureUrl = `${base}/v2/payments/authorizations/${encodeURIComponent(authorizationId)}/capture`
563
+ // Close the authorization once the session amount is exhausted, unless
564
+ // the session explicitly says otherwise.
565
+ const finalCapture =
566
+ typeof explicitFinalCapture === "boolean"
567
+ ? explicitFinalCapture
568
+ : order
569
+ ? roundMoney(sumCountedCaptureAmounts(liveCaptures) + amount) >=
570
+ roundMoney(sessionAmount)
571
+ : undefined
572
+ capturePayload = {
573
+ ...(captureValue
574
+ ? { amount: { currency_code: currencyCode, value: captureValue } }
575
+ : {}),
576
+ ...(typeof finalCapture === "boolean"
577
+ ? { final_capture: finalCapture }
578
+ : {}),
579
+ }
580
+ } else {
581
+ captureUrl = `${base}/v2/checkout/orders/${encodeURIComponent(orderId)}/capture`
582
+ capturePayload = {}
583
+ const orderTotal = order?.purchase_units?.[0]?.amount?.value
584
+ if (captureValue && orderTotal && captureValue !== String(orderTotal)) {
585
+ throw new Error(
586
+ `PayPal partial capture (${captureValue} ${currencyCode}) is not supported for ` +
587
+ `capture-intent orders (order total ${orderTotal}). Create the order with intent ` +
588
+ `AUTHORIZE to capture a partial amount.`
589
+ )
590
+ }
591
+ }
592
+
593
+ // Retry transient 5xx/429/timeout: the PayPal-Request-Id makes the
594
+ // capture idempotent, so a retry after a network blip re-uses the same
595
+ // capture instead of double-charging. `Prefer: return=representation`
596
+ // asks for the full capture resource (amount, final_capture, …) instead
597
+ // of the default id/status/links stub, so the session keeps a usable
598
+ // record of every capture.
599
+ const ppResp = await paypalFetchWithRetry(captureUrl, {
600
+ method: "POST",
601
+ headers: {
602
+ Authorization: `Bearer ${accessToken}`,
603
+ "Content-Type": "application/json",
604
+ Prefer: "return=representation",
605
+ "PayPal-Request-Id": requestId,
606
+ "PayPal-Partner-Attribution-Id": PAYPAL_PARTNER_ATTRIBUTION_ID,
607
+ },
608
+ body: JSON.stringify(capturePayload),
609
+ })
610
+
611
+ const ppText = await ppResp.text()
612
+ debugId = ppResp.headers.get("paypal-debug-id")
613
+ if (!ppResp.ok) {
614
+ throw new Error(
615
+ `PayPal capture error (${ppResp.status}): ${ppText}${
616
+ debugId ? ` debug_id=${debugId}` : ""
617
+ }`
618
+ )
619
+ }
620
+
621
+ const capture = JSON.parse(ppText)
622
+
623
+ // A 2xx response does NOT mean the funds were captured. PayPal returns 201
624
+ // for captures that are PENDING (pending review / eCheck), DECLINED, or
625
+ // FAILED. Recording any of these as "captured" books money that never
626
+ // settled, so only a COMPLETED capture is treated as success.
627
+ const captureStatus = extractCaptureStatus(capture)
628
+ if (captureStatus !== "COMPLETED") {
629
+ throw new Error(
630
+ `PayPal capture did not complete (status=${captureStatus || "UNKNOWN"}). ` +
631
+ `The payment was not captured.${debugId ? ` debug_id=${debugId}` : ""}`
632
+ )
633
+ }
634
+
635
+ const captureResource = authorizationId
636
+ ? capture
637
+ : (capture?.purchase_units?.[0]?.payments?.captures?.[0] ?? capture)
638
+ const captureId = captureResource?.id || capture?.id
639
+
640
+ await this.recordSuccess("capture_success")
641
+ await this.recordPaymentEvent("capture", {
642
+ order_id: orderId,
643
+ capture_id: captureId,
644
+ authorization_id: authorizationId || undefined,
645
+ amount,
646
+ currency_code: currencyCode,
647
+ request_id: requestId,
648
+ })
649
+
650
+ return successResult(capture, liveCaptures, {
651
+ ...toStoredCaptureEntry(captureResource),
652
+ id: captureId,
653
+ raw: capture,
654
+ })
655
+ } catch (error: any) {
656
+ await this.recordFailure("capture_failed", {
657
+ order_id: orderId,
658
+ request_id: requestId,
659
+ debug_id: debugId,
660
+ message: error?.message,
661
+ })
662
+ // Surface the real reason: Medusa masks non-MedusaErrors as a generic
663
+ // "unknown error" in production, hiding the PayPal failure.
664
+ throw error instanceof MedusaError
665
+ ? error
666
+ : new MedusaError(
667
+ MedusaError.Types.INVALID_DATA,
668
+ error?.message || "PayPal capture failed."
669
+ )
670
+ }
671
+ }
672
+
673
+ async createAccountHolder(
674
+ input: CreateAccountHolderInput
675
+ ): Promise<CreateAccountHolderOutput> {
676
+ const customerId = input.context?.customer?.id
677
+ const externalId = customerId
678
+ ? `paypal_${customerId}`
679
+ : `paypal_${this.generateSessionId()}`
680
+ return {
681
+ id: externalId,
682
+ data: {
683
+ email: input.context?.customer?.email || null,
684
+ customer_id: customerId || null,
685
+ },
686
+ }
687
+ }
688
+
689
+ async deletePayment(
690
+ _input: DeletePaymentInput
691
+ ): Promise<DeletePaymentOutput> {
692
+ return { data: {} }
693
+ }
694
+
695
+ async getWebhookActionAndData(
696
+ payload: ProviderWebhookPayload["payload"]
697
+ ): Promise<WebhookActionResult> {
698
+ return getPayPalWebhookActionAndData(payload)
699
+ }
700
+ }