@easypayment/medusa-payment-paypal 1.2.2 → 1.2.4

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 (267) hide show
  1. package/.medusa/server/src/admin/index.js +390 -136
  2. package/.medusa/server/src/admin/index.mjs +390 -136
  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 +5 -0
  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 +54 -20
  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 +33 -6
  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.map +1 -1
  113. package/.medusa/server/src/modules/paypal/payment-provider/base-provider.js.map +1 -1
  114. package/.medusa/server/src/modules/paypal/payment-provider/card-service.d.ts +14 -6
  115. package/.medusa/server/src/modules/paypal/payment-provider/card-service.d.ts.map +1 -1
  116. package/.medusa/server/src/modules/paypal/payment-provider/card-service.js +55 -32
  117. package/.medusa/server/src/modules/paypal/payment-provider/card-service.js.map +1 -1
  118. package/.medusa/server/src/modules/paypal/payment-provider/index.d.ts +6 -1
  119. package/.medusa/server/src/modules/paypal/payment-provider/index.d.ts.map +1 -1
  120. package/.medusa/server/src/modules/paypal/payment-provider/index.js +6 -4
  121. package/.medusa/server/src/modules/paypal/payment-provider/index.js.map +1 -1
  122. package/.medusa/server/src/modules/paypal/payment-provider/service.d.ts +8 -0
  123. package/.medusa/server/src/modules/paypal/payment-provider/service.d.ts.map +1 -1
  124. package/.medusa/server/src/modules/paypal/payment-provider/service.js +39 -12
  125. package/.medusa/server/src/modules/paypal/payment-provider/service.js.map +1 -1
  126. package/.medusa/server/src/modules/paypal/service.d.ts +72 -2
  127. package/.medusa/server/src/modules/paypal/service.d.ts.map +1 -1
  128. package/.medusa/server/src/modules/paypal/service.js +159 -33
  129. package/.medusa/server/src/modules/paypal/service.js.map +1 -1
  130. package/.medusa/server/src/modules/paypal/types/config.d.ts +2 -0
  131. package/.medusa/server/src/modules/paypal/types/config.d.ts.map +1 -1
  132. package/.medusa/server/src/modules/paypal/types/config.js +5 -2
  133. package/.medusa/server/src/modules/paypal/types/config.js.map +1 -1
  134. package/.medusa/server/src/modules/paypal/utils/amounts.d.ts +1 -0
  135. package/.medusa/server/src/modules/paypal/utils/amounts.d.ts.map +1 -1
  136. package/.medusa/server/src/modules/paypal/utils/amounts.js +15 -5
  137. package/.medusa/server/src/modules/paypal/utils/amounts.js.map +1 -1
  138. package/.medusa/server/src/modules/paypal/utils/credential-resolver.d.ts.map +1 -1
  139. package/.medusa/server/src/modules/paypal/utils/credential-resolver.js +3 -1
  140. package/.medusa/server/src/modules/paypal/utils/credential-resolver.js.map +1 -1
  141. package/.medusa/server/src/modules/paypal/utils/currencies.d.ts +9 -0
  142. package/.medusa/server/src/modules/paypal/utils/currencies.d.ts.map +1 -1
  143. package/.medusa/server/src/modules/paypal/utils/currencies.js +13 -0
  144. package/.medusa/server/src/modules/paypal/utils/currencies.js.map +1 -1
  145. package/.medusa/server/src/modules/paypal/utils/payment-session.d.ts +12 -0
  146. package/.medusa/server/src/modules/paypal/utils/payment-session.d.ts.map +1 -1
  147. package/.medusa/server/src/modules/paypal/utils/payment-session.js +4 -3
  148. package/.medusa/server/src/modules/paypal/utils/payment-session.js.map +1 -1
  149. package/.medusa/server/src/modules/paypal/utils/paypal-auth.d.ts +1 -0
  150. package/.medusa/server/src/modules/paypal/utils/paypal-auth.d.ts.map +1 -1
  151. package/.medusa/server/src/modules/paypal/utils/paypal-auth.js +1 -0
  152. package/.medusa/server/src/modules/paypal/utils/paypal-auth.js.map +1 -1
  153. package/.medusa/server/src/modules/paypal/utils/paypal-fetch.d.ts +11 -0
  154. package/.medusa/server/src/modules/paypal/utils/paypal-fetch.d.ts.map +1 -1
  155. package/.medusa/server/src/modules/paypal/utils/paypal-fetch.js +17 -1
  156. package/.medusa/server/src/modules/paypal/utils/paypal-fetch.js.map +1 -1
  157. package/.medusa/server/src/modules/paypal/utils/provider-ids.d.ts +6 -0
  158. package/.medusa/server/src/modules/paypal/utils/provider-ids.d.ts.map +1 -1
  159. package/.medusa/server/src/modules/paypal/utils/provider-ids.js +6 -0
  160. package/.medusa/server/src/modules/paypal/utils/provider-ids.js.map +1 -1
  161. package/.medusa/server/src/modules/paypal/utils/secret-crypto.d.ts +2 -0
  162. package/.medusa/server/src/modules/paypal/utils/secret-crypto.d.ts.map +1 -1
  163. package/.medusa/server/src/modules/paypal/utils/secret-crypto.js +6 -1
  164. package/.medusa/server/src/modules/paypal/utils/secret-crypto.js.map +1 -1
  165. package/.medusa/server/src/modules/paypal/webhook-processor.d.ts +43 -0
  166. package/.medusa/server/src/modules/paypal/webhook-processor.d.ts.map +1 -1
  167. package/.medusa/server/src/modules/paypal/webhook-processor.js +57 -5
  168. package/.medusa/server/src/modules/paypal/webhook-processor.js.map +1 -1
  169. package/.medusa/server/src/providers/paypal/index.d.ts +1 -0
  170. package/.medusa/server/src/providers/paypal/index.d.ts.map +1 -1
  171. package/.medusa/server/src/providers/paypal/index.js +1 -0
  172. package/.medusa/server/src/providers/paypal/index.js.map +1 -1
  173. package/.medusa/server/src/providers/paypal_card/index.d.ts +1 -0
  174. package/.medusa/server/src/providers/paypal_card/index.d.ts.map +1 -1
  175. package/.medusa/server/src/providers/paypal_card/index.js +1 -0
  176. package/.medusa/server/src/providers/paypal_card/index.js.map +1 -1
  177. package/.medusa/server/src/subscribers/paypal-order-invoice.d.ts +6 -0
  178. package/.medusa/server/src/subscribers/paypal-order-invoice.d.ts.map +1 -1
  179. package/.medusa/server/src/subscribers/paypal-order-invoice.js +9 -1
  180. package/.medusa/server/src/subscribers/paypal-order-invoice.js.map +1 -1
  181. package/.medusa/server/src/subscribers/paypal-webhook-process.d.ts +1 -0
  182. package/.medusa/server/src/subscribers/paypal-webhook-process.d.ts.map +1 -1
  183. package/.medusa/server/src/subscribers/paypal-webhook-process.js +17 -4
  184. package/.medusa/server/src/subscribers/paypal-webhook-process.js.map +1 -1
  185. package/CHANGELOG.md +19 -0
  186. package/README.md +184 -175
  187. package/package.json +24 -5
  188. package/src/admin/index.ts +1 -1
  189. package/src/admin/routes/settings/paypal/_components/FieldRow.tsx +38 -29
  190. package/src/admin/routes/settings/paypal/_components/SectionCard.tsx +29 -26
  191. package/src/admin/routes/settings/paypal/_components/Tabs.tsx +49 -48
  192. package/src/admin/routes/settings/paypal/_components/Toast.tsx +63 -52
  193. package/src/admin/routes/settings/paypal/_utils/adminFetch.ts +52 -32
  194. package/src/admin/routes/settings/paypal/additional-settings/page.tsx +246 -139
  195. package/src/admin/routes/settings/paypal/advanced-card-payments/page.tsx +208 -123
  196. package/src/admin/routes/settings/paypal/apple-pay/page.tsx +9 -5
  197. package/src/admin/routes/settings/paypal/connection/page.tsx +974 -908
  198. package/src/admin/routes/settings/paypal/google-pay/page.tsx +9 -5
  199. package/src/admin/routes/settings/paypal/page.tsx +14 -13
  200. package/src/admin/routes/settings/paypal/pay-later-messaging/page.tsx +9 -5
  201. package/src/admin/routes/settings/paypal/paypal-settings/page.tsx +304 -273
  202. package/src/api/admin/payment-collections/[id]/payment-sessions/route.ts +48 -39
  203. package/src/api/admin/paypal/disconnect/route.ts +15 -14
  204. package/src/api/admin/paypal/environment/route.ts +34 -32
  205. package/src/api/admin/paypal/onboard-complete/route.ts +61 -50
  206. package/src/api/admin/paypal/onboarding-link/route.ts +91 -76
  207. package/src/api/admin/paypal/onboarding-status/route.ts +21 -20
  208. package/src/api/admin/paypal/save-credentials/route.ts +48 -37
  209. package/src/api/admin/paypal/settings/route.ts +63 -45
  210. package/src/api/admin/paypal/status/route.ts +29 -17
  211. package/src/api/hooks/paypal/onboard-return/route.ts +15 -15
  212. package/src/api/hooks/paypal/webhook/route.ts +17 -17
  213. package/src/api/middlewares.ts +61 -61
  214. package/src/api/store/payment-collections/[id]/payment-sessions/route.ts +63 -54
  215. package/src/api/store/paypal/capture-order/route.ts +416 -370
  216. package/src/api/store/paypal/config/route.ts +121 -115
  217. package/src/api/store/paypal/create-order/route.ts +586 -539
  218. package/src/api/store/paypal/onboard-return/route.ts +116 -113
  219. package/src/api/store/paypal/settings/route.ts +29 -19
  220. package/src/api/store/paypal/webhook/route.ts +380 -314
  221. package/src/api/store/paypal-complete/route.ts +157 -128
  222. package/src/api/utils/rate-limit.ts +143 -129
  223. package/src/index.ts +1 -1
  224. package/src/jobs/paypal-webhook-retry.ts +257 -241
  225. package/src/modules/paypal/index.ts +9 -8
  226. package/src/modules/paypal/migrations/20260115120000_create_paypal_connection.ts +33 -33
  227. package/src/modules/paypal/migrations/20260123090000_create_paypal_settings.ts +22 -22
  228. package/src/modules/paypal/migrations/20260201090000_create_paypal_webhook_event.ts +29 -29
  229. package/src/modules/paypal/migrations/20260401090000_create_paypal_metric.ts +27 -27
  230. package/src/modules/paypal/migrations/20260701090000_add_paypal_webhook_event_processing.ts +31 -31
  231. package/src/modules/paypal/migrations/20261101090000_remove_paypal_reconciliation_status.ts +25 -25
  232. package/src/modules/paypal/migrations/20261201090000_remove_paypal_audit_log.ts +26 -26
  233. package/src/modules/paypal/migrations/20270101090000_set_paypal_environment_default_live.ts +15 -11
  234. package/src/modules/paypal/migrations/20270102090000_add_paypal_seller_email.ts +15 -11
  235. package/src/modules/paypal/migrations/20270103090000_add_paypal_seller_merchant_id.ts +15 -11
  236. package/src/modules/paypal/migrations/20270201000000_add_webhook_dead_letter.ts +17 -17
  237. package/src/modules/paypal/migrations/20270202000000_align_nullable_defaults.ts +44 -44
  238. package/src/modules/paypal/migrations/20270301000000_add_webhook_transmission_id_index.ts +15 -15
  239. package/src/modules/paypal/models/paypal_connection.ts +28 -23
  240. package/src/modules/paypal/models/paypal_metric.ts +13 -9
  241. package/src/modules/paypal/models/paypal_settings.ts +13 -8
  242. package/src/modules/paypal/models/paypal_webhook_event.ts +26 -19
  243. package/src/modules/paypal/payment-provider/base-provider.ts +287 -275
  244. package/src/modules/paypal/payment-provider/card-service.ts +927 -855
  245. package/src/modules/paypal/payment-provider/index.ts +14 -15
  246. package/src/modules/paypal/payment-provider/service.ts +906 -836
  247. package/src/modules/paypal/payment-provider/status-utils.ts +59 -59
  248. package/src/modules/paypal/payment-provider/webhook-utils.ts +109 -109
  249. package/src/modules/paypal/service.ts +362 -115
  250. package/src/modules/paypal/types/config.ts +70 -65
  251. package/src/modules/paypal/utils/amounts.ts +123 -107
  252. package/src/modules/paypal/utils/core-workflow.ts +46 -46
  253. package/src/modules/paypal/utils/credential-resolver.ts +275 -271
  254. package/src/modules/paypal/utils/currencies.ts +97 -84
  255. package/src/modules/paypal/utils/partner.ts +8 -8
  256. package/src/modules/paypal/utils/payment-session.ts +144 -138
  257. package/src/modules/paypal/utils/paypal-auth.ts +6 -5
  258. package/src/modules/paypal/utils/paypal-fetch.ts +197 -181
  259. package/src/modules/paypal/utils/provider-ids.ts +21 -15
  260. package/src/modules/paypal/utils/secret-crypto.ts +226 -197
  261. package/src/modules/paypal/utils/webhook-verify.ts +61 -61
  262. package/src/modules/paypal/webhook-processor.ts +641 -573
  263. package/src/providers/paypal/index.ts +9 -8
  264. package/src/providers/paypal_card/index.ts +9 -8
  265. package/src/subscribers/paypal-order-invoice.ts +180 -173
  266. package/src/subscribers/paypal-webhook-process.ts +147 -131
  267. package/tsconfig.json +21 -31
