@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,836 +1,673 @@
1
- import { MedusaError } from "@medusajs/framework/utils"
2
- import type {
3
- AuthorizePaymentInput,
4
- AuthorizePaymentOutput,
5
- CapturePaymentInput,
6
- CapturePaymentOutput,
7
- CancelPaymentInput,
8
- CancelPaymentOutput,
9
- GetPaymentStatusInput,
10
- GetPaymentStatusOutput,
11
- InitiatePaymentInput,
12
- InitiatePaymentOutput,
13
- RefundPaymentInput,
14
- RefundPaymentOutput,
15
- RetrievePaymentInput,
16
- RetrievePaymentOutput,
17
- UpdatePaymentInput,
18
- UpdatePaymentOutput,
19
- } from "@medusajs/framework/types"
20
- import { formatAmountForPayPal, toAmountNumber } from "../utils/amounts"
21
- import {
22
- assertPayPalCurrencySupported,
23
- normalizeCurrencyCode,
24
- } from "../utils/currencies"
25
- import { PAYPAL_PARTNER_ATTRIBUTION_ID } from "../utils/partner"
26
- import { paypalFetch, paypalFetchWithRetry } from "../utils/paypal-fetch"
27
- import {
28
- extractCaptureStatus,
29
- isCaptureCompleted,
30
- isRefundFailureStatus,
31
- } from "./status-utils"
32
- import { PayPalProviderBase } from "./base-provider"
33
-
34
- class PayPalPaymentProvider extends PayPalProviderBase {
35
- static identifier = "paypal"
36
-
37
- protected readonly sessionPrefix = "pp"
38
- protected readonly idempotencyPrefix = "pp"
39
-
40
- async initiatePayment(input: InitiatePaymentInput): Promise<InitiatePaymentOutput> {
41
- const providerId = (input.data as Record<string, any> | undefined)?.provider_id
42
- try {
43
- const currencyOverride = await this.resolveCurrencyOverride()
44
- const currencyCode = normalizeCurrencyCode(
45
- input.currency_code || currencyOverride || "EUR"
46
- )
47
- assertPayPalCurrencySupported({
48
- currencyCode,
49
- paypalCurrencyOverride: currencyOverride,
50
- })
51
- return {
52
- id: this.generateSessionId(),
53
- data: {
54
- ...(input.data || {}),
55
- ...(providerId ? { provider_id: providerId } : {}),
56
- amount: input.amount,
57
- currency_code: currencyCode,
58
- },
59
- }
60
- } catch (error) {
61
- await this.recordFailure("initiate_failed", {
62
- error: this.serializeError(error),
63
- currency_code: input.currency_code,
64
- amount: input.amount,
65
- provider_id: providerId,
66
- data: input.data ?? null,
67
- })
68
- throw error
69
- }
70
- }
71
-
72
- async updatePayment(input: UpdatePaymentInput): Promise<UpdatePaymentOutput> {
73
- const currencyOverride = await this.resolveCurrencyOverride()
74
- const currencyCode = normalizeCurrencyCode(
75
- input.currency_code || currencyOverride || "EUR"
76
- )
77
- assertPayPalCurrencySupported({
78
- currencyCode,
79
- paypalCurrencyOverride: currencyOverride,
80
- })
81
- const providerId = (input.data as Record<string, any> | undefined)?.provider_id
82
- return {
83
- data: {
84
- ...(input.data || {}),
85
- ...this.invalidateStaleOrder(input, currencyCode),
86
- ...(providerId ? { provider_id: providerId } : {}),
87
- amount: input.amount,
88
- currency_code: currencyCode,
89
- },
90
- }
91
- }
92
-
93
- async authorizePayment(
94
- input: AuthorizePaymentInput
95
- ): Promise<AuthorizePaymentOutput> {
96
- const { data } = await this.normalizePaymentData(input)
97
- const existingPayPal = (data.paypal || {}) as Record<string, any>
98
-
99
- // Session already carries a settled capture: trust it without a network
100
- // round-trip. The stored capture object is only written after a COMPLETED
101
- // gate (capture-order route / capturePayment), but re-verify its status
102
- // here so a PENDING/DECLINED capture patched in by a webhook is never
103
- // booked as captured money.
104
- const storedCaptureStatus = extractCaptureStatus(existingPayPal.capture)
105
- if (storedCaptureStatus === "COMPLETED") {
106
- console.info("[PayPal] authorizePayment: session already captured (COMPLETED)")
107
- return {
108
- status: "captured",
109
- data: {
110
- ...(input.data || {}),
111
- captured_at: (data as any).captured_at || new Date().toISOString(),
112
- },
113
- }
114
- }
115
-
116
- const orderId = String(existingPayPal.order_id || data.order_id || "")
117
- if (orderId) {
118
- try {
119
- console.info("[PayPal] authorizePayment: fetching live order status for", orderId)
120
- const order = await this.getOrderDetails(orderId)
121
- const capture = order?.purchase_units?.[0]?.payments?.captures?.[0]
122
- const authorization = order?.purchase_units?.[0]?.payments?.authorizations?.[0]
123
-
124
- // Derive the returned status from what actually happened at PayPal —
125
- // NOT from the mere presence of a capture/authorization id and NOT
126
- // from the merchant's configured paymentAction. A PENDING capture
127
- // (eCheck / pending review) must not be booked as captured, and a
128
- // DENIED/DECLINED one must fail the authorization outright.
129
- if (capture?.id) {
130
- const captureStatus = this.mapCaptureStatus(capture?.status)
131
- if (captureStatus === "captured") {
132
- return {
133
- status: "captured",
134
- data: {
135
- ...(input.data || {}),
136
- paypal: {
137
- ...existingPayPal,
138
- order_id: orderId,
139
- order,
140
- authorization_id: authorization?.id || existingPayPal.authorization_id,
141
- capture_id: capture.id,
142
- capture,
143
- },
144
- captured_at: new Date().toISOString(),
145
- },
146
- }
147
- }
148
- if (captureStatus === "pending") {
149
- // Funds are in flight (eCheck etc.): place the order as authorized
150
- // so checkout completes, but never mark it captured — the
151
- // CAPTURE.COMPLETED webhook settles it later.
152
- return {
153
- status: "authorized",
154
- data: {
155
- ...(input.data || {}),
156
- paypal: {
157
- ...existingPayPal,
158
- order_id: orderId,
159
- order,
160
- capture_id: capture.id,
161
- },
162
- authorized_at: new Date().toISOString(),
163
- },
164
- }
165
- }
166
- if (captureStatus === "error" || captureStatus === "canceled") {
167
- return {
168
- status: "error",
169
- data: {
170
- ...(input.data || {}),
171
- paypal: { ...existingPayPal, order_id: orderId, order },
172
- },
173
- }
174
- }
175
- }
176
-
177
- if (authorization?.id) {
178
- const authStatus = this.mapAuthorizationStatus(authorization?.status)
179
- if (authStatus === "authorized") {
180
- return {
181
- status: "authorized",
182
- data: {
183
- ...(input.data || {}),
184
- paypal: {
185
- ...existingPayPal,
186
- order_id: orderId,
187
- order,
188
- authorization_id: authorization.id,
189
- },
190
- authorized_at: new Date().toISOString(),
191
- },
192
- }
193
- }
194
- if (authStatus === "error" || authStatus === "canceled") {
195
- return {
196
- status: "error",
197
- data: {
198
- ...(input.data || {}),
199
- paypal: { ...existingPayPal, order_id: orderId, order },
200
- },
201
- }
202
- }
203
- }
204
-
205
- // Only a buyer-APPROVED order counts as authorized. CREATED/SAVED
206
- // means the buyer never approved the payment — treating those as
207
- // authorized would let a cart complete with no funds authorized at
208
- // PayPal at all.
209
- if (String(order?.status || "").toUpperCase() === "APPROVED") {
210
- console.info("[PayPal] authorizePayment: order approved, marking authorized")
211
- return {
212
- status: "authorized",
213
- data: {
214
- ...(input.data || {}),
215
- paypal: {
216
- ...existingPayPal,
217
- order_id: orderId,
218
- order,
219
- },
220
- authorized_at: new Date().toISOString(),
221
- },
222
- }
223
- }
224
- } catch (e: any) {
225
- console.warn("[PayPal] authorizePayment: order lookup failed:", e?.message)
226
- // Fall back to the session's own record when PayPal is unreachable so a
227
- // transient lookup error doesn't fail a checkout that already has a
228
- // real authorization/capture behind it. `captured_at` is only ever
229
- // stamped after a COMPLETED gate; a bare capture_id (e.g. patched in by
230
- // a webhook) or authorization id maps to "authorized" — the order is
231
- // placed without claiming settled funds.
232
- if ((data as any).captured_at) {
233
- return {
234
- status: "captured",
235
- data: { ...(input.data || {}), captured_at: (data as any).captured_at },
236
- }
237
- }
238
- if (
239
- existingPayPal.capture_id ||
240
- existingPayPal.authorization_id ||
241
- (data as any).authorized_at
242
- ) {
243
- return {
244
- status: "authorized",
245
- data: {
246
- ...(input.data || {}),
247
- authorized_at: (data as any).authorized_at || new Date().toISOString(),
248
- },
249
- }
250
- }
251
- }
252
- }
253
-
254
- // No usable PayPal order on the session: nothing can be authorized. The
255
- // previous fallback created a brand-new PayPal order here and immediately
256
- // called /v2/checkout/orders/{id}/authorize on it — but an order no buyer
257
- // has approved can never be authorized (PayPal rejects it with
258
- // ORDER_NOT_APPROVED), so that path only produced confusing 422s and
259
- // orphaned PayPal orders. Fail with a clear, actionable error instead.
260
- await this.recordFailure("authorize_failed", {
261
- cart_id: data.cart_id,
262
- payment_collection_id: data.payment_collection_id,
263
- message: "no approved PayPal order on session",
264
- })
265
- throw new MedusaError(
266
- MedusaError.Types.NOT_ALLOWED,
267
- "No approved PayPal payment was found for this session. The buyer must approve the payment with PayPal before the cart can be completed."
268
- )
269
- }
270
-
271
- async retrievePayment(input: RetrievePaymentInput): Promise<RetrievePaymentOutput> {
272
- const data = (input.data || {}) as Record<string, any>
273
- const paypalData = (data.paypal || {}) as Record<string, any>
274
- const orderId = String(paypalData.order_id || data.order_id || "")
275
- if (!orderId) {
276
- return { data: { ...(input.data || {}) } }
277
- }
278
-
279
- const order = await this.getOrderDetails(orderId)
280
- const capture = order?.purchase_units?.[0]?.payments?.captures?.[0]
281
- const authorization = order?.purchase_units?.[0]?.payments?.authorizations?.[0]
282
-
283
- return {
284
- data: {
285
- ...(input.data || {}),
286
- paypal: {
287
- ...((input.data || {}).paypal as Record<string, unknown>),
288
- order,
289
- authorization_id: authorization?.id || paypalData.authorization_id,
290
- capture_id: capture?.id || paypalData.capture_id,
291
- },
292
- },
293
- }
294
- }
295
-
296
- async getPaymentStatus(input: GetPaymentStatusInput): Promise<GetPaymentStatusOutput> {
297
- const data = (input.data || {}) as Record<string, any>
298
- const paypalData = (data.paypal || {}) as Record<string, any>
299
- const orderId = String(paypalData.order_id || data.order_id || "")
300
- if (!orderId) {
301
- return { status: "pending", data: { ...(input.data || {}) } }
302
- }
303
-
304
- try {
305
- const order = await this.getOrderDetails(orderId)
306
- const capture = order?.purchase_units?.[0]?.payments?.captures?.[0]
307
- const authorization = order?.purchase_units?.[0]?.payments?.authorizations?.[0]
308
- const mappedStatus =
309
- this.mapCaptureStatus(capture?.status) ||
310
- this.mapAuthorizationStatus(authorization?.status) ||
311
- this.mapOrderStatus(order?.status) ||
312
- "pending"
313
-
314
- await this.recordSuccess("status_success")
315
- return {
316
- status: mappedStatus,
317
- data: {
318
- ...(input.data || {}),
319
- paypal: {
320
- ...((input.data || {}).paypal as Record<string, unknown>),
321
- order,
322
- authorization_id: authorization?.id || paypalData.authorization_id,
323
- capture_id: capture?.id || paypalData.capture_id,
324
- },
325
- },
326
- }
327
- } catch (error: any) {
328
- await this.recordFailure("status_failed", {
329
- order_id: orderId,
330
- message: error?.message,
331
- })
332
- throw error
333
- }
334
- }
335
-
336
- async capturePayment(input: CapturePaymentInput): Promise<CapturePaymentOutput> {
337
- const data = (input.data || {}) as Record<string, any>
338
- const paypalData = (data.paypal || {}) as Record<string, any>
339
- const orderId = String(paypalData.order_id || data.order_id || "")
340
- let authorizationId = String(
341
- paypalData.authorization_id || data.authorization_id || ""
342
- )
343
- if (!orderId) {
344
- throw new Error("PayPal order_id is required to capture payment")
345
- }
346
-
347
- if (paypalData.capture_id || paypalData.capture) {
348
- return {
349
- data: {
350
- ...(input.data || {}),
351
- paypal: {
352
- ...((input.data || {}).paypal as Record<string, unknown>),
353
- capture_id: paypalData.capture_id,
354
- capture: paypalData.capture,
355
- },
356
- captured_at: new Date().toISOString(),
357
- },
358
- }
359
- }
360
-
361
- const { amount: sessionAmount, currencyCode } = await this.normalizePaymentData(input)
362
- // The requested (possibly partial) capture amount lives on the Medusa
363
- // capture row, not in the provider input — resolve it so partial captures
364
- // don't charge the full session total.
365
- const amount = await this.resolveRequestedCaptureAmount(input, sessionAmount)
366
- // Include the amount in the idempotency suffix: PayPal deduplicates by
367
- // PayPal-Request-Id, so two sequential partial captures of the same order
368
- // that share an upstream idempotency_key would otherwise collide and the
369
- // second capture would silently return the first one's result.
370
- const requestId = this.getIdempotencyKey(input, `capture-${orderId}-${amount}`)
371
- let debugId: string | null = null
372
-
373
- try {
374
- const { accessToken, base } = await this.getPayPalAccessToken()
375
- const order = await this.getOrderDetails(orderId).catch(() => null)
376
- const existingCapture = order?.purchase_units?.[0]?.payments?.captures?.[0]
377
- if (existingCapture?.id && isCaptureCompleted(existingCapture)) {
378
- return {
379
- data: {
380
- ...(input.data || {}),
381
- paypal: {
382
- ...((input.data || {}).paypal as Record<string, unknown>),
383
- capture_id: existingCapture.id,
384
- capture: existingCapture,
385
- },
386
- captured_at: new Date().toISOString(),
387
- },
388
- }
389
- }
390
-
391
- const resolvedIntent = String(
392
- order?.intent || paypalData.order?.intent || data.intent || ""
393
- ).toUpperCase()
394
-
395
- if (!authorizationId && resolvedIntent === "AUTHORIZE") {
396
- const authorizeResp = await paypalFetch(
397
- `${base}/v2/checkout/orders/${encodeURIComponent(orderId)}/authorize`,
398
- {
399
- method: "POST",
400
- headers: {
401
- Authorization: `Bearer ${accessToken}`,
402
- "Content-Type": "application/json",
403
- "PayPal-Request-Id": `${requestId}-auth`,
404
- "PayPal-Partner-Attribution-Id": PAYPAL_PARTNER_ATTRIBUTION_ID,
405
- },
406
- }
407
- )
408
- const authorizeText = await authorizeResp.text()
409
- debugId = authorizeResp.headers.get("paypal-debug-id")
410
- if (!authorizeResp.ok) {
411
- throw new Error(
412
- `PayPal authorize order error (${authorizeResp.status}): ${authorizeText}${
413
- debugId ? ` debug_id=${debugId}` : ""
414
- }`
415
- )
416
- }
417
- const authorization = JSON.parse(authorizeText)
418
- authorizationId =
419
- authorization?.purchase_units?.[0]?.payments?.authorizations?.[0]?.id
420
- }
421
-
422
- const isFinalCapture =
423
- paypalData.is_final_capture ??
424
- data.is_final_capture ??
425
- data.final_capture ??
426
- undefined
427
- const captureValue = amount > 0
428
- ? formatAmountForPayPal(amount, currencyCode || "EUR")
429
- : null
430
-
431
- // `amount` and `is_final_capture` are only valid on the authorizations
432
- // capture endpoint. The orders capture endpoint always captures the FULL
433
- // order and silently ignores an `amount` body — so sending a partial
434
- // amount there would over-capture while we record the (smaller) requested
435
- // value. Route partial captures to the authorization, and fail closed if a
436
- // partial capture is attempted against a capture-intent order.
437
- let capturePayload: Record<string, unknown>
438
- let captureUrl: string
439
- if (authorizationId) {
440
- captureUrl = `${base}/v2/payments/authorizations/${encodeURIComponent(authorizationId)}/capture`
441
- capturePayload = {
442
- ...(captureValue
443
- ? { amount: { currency_code: currencyCode || "EUR", value: captureValue } }
444
- : {}),
445
- ...(typeof isFinalCapture === "boolean" ? { is_final_capture: isFinalCapture } : {}),
446
- }
447
- } else {
448
- captureUrl = `${base}/v2/checkout/orders/${encodeURIComponent(orderId)}/capture`
449
- capturePayload = {}
450
- const orderTotal = order?.purchase_units?.[0]?.amount?.value
451
- if (captureValue && orderTotal && captureValue !== String(orderTotal)) {
452
- throw new Error(
453
- `PayPal partial capture (${captureValue} ${currencyCode || "EUR"}) is not supported for ` +
454
- `capture-intent orders (order total ${orderTotal}). Create the order with intent ` +
455
- `AUTHORIZE to capture a partial amount.`
456
- )
457
- }
458
- }
459
-
460
- // Retry transient 5xx/429/timeout: the PayPal-Request-Id makes the
461
- // capture idempotent, so a retry after a network blip re-uses the same
462
- // capture instead of double-charging.
463
- const ppResp = await paypalFetchWithRetry(captureUrl, {
464
- method: "POST",
465
- headers: {
466
- Authorization: `Bearer ${accessToken}`,
467
- "Content-Type": "application/json",
468
- "PayPal-Request-Id": requestId,
469
- "PayPal-Partner-Attribution-Id": PAYPAL_PARTNER_ATTRIBUTION_ID,
470
- },
471
- body: JSON.stringify(capturePayload),
472
- })
473
-
474
- const ppText = await ppResp.text()
475
- debugId = ppResp.headers.get("paypal-debug-id")
476
- if (!ppResp.ok) {
477
- throw new Error(
478
- `PayPal capture error (${ppResp.status}): ${ppText}${
479
- debugId ? ` debug_id=${debugId}` : ""
480
- }`
481
- )
482
- }
483
-
484
- const capture = JSON.parse(ppText)
485
-
486
- // A 2xx response does NOT mean the funds were captured. PayPal returns 201
487
- // for captures that are PENDING (e.g. pending review / eCheck), DECLINED,
488
- // or FAILED. Recording any of these as "captured" books money that never
489
- // settled, so only a COMPLETED capture is treated as success.
490
- const captureStatus = extractCaptureStatus(capture)
491
- if (captureStatus !== "COMPLETED") {
492
- throw new Error(
493
- `PayPal capture did not complete (status=${captureStatus || "UNKNOWN"}). ` +
494
- `The payment was not captured.${debugId ? ` debug_id=${debugId}` : ""}`
495
- )
496
- }
497
-
498
- const captureId =
499
- capture?.id || capture?.purchase_units?.[0]?.payments?.captures?.[0]?.id
500
- const existingCaptures = Array.isArray(paypalData.captures) ? paypalData.captures : []
501
- const captureEntry = {
502
- id: captureId,
503
- status: capture?.status,
504
- amount: capture?.amount,
505
- raw: capture,
506
- }
507
-
508
- await this.recordSuccess("capture_success")
509
- await this.recordPaymentEvent("capture", {
510
- order_id: orderId,
511
- capture_id: captureId,
512
- authorization_id: authorizationId || undefined,
513
- amount,
514
- currency_code: currencyCode,
515
- request_id: requestId,
516
- })
517
-
518
- return {
519
- data: {
520
- ...(input.data || {}),
521
- paypal: {
522
- ...((input.data || {}).paypal as Record<string, unknown>),
523
- order_id: orderId,
524
- capture_id: captureId,
525
- capture,
526
- authorization_id: authorizationId || paypalData.authorization_id,
527
- captures: [...existingCaptures, captureEntry],
528
- },
529
- captured_at: new Date().toISOString(),
530
- },
531
- }
532
- } catch (error: any) {
533
- await this.recordFailure("capture_failed", {
534
- order_id: orderId,
535
- request_id: requestId,
536
- debug_id: debugId,
537
- message: error?.message,
538
- })
539
- throw error instanceof MedusaError
540
- ? error
541
- : new MedusaError(
542
- MedusaError.Types.INVALID_DATA,
543
- error?.message || "PayPal capture failed."
544
- )
545
- }
546
- }
547
-
548
- async refundPayment(input: RefundPaymentInput): Promise<RefundPaymentOutput> {
549
- const data = (input.data || {}) as Record<string, any>
550
- const paypalData = (data.paypal || {}) as Record<string, any>
551
- const captureId = String(paypalData.capture_id || data.capture_id || "")
552
- const refundReason = String(
553
- paypalData.refund_reason || data.refund_reason || data.reason || ""
554
- ).trim()
555
- const refundReasonCode = String(
556
- paypalData.refund_reason_code || data.refund_reason_code || data.reason_code || ""
557
- ).trim()
558
- if (!captureId) {
559
- throw new MedusaError(
560
- MedusaError.Types.INVALID_DATA,
561
- "PayPal capture_id is required to refund payment. No capture found in session data."
562
- )
563
- }
564
-
565
- // Medusa passes the refund amount as a BigNumberInput (BigNumber instance or
566
- // serialized { value, precision }); coerce it to a number so partial refunds
567
- // send the correct value instead of silently refunding the full capture.
568
- const refundAmount = toAmountNumber(input.amount)
569
-
570
- // Include the amount in the idempotency suffix so two sequential partial
571
- // refunds of the same capture are not deduplicated by PayPal into one.
572
- const requestId = this.getIdempotencyKey(
573
- input,
574
- `refund-${captureId}-${refundAmount}`
575
- )
576
-
577
- const currencyOverride = await this.resolveCurrencyOverride()
578
- const currencyCode = normalizeCurrencyCode(
579
- data.currency_code || currencyOverride || "EUR"
580
- )
581
-
582
- const refundValue = refundAmount > 0
583
- ? formatAmountForPayPal(refundAmount, currencyCode)
584
- : null
585
-
586
- let debugId: string | null = null
587
-
588
- try {
589
- const { accessToken, base } = await this.getPayPalAccessToken()
590
- const refundPayload: Record<string, any> =
591
- refundValue
592
- ? {
593
- amount: {
594
- currency_code: currencyCode || "EUR",
595
- value: refundValue,
596
- },
597
- }
598
- : {}
599
-
600
- if (refundReason) {
601
- // PayPal rejects a note_to_payer longer than 255 characters with a 422
602
- // (which would otherwise fail the whole refund); truncate defensively.
603
- refundPayload.note_to_payer = refundReason.slice(0, 255)
604
- }
605
-
606
- // Retry transient 5xx/429/timeout: the PayPal-Request-Id (which includes
607
- // the refund amount) makes the refund idempotent, so a retry after a
608
- // network blip re-uses the same refund instead of double-refunding.
609
- const ppResp = await paypalFetchWithRetry(`${base}/v2/payments/captures/${encodeURIComponent(captureId)}/refund`, {
610
- method: "POST",
611
- headers: {
612
- Authorization: `Bearer ${accessToken}`,
613
- "Content-Type": "application/json",
614
- "PayPal-Request-Id": requestId,
615
- "PayPal-Partner-Attribution-Id": PAYPAL_PARTNER_ATTRIBUTION_ID,
616
- },
617
- body: JSON.stringify(refundPayload),
618
- })
619
-
620
- const ppText = await ppResp.text()
621
- debugId = ppResp.headers.get("paypal-debug-id")
622
- if (!ppResp.ok) {
623
- throw new Error(
624
- `PayPal refund error (${ppResp.status}): ${ppText}${
625
- debugId ? ` debug_id=${debugId}` : ""
626
- }`
627
- )
628
- }
629
-
630
- const refund = JSON.parse(ppText)
631
-
632
- // As with captures, a 2xx response does not guarantee the refund stuck.
633
- // FAILED / CANCELLED / DENIED refunds also return 2xx and must not be
634
- // recorded as a successful refund. PENDING is accepted: PayPal processes
635
- // refunds asynchronously and a pending refund will settle.
636
- const refundStatus = String(refund?.status || "").toUpperCase()
637
- if (isRefundFailureStatus(refundStatus)) {
638
- throw new Error(
639
- `PayPal refund did not succeed (status=${refundStatus}). The refund was not issued.` +
640
- (debugId ? ` debug_id=${debugId}` : "")
641
- )
642
- }
643
-
644
- const existingRefunds = Array.isArray(paypalData.refunds) ? paypalData.refunds : []
645
- const refundEntry = {
646
- id: refund?.id,
647
- status: refund?.status,
648
- amount: refund?.amount,
649
- reason: refundReason || refund?.note_to_payer,
650
- reason_code: refundReasonCode || refund?.reason_code,
651
- raw: refund,
652
- }
653
-
654
- await this.recordSuccess("refund_success")
655
- await this.recordPaymentEvent("refund", {
656
- capture_id: captureId,
657
- refund_id: refund?.id,
658
- amount: refundAmount,
659
- currency_code: currencyCode,
660
- request_id: requestId,
661
- reason: refundReason,
662
- reason_code: refundReasonCode,
663
- })
664
-
665
- return {
666
- data: {
667
- ...(input.data || {}),
668
- paypal: {
669
- ...((input.data || {}).paypal as Record<string, unknown>),
670
- refund_id: refund?.id,
671
- refund_status: refund?.status,
672
- refund_reason: refundReason || refund?.note_to_payer,
673
- refund_reason_code: refundReasonCode || refund?.reason_code,
674
- refunds: [...existingRefunds, refundEntry],
675
- refund,
676
- },
677
- refunded_at: new Date().toISOString(),
678
- },
679
- }
680
- } catch (error: any) {
681
- await this.recordFailure("refund_failed", {
682
- capture_id: captureId,
683
- request_id: requestId,
684
- debug_id: debugId,
685
- message: error?.message,
686
- })
687
- throw error instanceof MedusaError
688
- ? error
689
- : new MedusaError(
690
- MedusaError.Types.INVALID_DATA,
691
- error?.message || "PayPal refund failed."
692
- )
693
- }
694
- }
695
-
696
- async cancelPayment(input: CancelPaymentInput): Promise<CancelPaymentOutput> {
697
- const data = (input.data || {}) as Record<string, any>
698
- const paypalData = (data.paypal || {}) as Record<string, any>
699
- const orderId = String(paypalData.order_id || data.order_id || "")
700
- const captureId = String(paypalData.capture_id || data.capture_id || "")
701
- const storedAuthorizationId = String(
702
- paypalData.authorization_id || data.authorization_id || ""
703
- )
704
- let debugId: string | null = null
705
-
706
- try {
707
- const order = orderId ? await this.getOrderDetails(orderId) : null
708
- const intent = String(order?.intent || "").toUpperCase()
709
- const authorizationId =
710
- order?.purchase_units?.[0]?.payments?.authorizations?.[0]?.id ||
711
- storedAuthorizationId
712
-
713
- if (intent === "AUTHORIZE" && authorizationId) {
714
- const { accessToken, base } = await this.getPayPalAccessToken()
715
- const requestId = this.getIdempotencyKey(input, `void-${authorizationId}`)
716
-
717
- const resp = await paypalFetch(
718
- `${base}/v2/payments/authorizations/${encodeURIComponent(authorizationId)}/void`,
719
- {
720
- method: "POST",
721
- headers: {
722
- Authorization: `Bearer ${accessToken}`,
723
- "Content-Type": "application/json",
724
- "PayPal-Request-Id": requestId,
725
- "PayPal-Partner-Attribution-Id": PAYPAL_PARTNER_ATTRIBUTION_ID,
726
- },
727
- }
728
- )
729
-
730
- if (!resp.ok) {
731
- const text = await resp.text()
732
- debugId = resp.headers.get("paypal-debug-id")
733
- throw new Error(
734
- `PayPal void error (${resp.status}): ${text}${
735
- debugId ? ` debug_id=${debugId}` : ""
736
- }`
737
- )
738
- }
739
-
740
- await this.recordSuccess("void_success")
741
- await this.recordPaymentEvent("void", {
742
- order_id: orderId,
743
- authorization_id: authorizationId,
744
- })
745
- } else if (captureId) {
746
- const { accessToken, base } = await this.getPayPalAccessToken()
747
- const requestId = this.getIdempotencyKey(input, `cancel-refund-${captureId}`)
748
-
749
- const resp = await paypalFetch(`${base}/v2/payments/captures/${encodeURIComponent(captureId)}/refund`, {
750
- method: "POST",
751
- headers: {
752
- Authorization: `Bearer ${accessToken}`,
753
- "Content-Type": "application/json",
754
- "PayPal-Request-Id": requestId,
755
- "PayPal-Partner-Attribution-Id": PAYPAL_PARTNER_ATTRIBUTION_ID,
756
- },
757
- body: JSON.stringify({}),
758
- })
759
-
760
- if (!resp.ok) {
761
- const text = await resp.text()
762
- debugId = resp.headers.get("paypal-debug-id")
763
- throw new Error(
764
- `PayPal refund error (${resp.status}): ${text}${
765
- debugId ? ` debug_id=${debugId}` : ""
766
- }`
767
- )
768
- }
769
-
770
- const refund = await resp.json().catch(() => ({}))
771
-
772
- // As with refundPayment: a 2xx response does not guarantee the refund
773
- // stuck — FAILED / CANCELLED / DENIED refunds also return 2xx. Booking
774
- // `canceled_at` for a refund that never went through would record a
775
- // cancellation while the merchant keeps the funds.
776
- const cancelRefundStatus = String(refund?.status || "").toUpperCase()
777
- if (isRefundFailureStatus(cancelRefundStatus)) {
778
- throw new Error(
779
- `PayPal cancel-refund did not succeed (status=${cancelRefundStatus}). The payment was not canceled.`
780
- )
781
- }
782
-
783
- const existingRefunds = Array.isArray(paypalData.refunds) ? paypalData.refunds : []
784
- const refundEntry = {
785
- id: refund?.id,
786
- status: refund?.status,
787
- amount: refund?.amount,
788
- raw: refund,
789
- }
790
-
791
- await this.recordSuccess("cancel_refund_success")
792
-
793
- return {
794
- data: {
795
- ...(input.data || {}),
796
- paypal: {
797
- ...((input.data || {}).paypal as Record<string, unknown>),
798
- order: order || undefined,
799
- authorization_id: authorizationId || storedAuthorizationId,
800
- capture_id: captureId || paypalData.capture_id,
801
- refund_id: refund?.id,
802
- refund_status: refund?.status,
803
- refunds: [...existingRefunds, refundEntry],
804
- },
805
- canceled_at: new Date().toISOString(),
806
- },
807
- }
808
- }
809
-
810
- return {
811
- data: {
812
- ...(input.data || {}),
813
- paypal: {
814
- ...((input.data || {}).paypal as Record<string, unknown>),
815
- order: order || undefined,
816
- authorization_id: authorizationId || storedAuthorizationId,
817
- capture_id: captureId || paypalData.capture_id,
818
- },
819
- canceled_at: new Date().toISOString(),
820
- },
821
- }
822
- } catch (error: any) {
823
- await this.recordFailure("cancel_failed", {
824
- order_id: orderId,
825
- capture_id: captureId,
826
- debug_id: debugId,
827
- message: error?.message,
828
- })
829
- throw error
830
- }
831
- }
832
-
833
- }
834
-
835
- export default PayPalPaymentProvider
836
- export { PayPalPaymentProvider }
1
+ import { MedusaError } from "@medusajs/framework/utils"
2
+ import type {
3
+ AuthorizePaymentInput,
4
+ AuthorizePaymentOutput,
5
+ CancelPaymentInput,
6
+ CancelPaymentOutput,
7
+ GetPaymentStatusInput,
8
+ GetPaymentStatusOutput,
9
+ InitiatePaymentInput,
10
+ InitiatePaymentOutput,
11
+ RefundPaymentInput,
12
+ RefundPaymentOutput,
13
+ RetrievePaymentInput,
14
+ RetrievePaymentOutput,
15
+ UpdatePaymentInput,
16
+ UpdatePaymentOutput,
17
+ } from "@medusajs/framework/types"
18
+ import { formatAmountForPayPal, toAmountNumber } from "../utils/amounts"
19
+ import {
20
+ assertPayPalCurrencySupported,
21
+ normalizeCurrencyCode,
22
+ } from "../utils/currencies"
23
+ import { PAYPAL_PARTNER_ATTRIBUTION_ID } from "../utils/partner"
24
+ import { paypalFetch, paypalFetchWithRetry } from "../utils/paypal-fetch"
25
+ import { extractCaptureStatus, isRefundFailureStatus } from "./status-utils"
26
+ import { PayPalProviderBase } from "./base-provider"
27
+
28
+ /**
29
+ * PayPal wallet (Smart Buttons) payment provider — `pp_paypal_paypal`.
30
+ *
31
+ * The storefront creates and approves the PayPal order through the
32
+ * `/store/paypal/create-order` + `/store/paypal/capture-order` routes; this
33
+ * provider then authorizes/captures/refunds/cancels against the order id
34
+ * stored on the payment session.
35
+ */
36
+ class PayPalPaymentProvider extends PayPalProviderBase {
37
+ static identifier = "paypal"
38
+
39
+ protected readonly sessionPrefix = "pp"
40
+ protected readonly idempotencyPrefix = "pp"
41
+
42
+ async initiatePayment(
43
+ input: InitiatePaymentInput
44
+ ): Promise<InitiatePaymentOutput> {
45
+ const providerId = (input.data as Record<string, any> | undefined)
46
+ ?.provider_id
47
+ try {
48
+ const currencyOverride = await this.resolveCurrencyOverride()
49
+ const currencyCode = normalizeCurrencyCode(
50
+ input.currency_code || currencyOverride || "EUR"
51
+ )
52
+ assertPayPalCurrencySupported({
53
+ currencyCode,
54
+ paypalCurrencyOverride: currencyOverride,
55
+ })
56
+ return {
57
+ id: this.generateSessionId(),
58
+ data: {
59
+ ...(input.data || {}),
60
+ ...(providerId ? { provider_id: providerId } : {}),
61
+ amount: input.amount,
62
+ currency_code: currencyCode,
63
+ },
64
+ }
65
+ } catch (error) {
66
+ await this.recordFailure("initiate_failed", {
67
+ error: this.serializeError(error),
68
+ currency_code: input.currency_code,
69
+ amount: input.amount,
70
+ provider_id: providerId,
71
+ data: input.data ?? null,
72
+ })
73
+ throw error
74
+ }
75
+ }
76
+
77
+ async updatePayment(input: UpdatePaymentInput): Promise<UpdatePaymentOutput> {
78
+ const currencyOverride = await this.resolveCurrencyOverride()
79
+ const currencyCode = normalizeCurrencyCode(
80
+ input.currency_code || currencyOverride || "EUR"
81
+ )
82
+ assertPayPalCurrencySupported({
83
+ currencyCode,
84
+ paypalCurrencyOverride: currencyOverride,
85
+ })
86
+ const providerId = (input.data as Record<string, any> | undefined)
87
+ ?.provider_id
88
+ return {
89
+ data: {
90
+ ...(input.data || {}),
91
+ ...this.invalidateStaleOrder(input, currencyCode),
92
+ ...(providerId ? { provider_id: providerId } : {}),
93
+ amount: input.amount,
94
+ currency_code: currencyCode,
95
+ },
96
+ }
97
+ }
98
+
99
+ async authorizePayment(
100
+ input: AuthorizePaymentInput
101
+ ): Promise<AuthorizePaymentOutput> {
102
+ const { data } = await this.normalizePaymentData(input)
103
+ const existingPayPal = (data.paypal || {}) as Record<string, any>
104
+
105
+ // Session already carries a settled capture: trust it without a network
106
+ // round-trip. The stored capture object is only written after a COMPLETED
107
+ // gate (capture-order route / capturePayment), but re-verify its status
108
+ // here so a PENDING/DECLINED capture patched in by a webhook is never
109
+ // booked as captured money.
110
+ const storedCaptureStatus = extractCaptureStatus(existingPayPal.capture)
111
+ if (storedCaptureStatus === "COMPLETED") {
112
+ console.info(
113
+ "[PayPal] authorizePayment: session already captured (COMPLETED)"
114
+ )
115
+ return {
116
+ status: "captured",
117
+ data: {
118
+ ...(input.data || {}),
119
+ captured_at: (data as any).captured_at || new Date().toISOString(),
120
+ },
121
+ }
122
+ }
123
+
124
+ const orderId = String(existingPayPal.order_id || data.order_id || "")
125
+ if (orderId) {
126
+ try {
127
+ console.info(
128
+ "[PayPal] authorizePayment: fetching live order status for",
129
+ orderId
130
+ )
131
+ const order = await this.getOrderDetails(orderId)
132
+ const capture = order?.purchase_units?.[0]?.payments?.captures?.[0]
133
+ const authorization =
134
+ order?.purchase_units?.[0]?.payments?.authorizations?.[0]
135
+
136
+ // Derive the returned status from what actually happened at PayPal —
137
+ // NOT from the mere presence of a capture/authorization id and NOT
138
+ // from the merchant's configured paymentAction. A PENDING capture
139
+ // (eCheck / pending review) must not be booked as captured, and a
140
+ // DENIED/DECLINED one must fail the authorization outright.
141
+ if (capture?.id) {
142
+ const captureStatus = this.mapCaptureStatus(capture?.status)
143
+ if (captureStatus === "captured") {
144
+ return {
145
+ status: "captured",
146
+ data: {
147
+ ...(input.data || {}),
148
+ paypal: {
149
+ ...existingPayPal,
150
+ order_id: orderId,
151
+ order,
152
+ authorization_id:
153
+ authorization?.id || existingPayPal.authorization_id,
154
+ capture_id: capture.id,
155
+ capture,
156
+ },
157
+ captured_at: new Date().toISOString(),
158
+ },
159
+ }
160
+ }
161
+ if (captureStatus === "pending") {
162
+ // Funds are in flight (eCheck etc.): place the order as authorized
163
+ // so checkout completes, but never mark it captured — the
164
+ // CAPTURE.COMPLETED webhook settles it later.
165
+ return {
166
+ status: "authorized",
167
+ data: {
168
+ ...(input.data || {}),
169
+ paypal: {
170
+ ...existingPayPal,
171
+ order_id: orderId,
172
+ order,
173
+ capture_id: capture.id,
174
+ },
175
+ authorized_at: new Date().toISOString(),
176
+ },
177
+ }
178
+ }
179
+ if (captureStatus === "error" || captureStatus === "canceled") {
180
+ return {
181
+ status: "error",
182
+ data: {
183
+ ...(input.data || {}),
184
+ paypal: { ...existingPayPal, order_id: orderId, order },
185
+ },
186
+ }
187
+ }
188
+ }
189
+
190
+ if (authorization?.id) {
191
+ const authStatus = this.mapAuthorizationStatus(authorization?.status)
192
+ if (authStatus === "authorized") {
193
+ return {
194
+ status: "authorized",
195
+ data: {
196
+ ...(input.data || {}),
197
+ paypal: {
198
+ ...existingPayPal,
199
+ order_id: orderId,
200
+ order,
201
+ authorization_id: authorization.id,
202
+ },
203
+ authorized_at: new Date().toISOString(),
204
+ },
205
+ }
206
+ }
207
+ if (authStatus === "error" || authStatus === "canceled") {
208
+ return {
209
+ status: "error",
210
+ data: {
211
+ ...(input.data || {}),
212
+ paypal: { ...existingPayPal, order_id: orderId, order },
213
+ },
214
+ }
215
+ }
216
+ }
217
+
218
+ // Only a buyer-APPROVED order counts as authorized. CREATED/SAVED
219
+ // means the buyer never approved the payment — treating those as
220
+ // authorized would let a cart complete with no funds authorized at
221
+ // PayPal at all.
222
+ if (String(order?.status || "").toUpperCase() === "APPROVED") {
223
+ console.info(
224
+ "[PayPal] authorizePayment: order approved, marking authorized"
225
+ )
226
+ return {
227
+ status: "authorized",
228
+ data: {
229
+ ...(input.data || {}),
230
+ paypal: {
231
+ ...existingPayPal,
232
+ order_id: orderId,
233
+ order,
234
+ },
235
+ authorized_at: new Date().toISOString(),
236
+ },
237
+ }
238
+ }
239
+ } catch (e: any) {
240
+ console.warn(
241
+ "[PayPal] authorizePayment: order lookup failed:",
242
+ e?.message
243
+ )
244
+ // Fall back to the session's own record when PayPal is unreachable so a
245
+ // transient lookup error doesn't fail a checkout that already has a
246
+ // real authorization/capture behind it. `captured_at` is only ever
247
+ // stamped after a COMPLETED gate; a bare capture_id (e.g. patched in by
248
+ // a webhook) or authorization id maps to "authorized" — the order is
249
+ // placed without claiming settled funds.
250
+ if ((data as any).captured_at) {
251
+ return {
252
+ status: "captured",
253
+ data: {
254
+ ...(input.data || {}),
255
+ captured_at: (data as any).captured_at,
256
+ },
257
+ }
258
+ }
259
+ if (
260
+ existingPayPal.capture_id ||
261
+ existingPayPal.authorization_id ||
262
+ (data as any).authorized_at
263
+ ) {
264
+ return {
265
+ status: "authorized",
266
+ data: {
267
+ ...(input.data || {}),
268
+ authorized_at:
269
+ (data as any).authorized_at || new Date().toISOString(),
270
+ },
271
+ }
272
+ }
273
+ }
274
+ }
275
+
276
+ // No usable PayPal order on the session: nothing can be authorized. The
277
+ // previous fallback created a brand-new PayPal order here and immediately
278
+ // called /v2/checkout/orders/{id}/authorize on it — but an order no buyer
279
+ // has approved can never be authorized (PayPal rejects it with
280
+ // ORDER_NOT_APPROVED), so that path only produced confusing 422s and
281
+ // orphaned PayPal orders. Fail with a clear, actionable error instead.
282
+ await this.recordFailure("authorize_failed", {
283
+ cart_id: data.cart_id,
284
+ payment_collection_id: data.payment_collection_id,
285
+ message: "no approved PayPal order on session",
286
+ })
287
+ throw new MedusaError(
288
+ MedusaError.Types.NOT_ALLOWED,
289
+ "No approved PayPal payment was found for this session. The buyer must approve the payment with PayPal before the cart can be completed."
290
+ )
291
+ }
292
+
293
+ async retrievePayment(
294
+ input: RetrievePaymentInput
295
+ ): Promise<RetrievePaymentOutput> {
296
+ const data = (input.data || {}) as Record<string, any>
297
+ const paypalData = (data.paypal || {}) as Record<string, any>
298
+ const orderId = String(paypalData.order_id || data.order_id || "")
299
+ if (!orderId) {
300
+ return { data: { ...(input.data || {}) } }
301
+ }
302
+
303
+ const order = await this.getOrderDetails(orderId)
304
+ const capture = order?.purchase_units?.[0]?.payments?.captures?.[0]
305
+ const authorization =
306
+ order?.purchase_units?.[0]?.payments?.authorizations?.[0]
307
+
308
+ return {
309
+ data: {
310
+ ...(input.data || {}),
311
+ paypal: {
312
+ ...((input.data || {}).paypal as Record<string, unknown>),
313
+ order,
314
+ authorization_id: authorization?.id || paypalData.authorization_id,
315
+ capture_id: capture?.id || paypalData.capture_id,
316
+ },
317
+ },
318
+ }
319
+ }
320
+
321
+ async getPaymentStatus(
322
+ input: GetPaymentStatusInput
323
+ ): Promise<GetPaymentStatusOutput> {
324
+ const data = (input.data || {}) as Record<string, any>
325
+ const paypalData = (data.paypal || {}) as Record<string, any>
326
+ const orderId = String(paypalData.order_id || data.order_id || "")
327
+ if (!orderId) {
328
+ return { status: "pending", data: { ...(input.data || {}) } }
329
+ }
330
+
331
+ try {
332
+ const order = await this.getOrderDetails(orderId)
333
+ const capture = order?.purchase_units?.[0]?.payments?.captures?.[0]
334
+ const authorization =
335
+ order?.purchase_units?.[0]?.payments?.authorizations?.[0]
336
+ const mappedStatus =
337
+ this.mapCaptureStatus(capture?.status) ||
338
+ this.mapAuthorizationStatus(authorization?.status) ||
339
+ this.mapOrderStatus(order?.status) ||
340
+ "pending"
341
+
342
+ await this.recordSuccess("status_success")
343
+ return {
344
+ status: mappedStatus,
345
+ data: {
346
+ ...(input.data || {}),
347
+ paypal: {
348
+ ...((input.data || {}).paypal as Record<string, unknown>),
349
+ order,
350
+ authorization_id: authorization?.id || paypalData.authorization_id,
351
+ capture_id: capture?.id || paypalData.capture_id,
352
+ },
353
+ },
354
+ }
355
+ } catch (error: any) {
356
+ await this.recordFailure("status_failed", {
357
+ order_id: orderId,
358
+ message: error?.message,
359
+ })
360
+ throw error
361
+ }
362
+ }
363
+
364
+ async refundPayment(input: RefundPaymentInput): Promise<RefundPaymentOutput> {
365
+ const data = (input.data || {}) as Record<string, any>
366
+ const paypalData = (data.paypal || {}) as Record<string, any>
367
+ const captureId = String(paypalData.capture_id || data.capture_id || "")
368
+ const refundReason = String(
369
+ paypalData.refund_reason || data.refund_reason || data.reason || ""
370
+ ).trim()
371
+ const refundReasonCode = String(
372
+ paypalData.refund_reason_code ||
373
+ data.refund_reason_code ||
374
+ data.reason_code ||
375
+ ""
376
+ ).trim()
377
+ if (!captureId) {
378
+ throw new MedusaError(
379
+ MedusaError.Types.INVALID_DATA,
380
+ "PayPal capture_id is required to refund payment. No capture found in session data."
381
+ )
382
+ }
383
+
384
+ // Medusa passes the refund amount as a BigNumberInput (BigNumber instance or
385
+ // serialized { value, precision }); coerce it to a number so partial refunds
386
+ // send the correct value instead of silently refunding the full capture.
387
+ const refundAmount = toAmountNumber(input.amount)
388
+
389
+ // Include the amount in the idempotency suffix so two sequential partial
390
+ // refunds of the same capture are not deduplicated by PayPal into one.
391
+ const requestId = this.getIdempotencyKey(
392
+ input,
393
+ `refund-${captureId}-${refundAmount}`
394
+ )
395
+
396
+ const currencyOverride = await this.resolveCurrencyOverride()
397
+ const currencyCode = normalizeCurrencyCode(
398
+ data.currency_code || currencyOverride || "EUR"
399
+ )
400
+
401
+ const refundValue =
402
+ refundAmount > 0
403
+ ? formatAmountForPayPal(refundAmount, currencyCode)
404
+ : null
405
+
406
+ let debugId: string | null = null
407
+
408
+ try {
409
+ const { accessToken, base } = await this.getPayPalAccessToken()
410
+ const refundPayload: Record<string, any> = refundValue
411
+ ? {
412
+ amount: {
413
+ currency_code: currencyCode || "EUR",
414
+ value: refundValue,
415
+ },
416
+ }
417
+ : {}
418
+
419
+ if (refundReason) {
420
+ // PayPal rejects a note_to_payer longer than 255 characters with a 422
421
+ // (which would otherwise fail the whole refund); truncate defensively.
422
+ refundPayload.note_to_payer = refundReason.slice(0, 255)
423
+ }
424
+
425
+ // Retry transient 5xx/429/timeout: the PayPal-Request-Id (which includes
426
+ // the refund amount) makes the refund idempotent, so a retry after a
427
+ // network blip re-uses the same refund instead of double-refunding.
428
+ const ppResp = await paypalFetchWithRetry(
429
+ `${base}/v2/payments/captures/${encodeURIComponent(captureId)}/refund`,
430
+ {
431
+ method: "POST",
432
+ headers: {
433
+ Authorization: `Bearer ${accessToken}`,
434
+ "Content-Type": "application/json",
435
+ // Full refund resource (amount, status, …) instead of the
436
+ // id/status/links stub, so the stored refund entry is usable.
437
+ Prefer: "return=representation",
438
+ "PayPal-Request-Id": requestId,
439
+ "PayPal-Partner-Attribution-Id": PAYPAL_PARTNER_ATTRIBUTION_ID,
440
+ },
441
+ body: JSON.stringify(refundPayload),
442
+ }
443
+ )
444
+
445
+ const ppText = await ppResp.text()
446
+ debugId = ppResp.headers.get("paypal-debug-id")
447
+ if (!ppResp.ok) {
448
+ throw new Error(
449
+ `PayPal refund error (${ppResp.status}): ${ppText}${
450
+ debugId ? ` debug_id=${debugId}` : ""
451
+ }`
452
+ )
453
+ }
454
+
455
+ const refund = JSON.parse(ppText)
456
+
457
+ // As with captures, a 2xx response does not guarantee the refund stuck.
458
+ // FAILED / CANCELLED / DENIED refunds also return 2xx and must not be
459
+ // recorded as a successful refund. PENDING is accepted: PayPal processes
460
+ // refunds asynchronously and a pending refund will settle.
461
+ const refundStatus = String(refund?.status || "").toUpperCase()
462
+ if (isRefundFailureStatus(refundStatus)) {
463
+ throw new Error(
464
+ `PayPal refund did not succeed (status=${refundStatus}). The refund was not issued.` +
465
+ (debugId ? ` debug_id=${debugId}` : "")
466
+ )
467
+ }
468
+
469
+ const existingRefunds = Array.isArray(paypalData.refunds)
470
+ ? paypalData.refunds
471
+ : []
472
+ const refundEntry = {
473
+ id: refund?.id,
474
+ status: refund?.status,
475
+ amount: refund?.amount,
476
+ reason: refundReason || refund?.note_to_payer,
477
+ reason_code: refundReasonCode || refund?.reason_code,
478
+ raw: refund,
479
+ }
480
+
481
+ await this.recordSuccess("refund_success")
482
+ await this.recordPaymentEvent("refund", {
483
+ capture_id: captureId,
484
+ refund_id: refund?.id,
485
+ amount: refundAmount,
486
+ currency_code: currencyCode,
487
+ request_id: requestId,
488
+ reason: refundReason,
489
+ reason_code: refundReasonCode,
490
+ })
491
+
492
+ return {
493
+ data: {
494
+ ...(input.data || {}),
495
+ paypal: {
496
+ ...((input.data || {}).paypal as Record<string, unknown>),
497
+ refund_id: refund?.id,
498
+ refund_status: refund?.status,
499
+ refund_reason: refundReason || refund?.note_to_payer,
500
+ refund_reason_code: refundReasonCode || refund?.reason_code,
501
+ refunds: [...existingRefunds, refundEntry],
502
+ refund,
503
+ },
504
+ refunded_at: new Date().toISOString(),
505
+ },
506
+ }
507
+ } catch (error: any) {
508
+ await this.recordFailure("refund_failed", {
509
+ capture_id: captureId,
510
+ request_id: requestId,
511
+ debug_id: debugId,
512
+ message: error?.message,
513
+ })
514
+ throw error instanceof MedusaError
515
+ ? error
516
+ : new MedusaError(
517
+ MedusaError.Types.INVALID_DATA,
518
+ error?.message || "PayPal refund failed."
519
+ )
520
+ }
521
+ }
522
+
523
+ async cancelPayment(input: CancelPaymentInput): Promise<CancelPaymentOutput> {
524
+ const data = (input.data || {}) as Record<string, any>
525
+ const paypalData = (data.paypal || {}) as Record<string, any>
526
+ const orderId = String(paypalData.order_id || data.order_id || "")
527
+ const captureId = String(paypalData.capture_id || data.capture_id || "")
528
+ const storedAuthorizationId = String(
529
+ paypalData.authorization_id || data.authorization_id || ""
530
+ )
531
+ let debugId: string | null = null
532
+
533
+ try {
534
+ const order = orderId ? await this.getOrderDetails(orderId) : null
535
+ const intent = String(order?.intent || "").toUpperCase()
536
+ const authorizationId =
537
+ order?.purchase_units?.[0]?.payments?.authorizations?.[0]?.id ||
538
+ storedAuthorizationId
539
+
540
+ if (intent === "AUTHORIZE" && authorizationId) {
541
+ const { accessToken, base } = await this.getPayPalAccessToken()
542
+ const requestId = this.getIdempotencyKey(
543
+ input,
544
+ `void-${authorizationId}`
545
+ )
546
+
547
+ const resp = await paypalFetch(
548
+ `${base}/v2/payments/authorizations/${encodeURIComponent(authorizationId)}/void`,
549
+ {
550
+ method: "POST",
551
+ headers: {
552
+ Authorization: `Bearer ${accessToken}`,
553
+ "Content-Type": "application/json",
554
+ "PayPal-Request-Id": requestId,
555
+ "PayPal-Partner-Attribution-Id": PAYPAL_PARTNER_ATTRIBUTION_ID,
556
+ },
557
+ }
558
+ )
559
+
560
+ if (!resp.ok) {
561
+ const text = await resp.text()
562
+ debugId = resp.headers.get("paypal-debug-id")
563
+ throw new Error(
564
+ `PayPal void error (${resp.status}): ${text}${
565
+ debugId ? ` debug_id=${debugId}` : ""
566
+ }`
567
+ )
568
+ }
569
+
570
+ await this.recordSuccess("void_success")
571
+ await this.recordPaymentEvent("void", {
572
+ order_id: orderId,
573
+ authorization_id: authorizationId,
574
+ })
575
+ } else if (captureId) {
576
+ const { accessToken, base } = await this.getPayPalAccessToken()
577
+ const requestId = this.getIdempotencyKey(
578
+ input,
579
+ `cancel-refund-${captureId}`
580
+ )
581
+
582
+ const resp = await paypalFetch(
583
+ `${base}/v2/payments/captures/${encodeURIComponent(captureId)}/refund`,
584
+ {
585
+ method: "POST",
586
+ headers: {
587
+ Authorization: `Bearer ${accessToken}`,
588
+ "Content-Type": "application/json",
589
+ "PayPal-Request-Id": requestId,
590
+ "PayPal-Partner-Attribution-Id": PAYPAL_PARTNER_ATTRIBUTION_ID,
591
+ },
592
+ body: JSON.stringify({}),
593
+ }
594
+ )
595
+
596
+ if (!resp.ok) {
597
+ const text = await resp.text()
598
+ debugId = resp.headers.get("paypal-debug-id")
599
+ throw new Error(
600
+ `PayPal refund error (${resp.status}): ${text}${
601
+ debugId ? ` debug_id=${debugId}` : ""
602
+ }`
603
+ )
604
+ }
605
+
606
+ const refund = await resp.json().catch(() => ({}))
607
+
608
+ // As with refundPayment: a 2xx response does not guarantee the refund
609
+ // stuck — FAILED / CANCELLED / DENIED refunds also return 2xx. Booking
610
+ // `canceled_at` for a refund that never went through would record a
611
+ // cancellation while the merchant keeps the funds.
612
+ const cancelRefundStatus = String(refund?.status || "").toUpperCase()
613
+ if (isRefundFailureStatus(cancelRefundStatus)) {
614
+ throw new Error(
615
+ `PayPal cancel-refund did not succeed (status=${cancelRefundStatus}). The payment was not canceled.`
616
+ )
617
+ }
618
+
619
+ const existingRefunds = Array.isArray(paypalData.refunds)
620
+ ? paypalData.refunds
621
+ : []
622
+ const refundEntry = {
623
+ id: refund?.id,
624
+ status: refund?.status,
625
+ amount: refund?.amount,
626
+ raw: refund,
627
+ }
628
+
629
+ await this.recordSuccess("cancel_refund_success")
630
+
631
+ return {
632
+ data: {
633
+ ...(input.data || {}),
634
+ paypal: {
635
+ ...((input.data || {}).paypal as Record<string, unknown>),
636
+ order: order || undefined,
637
+ authorization_id: authorizationId || storedAuthorizationId,
638
+ capture_id: captureId || paypalData.capture_id,
639
+ refund_id: refund?.id,
640
+ refund_status: refund?.status,
641
+ refunds: [...existingRefunds, refundEntry],
642
+ },
643
+ canceled_at: new Date().toISOString(),
644
+ },
645
+ }
646
+ }
647
+
648
+ return {
649
+ data: {
650
+ ...(input.data || {}),
651
+ paypal: {
652
+ ...((input.data || {}).paypal as Record<string, unknown>),
653
+ order: order || undefined,
654
+ authorization_id: authorizationId || storedAuthorizationId,
655
+ capture_id: captureId || paypalData.capture_id,
656
+ },
657
+ canceled_at: new Date().toISOString(),
658
+ },
659
+ }
660
+ } catch (error: any) {
661
+ await this.recordFailure("cancel_failed", {
662
+ order_id: orderId,
663
+ capture_id: captureId,
664
+ debug_id: debugId,
665
+ message: error?.message,
666
+ })
667
+ throw error
668
+ }
669
+ }
670
+ }
671
+
672
+ export default PayPalPaymentProvider
673
+ export { PayPalPaymentProvider }