@@ -1,573 +1,641 @@
1
- import type { MedusaContainer } from "@medusajs/framework/types"
2
- import { Modules } from "@medusajs/framework/utils"
3
- import { runCoreWorkflow } from "./utils/core-workflow"
4
- import { isPayPalProviderId, PAYPAL_PROVIDER_IDS } from "./utils/provider-ids"
5
-
6
-
7
- export const EVENT_STATUS_MAP: Record<
8
- string,
9
- "authorized" | "captured" | "canceled" | "error"
10
- > = {
11
- "CHECKOUT.ORDER.APPROVED": "authorized",
12
- "CHECKOUT.ORDER.CANCELLED": "canceled",
13
- "PAYMENT.CAPTURE.COMPLETED": "captured",
14
- "PAYMENT.CAPTURE.DENIED": "error",
15
- "PAYMENT.CAPTURE.PENDING": "authorized",
16
- "PAYMENT.CAPTURE.REFUNDED": "canceled",
17
- "PAYMENT.CAPTURE.REVERSED": "canceled",
18
- "PAYMENT.AUTHORIZATION.CREATED": "authorized",
19
- "PAYMENT.AUTHORIZATION.VOIDED": "canceled",
20
- "PAYMENT.AUTHORIZATION.DENIED": "error",
21
- "PAYMENT.AUTHORIZATION.EXPIRED": "canceled",
22
- "PAYMENT.REFUND.COMPLETED": "canceled",
23
- "PAYMENT.REFUND.DENIED": "error",
24
- }
25
-
26
-
27
- const ALLOWED_TRANSITIONS: Record<string, Set<string>> = {
28
- pending: new Set(["authorized", "captured", "canceled", "error"]),
29
- authorized: new Set(["captured", "canceled", "error"]),
30
- captured: new Set(["canceled"]),
31
- canceled: new Set([]),
32
- error: new Set(["authorized", "captured", "canceled"]),
33
- }
34
-
35
- export function isTransitionAllowed(from: string, to: string): boolean {
36
- return ALLOWED_TRANSITIONS[from]?.has(to) ?? false
37
- }
38
-
39
-
40
- export const SUPPORTED_EVENT_PREFIXES = [
41
- "PAYMENT.CAPTURE.",
42
- "CHECKOUT.ORDER.",
43
- "PAYMENT.AUTHORIZATION.",
44
- "PAYMENT.REFUND.",
45
- ]
46
-
47
- export function isAllowedEventType(eventType: string): boolean {
48
- return SUPPORTED_EVENT_PREFIXES.some((prefix) => eventType.startsWith(prefix))
49
- }
50
-
51
-
52
- const NON_RETRYABLE_PATTERNS = [
53
- "payment collection not found",
54
- "no paypal session",
55
- "session not found",
56
- "cart not found",
57
- "no payment collection",
58
- ]
59
-
60
- export function isRetryableError(error: unknown): boolean {
61
- const message = String(
62
- error instanceof Error ? error.message : error ?? ""
63
- ).toLowerCase()
64
- return !NON_RETRYABLE_PATTERNS.some((p) => message.includes(p))
65
- }
66
-
67
-
68
- const RETRY_SCHEDULE_MINUTES = [2, 10, 30, 60, 120]
69
- export const MAX_WEBHOOK_ATTEMPTS = RETRY_SCHEDULE_MINUTES.length + 1
70
-
71
- export function computeNextRetryAt(attemptCount: number): Date | null {
72
- const idx = attemptCount - 1
73
- const delayMinutes = RETRY_SCHEDULE_MINUTES[idx]
74
- if (delayMinutes === undefined || attemptCount <= 0) return null
75
- return new Date(Date.now() + delayMinutes * 60 * 1000)
76
- }
77
-
78
-
79
- export function normalizeResource(payload: Record<string, any>): Record<string, any> {
80
- const resource = payload?.resource
81
- if (!resource) return {}
82
- if (typeof resource === "string") {
83
- try {
84
- return JSON.parse(resource)
85
- } catch {
86
- return {}
87
- }
88
- }
89
- return resource as Record<string, any>
90
- }
91
-
92
- export function normalizeEventVersion(payload: Record<string, any>): string | null {
93
- const raw =
94
- payload?.event_version ??
95
- payload?.resource_version ??
96
- payload?.resource?.resource_version ??
97
- payload?.resource?.version ??
98
- null
99
- if (!raw) return null
100
- return String(raw).trim().replace(/^v/i, "")
101
- }
102
-
103
-
104
- /** Pull the capture id out of a refund resource's "up" HATEOAS link. */
105
- export function extractCaptureIdFromLinks(
106
- resource: Record<string, any>
107
- ): string | null {
108
- const links = Array.isArray(resource?.links) ? resource.links : []
109
- for (const link of links) {
110
- const href = String(link?.href || "")
111
- const match = href.match(/\/captures\/([A-Za-z0-9-]+)/)
112
- if (match) return match[1]
113
- }
114
- return null
115
- }
116
-
117
- export interface ExtractedIdentifiers {
118
- orderId: string | null
119
- captureId: string | null
120
- refundId: string | null
121
- cartId: string | null
122
- }
123
-
124
- export function extractIdentifiers(
125
- resource: Record<string, any>,
126
- eventType: string
127
- ): ExtractedIdentifiers {
128
- const related = resource?.supplementary_data?.related_ids || {}
129
- const isOrder = eventType.startsWith("CHECKOUT.ORDER.")
130
- const isCapture = eventType.startsWith("PAYMENT.CAPTURE.")
131
- const isAuthorization = eventType.startsWith("PAYMENT.AUTHORIZATION.")
132
- const isRefund = eventType.startsWith("PAYMENT.REFUND.")
133
-
134
- let orderId: string | null = null
135
- let captureId: string | null = null
136
- let refundId: string | null = null
137
- let cartId: string | null = null
138
-
139
- if (isOrder) {
140
- orderId = String(resource?.id || "").trim() || null
141
- cartId =
142
- String(
143
- resource?.purchase_units?.[0]?.custom_id || resource?.custom_id || ""
144
- ).trim() || null
145
- captureId =
146
- String(
147
- resource?.purchase_units?.[0]?.payments?.captures?.[0]?.id || ""
148
- ).trim() || null
149
- } else if (isCapture) {
150
- // PAYMENT.CAPTURE.REFUNDED / REVERSED carry a *refund* resource (its `id`
151
- // is the refund id, with an "up" link to the capture) — treating that id
152
- // as the capture id would corrupt the session's stored capture_id.
153
- const isRefundShaped =
154
- eventType === "PAYMENT.CAPTURE.REFUNDED" ||
155
- eventType === "PAYMENT.CAPTURE.REVERSED"
156
- if (isRefundShaped) {
157
- refundId = String(resource?.id || "").trim() || null
158
- captureId =
159
- String(related?.capture_id || "").trim() ||
160
- extractCaptureIdFromLinks(resource) ||
161
- null
162
- } else {
163
- captureId = String(resource?.id || "").trim() || null
164
- }
165
- orderId = String(related?.order_id || "").trim() || null
166
- cartId = String(resource?.custom_id || "").trim() || null
167
- } else if (isAuthorization) {
168
- orderId = String(related?.order_id || "").trim() || null
169
- cartId = String(resource?.custom_id || "").trim() || null
170
- } else if (isRefund) {
171
- refundId = String(resource?.id || "").trim() || null
172
- orderId = String(related?.order_id || "").trim() || null
173
- captureId = String(related?.capture_id || "").trim() || null
174
- // The refund resource carries the capture's custom_id (the cart id) when it
175
- // was set on the purchase unit — use it so refunds resolve directly instead
176
- // of always falling back to a session scan.
177
- cartId = String(resource?.custom_id || "").trim() || null
178
- }
179
-
180
- return { orderId, captureId, refundId, cartId }
181
- }
182
-
183
-
184
- interface ResolvedSession {
185
- sessionId: string
186
- sessionData: Record<string, any>
187
- sessionStatus: string
188
- collectionId: string
189
- }
190
-
191
- async function findPayPalSession(
192
- container: MedusaContainer,
193
- cartId: string
194
- ): Promise<ResolvedSession | null> {
195
- const paymentModule = container.resolve(Modules.PAYMENT) as any
196
-
197
- let collections: any[]
198
- try {
199
- collections = await paymentModule.listPaymentCollections(
200
- { cart_id: [cartId] },
201
- { take: 1 }
202
- )
203
- } catch (e: any) {
204
- throw new Error(`payment collection not found for cart ${cartId}: ${e?.message}`)
205
- }
206
-
207
- const collection = collections?.[0]
208
- if (!collection?.id) {
209
- throw new Error(`payment collection not found for cart ${cartId}`)
210
- }
211
-
212
- const sessions = await paymentModule.listPaymentSessions({
213
- payment_collection_id: collection.id,
214
- }, { take: 50 })
215
-
216
- const paypalSession = (sessions || [])
217
- .filter((s: any) => isPayPalProviderId(s.provider_id))
218
- .sort(
219
- (a: any, b: any) =>
220
- new Date(b.created_at || 0).getTime() -
221
- new Date(a.created_at || 0).getTime()
222
- )[0]
223
-
224
- if (!paypalSession) {
225
- throw new Error(
226
- `no paypal session found in collection ${collection.id} for cart ${cartId}`
227
- )
228
- }
229
-
230
- return {
231
- sessionId: paypalSession.id,
232
- sessionData: (paypalSession.data || {}) as Record<string, any>,
233
- sessionStatus: String(paypalSession.status || "pending"),
234
- collectionId: collection.id,
235
- }
236
- }
237
-
238
-
239
- function mergeRefunds(existing: any[], incoming: any[]): any[] {
240
- const seen = new Set<string>()
241
- const merged: any[] = []
242
- for (const refund of [...existing, ...incoming]) {
243
- const id = String(refund?.id || "")
244
- if (id && seen.has(id)) continue
245
- if (id) seen.add(id)
246
- merged.push(refund)
247
- }
248
- return merged
249
- }
250
-
251
- async function applyStatusToSession(
252
- container: MedusaContainer,
253
- resolved: ResolvedSession,
254
- status: string | null,
255
- patch: Record<string, unknown>
256
- ): Promise<void> {
257
- const paymentModule = container.resolve(Modules.PAYMENT) as any
258
-
259
- // A null status means "record the data but keep the current session status"
260
- // (e.g. a partial refund must not cancel a captured session).
261
- if (status !== null && !isTransitionAllowed(resolved.sessionStatus, status)) {
262
- console.info(
263
- `[PayPal] webhook: skipping disallowed transition ${resolved.sessionStatus} → ${status} for session ${resolved.sessionId}`
264
- )
265
- return
266
- }
267
-
268
- const existingPaypal = (resolved.sessionData.paypal || {}) as Record<string, any>
269
- const existingRefunds = Array.isArray(existingPaypal.refunds)
270
- ? existingPaypal.refunds
271
- : []
272
- const incomingRefunds = Array.isArray(patch.refunds)
273
- ? (patch.refunds as any[])
274
- : null
275
- const nextRefunds = incomingRefunds
276
- ? mergeRefunds(existingRefunds, incomingRefunds)
277
- : existingRefunds
278
-
279
- // Drop undefined/null values from the patch so a webhook that lacks an
280
- // identifier (e.g. a capture event with no related_ids) can never clobber
281
- // stored fields like `order_id` with null.
282
- const cleanPatch: Record<string, unknown> = {}
283
- for (const [k, v] of Object.entries(patch)) {
284
- if (v !== undefined && v !== null) cleanPatch[k] = v
285
- }
286
-
287
- await paymentModule.updatePaymentSession({
288
- id: resolved.sessionId,
289
- status: status === null ? resolved.sessionStatus : status,
290
- data: {
291
- ...resolved.sessionData,
292
- paypal: {
293
- ...existingPaypal,
294
- ...cleanPatch,
295
- refunds: nextRefunds,
296
- },
297
- },
298
- })
299
- }
300
-
301
-
302
- /**
303
- * True when a refund resource demonstrably covers less than the captured
304
- * amount. Uses the refund's cumulative `total_refunded_amount` (falling back
305
- * to the single refund amount) against the capture amount stored on the
306
- * session (falling back to the session total). Returns false — i.e. treat as
307
- * a full refund, matching the previous behavior — whenever the amounts can't
308
- * be determined.
309
- */
310
- export function isPartialRefund(
311
- resource: Record<string, any>,
312
- sessionData: Record<string, any>
313
- ): boolean {
314
- const refundedRaw =
315
- resource?.seller_payable_breakdown?.total_refunded_amount?.value ??
316
- resource?.amount?.value
317
- const refunded = Number(refundedRaw)
318
- if (!Number.isFinite(refunded) || refunded <= 0) return false
319
-
320
- const paypal = (sessionData?.paypal || {}) as Record<string, any>
321
- const capturedRaw =
322
- paypal?.capture?.amount?.value ??
323
- paypal?.capture?.seller_receivable_breakdown?.gross_amount?.value ??
324
- sessionData?.amount
325
- const captured = Number(capturedRaw)
326
- if (!Number.isFinite(captured) || captured <= 0) return false
327
-
328
- // Tolerance for floating-point noise; amounts are decimal strings from
329
- // PayPal or the session's stored major-unit amount.
330
- return refunded + 0.005 < captured
331
- }
332
-
333
- /**
334
- * Whether the webhook processor may complete a paid-but-unfinalized cart.
335
- *
336
- * The storefront's `/store/paypal-complete` call is the primary completion
337
- * path, but it only runs in the buyer's browser. If the tab closes, crashes,
338
- * or reloads between the capture and that call, the money is captured and no
339
- * Medusa order is ever created. The PAYMENT.CAPTURE.COMPLETED webhook is the
340
- * server-side safety net for exactly that gap.
341
- *
342
- * Enabled by default (completing a cart whose payment settled is the correct
343
- * outcome); set PAYPAL_WEBHOOK_COMPLETE_CART=false to disable.
344
- */
345
- export function isWebhookCartCompletionEnabled(
346
- envValue: string | undefined = process.env.PAYPAL_WEBHOOK_COMPLETE_CART
347
- ): boolean {
348
- const v = String(envValue ?? "").trim().toLowerCase()
349
- return !(v === "false" || v === "0" || v === "off" || v === "no")
350
- }
351
-
352
- /** Events that prove settled funds and may therefore complete the cart. */
353
- export function isCartCompletingEventType(eventType: string): boolean {
354
- return eventType === "PAYMENT.CAPTURE.COMPLETED"
355
- }
356
-
357
- /**
358
- * Complete the cart if (and only if) it is still incomplete. Returns true when
359
- * this call completed it. Racing the storefront's own completion is expected
360
- * and safe: on a workflow error the cart is re-checked, and "someone else
361
- * completed it first" counts as success. A genuine failure is re-thrown so the
362
- * webhook retry schedule (and ultimately the dead-letter queue) keeps the
363
- * paid-but-unfinalized cart visible instead of silently dropping it.
364
- */
365
- async function completeCartIfPending(
366
- container: MedusaContainer,
367
- cartId: string,
368
- eventType: string
369
- ): Promise<boolean> {
370
- const query = container.resolve("query") as any
371
- const { data } = await query.graph({
372
- entity: "cart",
373
- fields: ["id", "completed_at"],
374
- filters: { id: cartId },
375
- })
376
- const cart = data?.[0]
377
- if (!cart || cart.completed_at) return false
378
-
379
- try {
380
- const { result } = await runCoreWorkflow<{ id: string }, { id?: string }>(
381
- container,
382
- "complete-cart",
383
- { id: cartId }
384
- )
385
- console.info(
386
- `[PayPal] webhook: completed cart ${cartId} from ${eventType} (order_id=${result?.id ?? "n/a"})`
387
- )
388
- return true
389
- } catch (e: unknown) {
390
- const recheck = await query
391
- .graph({ entity: "cart", fields: ["id", "completed_at"], filters: { id: cartId } })
392
- .catch(() => ({ data: [] as any[] }))
393
- if (recheck?.data?.[0]?.completed_at) {
394
- // The storefront (or a concurrent webhook) won the race — that's success.
395
- return false
396
- }
397
- const msg = e instanceof Error ? e.message : String(e)
398
- throw new Error(`webhook cart completion failed for ${cartId}: ${msg}`)
399
- }
400
- }
401
-
402
- export interface ProcessResult {
403
- orderId: string | null
404
- captureId: string | null
405
- refundId: string | null
406
- cartId: string | null
407
- sessionUpdated: boolean
408
- cartCompleted: boolean
409
- }
410
-
411
- export async function processPayPalWebhookEvent(
412
- container: MedusaContainer,
413
- input: {
414
- eventType: string
415
- payload: Record<string, any>
416
- }
417
- ): Promise<ProcessResult> {
418
- const resource = normalizeResource(input.payload)
419
- const { orderId, captureId, refundId, cartId: rawCartId } = extractIdentifiers(
420
- resource,
421
- input.eventType
422
- )
423
-
424
- const refundReason =
425
- String(
426
- resource?.note_to_payer || resource?.reason || resource?.seller_note || ""
427
- ).trim() || undefined
428
- const refundReasonCode =
429
- String(resource?.reason_code || resource?.reasonCode || "").trim() ||
430
- undefined
431
-
432
- const targetStatus = EVENT_STATUS_MAP[input.eventType]
433
- if (!targetStatus) {
434
- return {
435
- orderId,
436
- captureId,
437
- refundId,
438
- cartId: rawCartId,
439
- sessionUpdated: false,
440
- cartCompleted: false,
441
- }
442
- }
443
-
444
- let cartId = rawCartId
445
-
446
- if (!cartId && (orderId || captureId)) {
447
- try {
448
- const paymentModule = container.resolve(Modules.PAYMENT) as any
449
- const PAGE_SIZE = 200
450
- const MAX_PAGES = 5
451
- let matchedSession: Record<string, unknown> | null = null
452
- let totalScanned = 0
453
-
454
- for (let page = 0; page < MAX_PAGES && !matchedSession; page++) {
455
- const sessions = await paymentModule.listPaymentSessions(
456
- { provider_id: [...PAYPAL_PROVIDER_IDS] },
457
- { take: PAGE_SIZE, skip: page * PAGE_SIZE, order: { created_at: "DESC" } }
458
- )
459
- if (!sessions || sessions.length === 0) break
460
- totalScanned += sessions.length
461
- matchedSession =
462
- sessions.find((s: Record<string, unknown>) => {
463
- const pp =
464
- (((s.data || {}) as Record<string, unknown>).paypal as Record<string, unknown>) || {}
465
- if (orderId && pp.order_id === orderId) return true
466
- if (captureId && pp.capture_id === captureId) return true
467
- return false
468
- }) || null
469
- if (sessions.length < PAGE_SIZE) break
470
- }
471
-
472
- if (!matchedSession && totalScanned >= MAX_PAGES * PAGE_SIZE) {
473
- console.warn(
474
- `[PayPal] webhook: cartId fallback scan hit limit (${totalScanned} sessions). ` +
475
- `Event ${input.eventType} may be lost. Ensure custom_id is set on PayPal orders.`,
476
- { orderId, captureId }
477
- )
478
- }
479
-
480
- if (matchedSession?.payment_collection_id) {
481
- const colls = await paymentModule.listPaymentCollections(
482
- { id: [matchedSession.payment_collection_id] },
483
- { take: 1 }
484
- )
485
- cartId = String(colls?.[0]?.cart_id || "").trim() || null
486
- }
487
- } catch (e: unknown) {
488
- console.warn(
489
- `[PayPal] webhook: cartId fallback lookup failed for ${input.eventType}:`,
490
- e instanceof Error ? e.message : e
491
- )
492
- }
493
- }
494
-
495
- let sessionUpdated = false
496
- let cartCompleted = false
497
- let sessionEligibleForCompletion = false
498
-
499
- if (cartId) {
500
- const resolved = await findPayPalSession(container, cartId)
501
- if (resolved) {
502
- // A canceled session must never complete a cart; anything that is (or
503
- // may legally become) captured can.
504
- sessionEligibleForCompletion =
505
- resolved.sessionStatus === "captured" ||
506
- isTransitionAllowed(resolved.sessionStatus, "captured")
507
- const refundEntry = refundId
508
- ? [
509
- {
510
- id: refundId,
511
- status: resource?.status,
512
- reason: refundReason,
513
- reason_code: refundReasonCode,
514
- amount: resource?.amount,
515
- raw: resource,
516
- },
517
- ]
518
- : null
519
-
520
- // A PARTIAL refund must not cancel the session: PayPal fires
521
- // PAYMENT.CAPTURE.REFUNDED / PAYMENT.REFUND.COMPLETED for partial
522
- // refunds too, and flipping a substantially-paid session to "canceled"
523
- // misrepresents the payment. Record the refund but keep the status
524
- // unless the cumulative refunded total covers the captured amount (or
525
- // the amounts can't be determined, preserving the old full-refund
526
- // behavior).
527
- let effectiveStatus: string | null = targetStatus
528
- const isRefundEvent =
529
- input.eventType === "PAYMENT.CAPTURE.REFUNDED" ||
530
- input.eventType === "PAYMENT.CAPTURE.REVERSED" ||
531
- input.eventType === "PAYMENT.REFUND.COMPLETED"
532
- if (isRefundEvent && targetStatus === "canceled") {
533
- if (isPartialRefund(resource, resolved.sessionData)) {
534
- effectiveStatus = null
535
- }
536
- }
537
-
538
- await applyStatusToSession(container, resolved, effectiveStatus, {
539
- order_id: orderId ?? undefined,
540
- capture_id: captureId ?? resolved.sessionData.paypal?.capture_id ?? undefined,
541
- refund_id: refundId ?? undefined,
542
- refund_status: refundId ? resource?.status : undefined,
543
- refund_reason: refundReason,
544
- refund_reason_code: refundReasonCode,
545
- ...(refundEntry ? { refunds: refundEntry } : {}),
546
- webhook_event_type: input.eventType,
547
- last_webhook_at: new Date().toISOString(),
548
- })
549
- sessionUpdated = true
550
- }
551
- } else {
552
- console.warn(
553
- `[PayPal] webhook: could not resolve cartId for event ${input.eventType}`,
554
- { orderId, captureId, refundId }
555
- )
556
- }
557
-
558
- // Server-side safety net: the funds settled but the buyer's browser may
559
- // never call /store/paypal-complete (closed tab, crash, mobile redirect
560
- // loss). Complete the cart here so a captured payment always produces an
561
- // order. Runs after the session update so authorizePayment sees the capture.
562
- if (
563
- cartId &&
564
- sessionUpdated &&
565
- sessionEligibleForCompletion &&
566
- isCartCompletingEventType(input.eventType) &&
567
- isWebhookCartCompletionEnabled()
568
- ) {
569
- cartCompleted = await completeCartIfPending(container, cartId, input.eventType)
570
- }
571
-
572
- return { orderId, captureId, refundId, cartId, sessionUpdated, cartCompleted }
573
- }
1
+ import type { MedusaContainer } from "@medusajs/framework/types"
2
+ import { Modules } from "@medusajs/framework/utils"
3
+ import { runCoreWorkflow } from "./utils/core-workflow"
4
+ import { isPayPalProviderId, PAYPAL_PROVIDER_IDS } from "./utils/provider-ids"
5
+
6
+ /**
7
+ * Core webhook processing shared by the async subscriber and the retry cron.
8
+ *
9
+ * Given a verified, persisted PayPal event, this resolves the cart's PayPal
10
+ * payment session, applies the event's status transition (guarded by
11
+ * `ALLOWED_TRANSITIONS`), merges capture/refund identifiers onto the session,
12
+ * and — for settled captures — completes a cart the buyer's browser never
13
+ * finalized. Everything here is pure or container-driven so it can be
14
+ * unit-tested without an HTTP layer.
15
+ */
16
+
17
+ /** PayPal event type → Medusa payment-session status it should produce. */
18
+ export const EVENT_STATUS_MAP: Record<
19
+ string,
20
+ "authorized" | "captured" | "canceled" | "error"
21
+ > = {
22
+ "CHECKOUT.ORDER.APPROVED": "authorized",
23
+ "CHECKOUT.ORDER.CANCELLED": "canceled",
24
+ "PAYMENT.CAPTURE.COMPLETED": "captured",
25
+ "PAYMENT.CAPTURE.DENIED": "error",
26
+ "PAYMENT.CAPTURE.PENDING": "authorized",
27
+ "PAYMENT.CAPTURE.REFUNDED": "canceled",
28
+ "PAYMENT.CAPTURE.REVERSED": "canceled",
29
+ "PAYMENT.AUTHORIZATION.CREATED": "authorized",
30
+ "PAYMENT.AUTHORIZATION.VOIDED": "canceled",
31
+ "PAYMENT.AUTHORIZATION.DENIED": "error",
32
+ "PAYMENT.AUTHORIZATION.EXPIRED": "canceled",
33
+ "PAYMENT.REFUND.COMPLETED": "canceled",
34
+ "PAYMENT.REFUND.DENIED": "error",
35
+ }
36
+
37
+ const ALLOWED_TRANSITIONS: Record<string, Set<string>> = {
38
+ pending: new Set(["authorized", "captured", "canceled", "error"]),
39
+ authorized: new Set(["captured", "canceled", "error"]),
40
+ captured: new Set(["canceled"]),
41
+ canceled: new Set([]),
42
+ error: new Set(["authorized", "captured", "canceled"]),
43
+ }
44
+
45
+ /**
46
+ * Whether a session may move from `from` to `to`. Out-of-order or replayed
47
+ * webhooks must never regress a session (e.g. captured → authorized).
48
+ */
49
+ export function isTransitionAllowed(from: string, to: string): boolean {
50
+ return ALLOWED_TRANSITIONS[from]?.has(to) ?? false
51
+ }
52
+
53
+ /** Event families this plugin handles; anything else is recorded as ignored. */
54
+ export const SUPPORTED_EVENT_PREFIXES = [
55
+ "PAYMENT.CAPTURE.",
56
+ "CHECKOUT.ORDER.",
57
+ "PAYMENT.AUTHORIZATION.",
58
+ "PAYMENT.REFUND.",
59
+ ]
60
+
61
+ /** True for event types under one of `SUPPORTED_EVENT_PREFIXES`. */
62
+ export function isAllowedEventType(eventType: string): boolean {
63
+ return SUPPORTED_EVENT_PREFIXES.some((prefix) => eventType.startsWith(prefix))
64
+ }
65
+
66
+ const NON_RETRYABLE_PATTERNS = [
67
+ "payment collection not found",
68
+ "no paypal session",
69
+ "session not found",
70
+ "cart not found",
71
+ "no payment collection",
72
+ ]
73
+
74
+ /**
75
+ * Whether a processing failure is worth retrying. Missing carts/sessions are
76
+ * permanent and go straight to the dead-letter queue; everything else (DB or
77
+ * PayPal hiccups) is scheduled for retry.
78
+ */
79
+ export function isRetryableError(error: unknown): boolean {
80
+ const message = String(
81
+ error instanceof Error ? error.message : (error ?? "")
82
+ ).toLowerCase()
83
+ return !NON_RETRYABLE_PATTERNS.some((p) => message.includes(p))
84
+ }
85
+
86
+ /** Backoff (in minutes) applied after the 1st, 2nd, … failed attempt. */
87
+ const RETRY_SCHEDULE_MINUTES = [2, 10, 30, 60, 120]
88
+
89
+ /** Initial attempt plus one retry per entry in the schedule. */
90
+ export const MAX_WEBHOOK_ATTEMPTS = RETRY_SCHEDULE_MINUTES.length + 1
91
+
92
+ /** When to retry after `attemptCount` failures, or null once exhausted. */
93
+ export function computeNextRetryAt(attemptCount: number): Date | null {
94
+ const idx = attemptCount - 1
95
+ const delayMinutes = RETRY_SCHEDULE_MINUTES[idx]
96
+ if (delayMinutes === undefined || attemptCount <= 0) return null
97
+ return new Date(Date.now() + delayMinutes * 60 * 1000)
98
+ }
99
+
100
+ /**
101
+ * The event's `resource` object. PayPal occasionally delivers it as a JSON
102
+ * string; anything unparseable yields `{}` so downstream lookups stay safe.
103
+ */
104
+ export function normalizeResource(
105
+ payload: Record<string, any>
106
+ ): Record<string, any> {
107
+ const resource = payload?.resource
108
+ if (!resource) return {}
109
+ if (typeof resource === "string") {
110
+ try {
111
+ return JSON.parse(resource)
112
+ } catch {
113
+ return {}
114
+ }
115
+ }
116
+ return resource as Record<string, any>
117
+ }
118
+
119
+ /** Event/resource version with any leading "v" stripped, or null. */
120
+ export function normalizeEventVersion(
121
+ payload: Record<string, any>
122
+ ): string | null {
123
+ const raw =
124
+ payload?.event_version ??
125
+ payload?.resource_version ??
126
+ payload?.resource?.resource_version ??
127
+ payload?.resource?.version ??
128
+ null
129
+ if (!raw) return null
130
+ return String(raw).trim().replace(/^v/i, "")
131
+ }
132
+
133
+ /** Pull the capture id out of a refund resource's "up" HATEOAS link. */
134
+ export function extractCaptureIdFromLinks(
135
+ resource: Record<string, any>
136
+ ): string | null {
137
+ const links = Array.isArray(resource?.links) ? resource.links : []
138
+ for (const link of links) {
139
+ const href = String(link?.href || "")
140
+ const match = href.match(/\/captures\/([A-Za-z0-9-]+)/)
141
+ if (match) return match[1]
142
+ }
143
+ return null
144
+ }
145
+
146
+ /** PayPal + Medusa identifiers pulled from a webhook resource. */
147
+ export interface ExtractedIdentifiers {
148
+ orderId: string | null
149
+ captureId: string | null
150
+ refundId: string | null
151
+ cartId: string | null
152
+ }
153
+
154
+ /**
155
+ * Pull order / capture / refund ids and the cart id (`custom_id`) out of a
156
+ * webhook resource. The shape differs per event family, and some
157
+ * PAYMENT.CAPTURE.* events actually carry a refund resource — see inline.
158
+ */
159
+ export function extractIdentifiers(
160
+ resource: Record<string, any>,
161
+ eventType: string
162
+ ): ExtractedIdentifiers {
163
+ const related = resource?.supplementary_data?.related_ids || {}
164
+ const isOrder = eventType.startsWith("CHECKOUT.ORDER.")
165
+ const isCapture = eventType.startsWith("PAYMENT.CAPTURE.")
166
+ const isAuthorization = eventType.startsWith("PAYMENT.AUTHORIZATION.")
167
+ const isRefund = eventType.startsWith("PAYMENT.REFUND.")
168
+
169
+ let orderId: string | null = null
170
+ let captureId: string | null = null
171
+ let refundId: string | null = null
172
+ let cartId: string | null = null
173
+
174
+ if (isOrder) {
175
+ orderId = String(resource?.id || "").trim() || null
176
+ cartId =
177
+ String(
178
+ resource?.purchase_units?.[0]?.custom_id || resource?.custom_id || ""
179
+ ).trim() || null
180
+ captureId =
181
+ String(
182
+ resource?.purchase_units?.[0]?.payments?.captures?.[0]?.id || ""
183
+ ).trim() || null
184
+ } else if (isCapture) {
185
+ // PAYMENT.CAPTURE.REFUNDED / REVERSED carry a *refund* resource (its `id`
186
+ // is the refund id, with an "up" link to the capture) — treating that id
187
+ // as the capture id would corrupt the session's stored capture_id.
188
+ const isRefundShaped =
189
+ eventType === "PAYMENT.CAPTURE.REFUNDED" ||
190
+ eventType === "PAYMENT.CAPTURE.REVERSED"
191
+ if (isRefundShaped) {
192
+ refundId = String(resource?.id || "").trim() || null
193
+ captureId =
194
+ String(related?.capture_id || "").trim() ||
195
+ extractCaptureIdFromLinks(resource) ||
196
+ null
197
+ } else {
198
+ captureId = String(resource?.id || "").trim() || null
199
+ }
200
+ orderId = String(related?.order_id || "").trim() || null
201
+ cartId = String(resource?.custom_id || "").trim() || null
202
+ } else if (isAuthorization) {
203
+ orderId = String(related?.order_id || "").trim() || null
204
+ cartId = String(resource?.custom_id || "").trim() || null
205
+ } else if (isRefund) {
206
+ refundId = String(resource?.id || "").trim() || null
207
+ orderId = String(related?.order_id || "").trim() || null
208
+ captureId = String(related?.capture_id || "").trim() || null
209
+ // The refund resource carries the capture's custom_id (the cart id) when it
210
+ // was set on the purchase unit — use it so refunds resolve directly instead
211
+ // of always falling back to a session scan.
212
+ cartId = String(resource?.custom_id || "").trim() || null
213
+ }
214
+
215
+ return { orderId, captureId, refundId, cartId }
216
+ }
217
+
218
+ interface ResolvedSession {
219
+ sessionId: string
220
+ sessionData: Record<string, any>
221
+ sessionStatus: string
222
+ collectionId: string
223
+ }
224
+
225
+ async function findPayPalSession(
226
+ container: MedusaContainer,
227
+ cartId: string
228
+ ): Promise<ResolvedSession | null> {
229
+ const paymentModule = container.resolve(Modules.PAYMENT) as any
230
+
231
+ let collections: any[]
232
+ try {
233
+ collections = await paymentModule.listPaymentCollections(
234
+ { cart_id: [cartId] },
235
+ { take: 1 }
236
+ )
237
+ } catch (e: any) {
238
+ throw new Error(
239
+ `payment collection not found for cart ${cartId}: ${e?.message}`
240
+ )
241
+ }
242
+
243
+ const collection = collections?.[0]
244
+ if (!collection?.id) {
245
+ throw new Error(`payment collection not found for cart ${cartId}`)
246
+ }
247
+
248
+ const sessions = await paymentModule.listPaymentSessions(
249
+ {
250
+ payment_collection_id: collection.id,
251
+ },
252
+ { take: 50 }
253
+ )
254
+
255
+ const paypalSession = (sessions || [])
256
+ .filter((s: any) => isPayPalProviderId(s.provider_id))
257
+ .sort(
258
+ (a: any, b: any) =>
259
+ new Date(b.created_at || 0).getTime() -
260
+ new Date(a.created_at || 0).getTime()
261
+ )[0]
262
+
263
+ if (!paypalSession) {
264
+ throw new Error(
265
+ `no paypal session found in collection ${collection.id} for cart ${cartId}`
266
+ )
267
+ }
268
+
269
+ return {
270
+ sessionId: paypalSession.id,
271
+ sessionData: (paypalSession.data || {}) as Record<string, any>,
272
+ sessionStatus: String(paypalSession.status || "pending"),
273
+ collectionId: collection.id,
274
+ }
275
+ }
276
+
277
+ function mergeRefunds(existing: any[], incoming: any[]): any[] {
278
+ const seen = new Set<string>()
279
+ const merged: any[] = []
280
+ for (const refund of [...existing, ...incoming]) {
281
+ const id = String(refund?.id || "")
282
+ if (id && seen.has(id)) continue
283
+ if (id) seen.add(id)
284
+ merged.push(refund)
285
+ }
286
+ return merged
287
+ }
288
+
289
+ async function applyStatusToSession(
290
+ container: MedusaContainer,
291
+ resolved: ResolvedSession,
292
+ status: string | null,
293
+ patch: Record<string, unknown>
294
+ ): Promise<void> {
295
+ const paymentModule = container.resolve(Modules.PAYMENT) as any
296
+
297
+ // A null status means "record the data but keep the current session status"
298
+ // (e.g. a partial refund must not cancel a captured session).
299
+ if (status !== null && !isTransitionAllowed(resolved.sessionStatus, status)) {
300
+ console.info(
301
+ `[PayPal] webhook: skipping disallowed transition ${resolved.sessionStatus} → ${status} for session ${resolved.sessionId}`
302
+ )
303
+ return
304
+ }
305
+
306
+ const existingPaypal = (resolved.sessionData.paypal || {}) as Record<
307
+ string,
308
+ any
309
+ >
310
+ const existingRefunds = Array.isArray(existingPaypal.refunds)
311
+ ? existingPaypal.refunds
312
+ : []
313
+ const incomingRefunds = Array.isArray(patch.refunds)
314
+ ? (patch.refunds as any[])
315
+ : null
316
+ const nextRefunds = incomingRefunds
317
+ ? mergeRefunds(existingRefunds, incomingRefunds)
318
+ : existingRefunds
319
+
320
+ // Drop undefined/null values from the patch so a webhook that lacks an
321
+ // identifier (e.g. a capture event with no related_ids) can never clobber
322
+ // stored fields like `order_id` with null.
323
+ const cleanPatch: Record<string, unknown> = {}
324
+ for (const [k, v] of Object.entries(patch)) {
325
+ if (v !== undefined && v !== null) cleanPatch[k] = v
326
+ }
327
+
328
+ await paymentModule.updatePaymentSession({
329
+ id: resolved.sessionId,
330
+ status: status === null ? resolved.sessionStatus : status,
331
+ data: {
332
+ ...resolved.sessionData,
333
+ paypal: {
334
+ ...existingPaypal,
335
+ ...cleanPatch,
336
+ refunds: nextRefunds,
337
+ },
338
+ },
339
+ })
340
+ }
341
+
342
+ /**
343
+ * True when a refund resource demonstrably covers less than the captured
344
+ * amount. Uses the refund's cumulative `total_refunded_amount` (falling back
345
+ * to the single refund amount) against the capture amount stored on the
346
+ * session (falling back to the session total). Returns false — i.e. treat as
347
+ * a full refund, matching the previous behavior — whenever the amounts can't
348
+ * be determined.
349
+ */
350
+ export function isPartialRefund(
351
+ resource: Record<string, any>,
352
+ sessionData: Record<string, any>
353
+ ): boolean {
354
+ const refundedRaw =
355
+ resource?.seller_payable_breakdown?.total_refunded_amount?.value ??
356
+ resource?.amount?.value
357
+ const refunded = Number(refundedRaw)
358
+ if (!Number.isFinite(refunded) || refunded <= 0) return false
359
+
360
+ const paypal = (sessionData?.paypal || {}) as Record<string, any>
361
+ const capturedRaw =
362
+ paypal?.capture?.amount?.value ??
363
+ paypal?.capture?.seller_receivable_breakdown?.gross_amount?.value ??
364
+ sessionData?.amount
365
+ const captured = Number(capturedRaw)
366
+ if (!Number.isFinite(captured) || captured <= 0) return false
367
+
368
+ // Tolerance for floating-point noise; amounts are decimal strings from
369
+ // PayPal or the session's stored major-unit amount.
370
+ return refunded + 0.005 < captured
371
+ }
372
+
373
+ /**
374
+ * Whether the webhook processor may complete a paid-but-unfinalized cart.
375
+ *
376
+ * The storefront's `/store/paypal-complete` call is the primary completion
377
+ * path, but it only runs in the buyer's browser. If the tab closes, crashes,
378
+ * or reloads between the capture and that call, the money is captured and no
379
+ * Medusa order is ever created. The PAYMENT.CAPTURE.COMPLETED webhook is the
380
+ * server-side safety net for exactly that gap.
381
+ *
382
+ * Enabled by default (completing a cart whose payment settled is the correct
383
+ * outcome); set PAYPAL_WEBHOOK_COMPLETE_CART=false to disable.
384
+ */
385
+ export function isWebhookCartCompletionEnabled(
386
+ envValue: string | undefined = process.env.PAYPAL_WEBHOOK_COMPLETE_CART
387
+ ): boolean {
388
+ const v = String(envValue ?? "")
389
+ .trim()
390
+ .toLowerCase()
391
+ return !(v === "false" || v === "0" || v === "off" || v === "no")
392
+ }
393
+
394
+ /** Events that prove settled funds and may therefore complete the cart. */
395
+ export function isCartCompletingEventType(eventType: string): boolean {
396
+ return eventType === "PAYMENT.CAPTURE.COMPLETED"
397
+ }
398
+
399
+ /**
400
+ * Complete the cart if (and only if) it is still incomplete. Returns true when
401
+ * this call completed it. Racing the storefront's own completion is expected
402
+ * and safe: on a workflow error the cart is re-checked, and "someone else
403
+ * completed it first" counts as success. A genuine failure is re-thrown so the
404
+ * webhook retry schedule (and ultimately the dead-letter queue) keeps the
405
+ * paid-but-unfinalized cart visible instead of silently dropping it.
406
+ */
407
+ async function completeCartIfPending(
408
+ container: MedusaContainer,
409
+ cartId: string,
410
+ eventType: string
411
+ ): Promise<boolean> {
412
+ const query = container.resolve("query") as any
413
+ const { data } = await query.graph({
414
+ entity: "cart",
415
+ fields: ["id", "completed_at"],
416
+ filters: { id: cartId },
417
+ })
418
+ const cart = data?.[0]
419
+ if (!cart || cart.completed_at) return false
420
+
421
+ try {
422
+ const { result } = await runCoreWorkflow<{ id: string }, { id?: string }>(
423
+ container,
424
+ "complete-cart",
425
+ { id: cartId }
426
+ )
427
+ console.info(
428
+ `[PayPal] webhook: completed cart ${cartId} from ${eventType} (order_id=${result?.id ?? "n/a"})`
429
+ )
430
+ return true
431
+ } catch (e: unknown) {
432
+ const recheck = await query
433
+ .graph({
434
+ entity: "cart",
435
+ fields: ["id", "completed_at"],
436
+ filters: { id: cartId },
437
+ })
438
+ .catch(() => ({ data: [] as any[] }))
439
+ if (recheck?.data?.[0]?.completed_at) {
440
+ // The storefront (or a concurrent webhook) won the race — that's success.
441
+ return false
442
+ }
443
+ const msg = e instanceof Error ? e.message : String(e)
444
+ throw new Error(`webhook cart completion failed for ${cartId}: ${msg}`)
445
+ }
446
+ }
447
+
448
+ /** Outcome of `processPayPalWebhookEvent`, mainly for logging/metrics. */
449
+ export interface ProcessResult {
450
+ orderId: string | null
451
+ captureId: string | null
452
+ refundId: string | null
453
+ cartId: string | null
454
+ sessionUpdated: boolean
455
+ cartCompleted: boolean
456
+ }
457
+
458
+ /**
459
+ * Apply one verified PayPal webhook event to the matching payment session.
460
+ *
461
+ * Throws on failures the caller should retry (see `isRetryableError`);
462
+ * returns normally — with `sessionUpdated: false` — for events that carry no
463
+ * status mapping or whose cart cannot be resolved.
464
+ */
465
+ export async function processPayPalWebhookEvent(
466
+ container: MedusaContainer,
467
+ input: {
468
+ eventType: string
469
+ payload: Record<string, any>
470
+ }
471
+ ): Promise<ProcessResult> {
472
+ const resource = normalizeResource(input.payload)
473
+ const {
474
+ orderId,
475
+ captureId,
476
+ refundId,
477
+ cartId: rawCartId,
478
+ } = extractIdentifiers(resource, input.eventType)
479
+
480
+ const refundReason =
481
+ String(
482
+ resource?.note_to_payer || resource?.reason || resource?.seller_note || ""
483
+ ).trim() || undefined
484
+ const refundReasonCode =
485
+ String(resource?.reason_code || resource?.reasonCode || "").trim() ||
486
+ undefined
487
+
488
+ const targetStatus = EVENT_STATUS_MAP[input.eventType]
489
+ if (!targetStatus) {
490
+ return {
491
+ orderId,
492
+ captureId,
493
+ refundId,
494
+ cartId: rawCartId,
495
+ sessionUpdated: false,
496
+ cartCompleted: false,
497
+ }
498
+ }
499
+
500
+ let cartId = rawCartId
501
+
502
+ if (!cartId && (orderId || captureId)) {
503
+ try {
504
+ const paymentModule = container.resolve(Modules.PAYMENT) as any
505
+ const PAGE_SIZE = 200
506
+ const MAX_PAGES = 5
507
+ let matchedSession: Record<string, unknown> | null = null
508
+ let totalScanned = 0
509
+
510
+ for (let page = 0; page < MAX_PAGES && !matchedSession; page++) {
511
+ const sessions = await paymentModule.listPaymentSessions(
512
+ { provider_id: [...PAYPAL_PROVIDER_IDS] },
513
+ {
514
+ take: PAGE_SIZE,
515
+ skip: page * PAGE_SIZE,
516
+ order: { created_at: "DESC" },
517
+ }
518
+ )
519
+ if (!sessions || sessions.length === 0) break
520
+ totalScanned += sessions.length
521
+ matchedSession =
522
+ sessions.find((s: Record<string, unknown>) => {
523
+ const pp =
524
+ (((s.data || {}) as Record<string, unknown>).paypal as Record<
525
+ string,
526
+ unknown
527
+ >) || {}
528
+ if (orderId && pp.order_id === orderId) return true
529
+ if (captureId && pp.capture_id === captureId) return true
530
+ return false
531
+ }) || null
532
+ if (sessions.length < PAGE_SIZE) break
533
+ }
534
+
535
+ if (!matchedSession && totalScanned >= MAX_PAGES * PAGE_SIZE) {
536
+ console.warn(
537
+ `[PayPal] webhook: cartId fallback scan hit limit (${totalScanned} sessions). ` +
538
+ `Event ${input.eventType} may be lost. Ensure custom_id is set on PayPal orders.`,
539
+ { orderId, captureId }
540
+ )
541
+ }
542
+
543
+ if (matchedSession?.payment_collection_id) {
544
+ const colls = await paymentModule.listPaymentCollections(
545
+ { id: [matchedSession.payment_collection_id] },
546
+ { take: 1 }
547
+ )
548
+ cartId = String(colls?.[0]?.cart_id || "").trim() || null
549
+ }
550
+ } catch (e: unknown) {
551
+ console.warn(
552
+ `[PayPal] webhook: cartId fallback lookup failed for ${input.eventType}:`,
553
+ e instanceof Error ? e.message : e
554
+ )
555
+ }
556
+ }
557
+
558
+ let sessionUpdated = false
559
+ let cartCompleted = false
560
+ let sessionEligibleForCompletion = false
561
+
562
+ if (cartId) {
563
+ const resolved = await findPayPalSession(container, cartId)
564
+ if (resolved) {
565
+ // A canceled session must never complete a cart; anything that is (or
566
+ // may legally become) captured can.
567
+ sessionEligibleForCompletion =
568
+ resolved.sessionStatus === "captured" ||
569
+ isTransitionAllowed(resolved.sessionStatus, "captured")
570
+ const refundEntry = refundId
571
+ ? [
572
+ {
573
+ id: refundId,
574
+ status: resource?.status,
575
+ reason: refundReason,
576
+ reason_code: refundReasonCode,
577
+ amount: resource?.amount,
578
+ raw: resource,
579
+ },
580
+ ]
581
+ : null
582
+
583
+ // A PARTIAL refund must not cancel the session: PayPal fires
584
+ // PAYMENT.CAPTURE.REFUNDED / PAYMENT.REFUND.COMPLETED for partial
585
+ // refunds too, and flipping a substantially-paid session to "canceled"
586
+ // misrepresents the payment. Record the refund but keep the status
587
+ // unless the cumulative refunded total covers the captured amount (or
588
+ // the amounts can't be determined, preserving the old full-refund
589
+ // behavior).
590
+ let effectiveStatus: string | null = targetStatus
591
+ const isRefundEvent =
592
+ input.eventType === "PAYMENT.CAPTURE.REFUNDED" ||
593
+ input.eventType === "PAYMENT.CAPTURE.REVERSED" ||
594
+ input.eventType === "PAYMENT.REFUND.COMPLETED"
595
+ if (isRefundEvent && targetStatus === "canceled") {
596
+ if (isPartialRefund(resource, resolved.sessionData)) {
597
+ effectiveStatus = null
598
+ }
599
+ }
600
+
601
+ await applyStatusToSession(container, resolved, effectiveStatus, {
602
+ order_id: orderId ?? undefined,
603
+ capture_id:
604
+ captureId ?? resolved.sessionData.paypal?.capture_id ?? undefined,
605
+ refund_id: refundId ?? undefined,
606
+ refund_status: refundId ? resource?.status : undefined,
607
+ refund_reason: refundReason,
608
+ refund_reason_code: refundReasonCode,
609
+ ...(refundEntry ? { refunds: refundEntry } : {}),
610
+ webhook_event_type: input.eventType,
611
+ last_webhook_at: new Date().toISOString(),
612
+ })
613
+ sessionUpdated = true
614
+ }
615
+ } else {
616
+ console.warn(
617
+ `[PayPal] webhook: could not resolve cartId for event ${input.eventType}`,
618
+ { orderId, captureId, refundId }
619
+ )
620
+ }
621
+
622
+ // Server-side safety net: the funds settled but the buyer's browser may
623
+ // never call /store/paypal-complete (closed tab, crash, mobile redirect
624
+ // loss). Complete the cart here so a captured payment always produces an
625
+ // order. Runs after the session update so authorizePayment sees the capture.
626
+ if (
627
+ cartId &&
628
+ sessionUpdated &&
629
+ sessionEligibleForCompletion &&
630
+ isCartCompletingEventType(input.eventType) &&
631
+ isWebhookCartCompletionEnabled()
632
+ ) {
633
+ cartCompleted = await completeCartIfPending(
634
+ container,
635
+ cartId,
636
+ input.eventType
637
+ )
638
+ }
639
+
640
+ return { orderId, captureId, refundId, cartId, sessionUpdated, cartCompleted }
641
+ }