@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
@@ -36,11 +36,22 @@ function redactSensitive(value: unknown, depth = 0): unknown {
36
36
  }
37
37
  const out: Record<string, unknown> = {}
38
38
  for (const [k, v] of Object.entries(value as Record<string, unknown>)) {
39
- out[k] = SENSITIVE_KEY_RE.test(k) ? "[REDACTED]" : redactSensitive(v, depth + 1)
39
+ out[k] = SENSITIVE_KEY_RE.test(k)
40
+ ? "[REDACTED]"
41
+ : redactSensitive(v, depth + 1)
40
42
  }
41
43
  return out
42
44
  }
43
45
 
46
+ /**
47
+ * Application-container service for the PayPal module.
48
+ *
49
+ * Owns the merchant's PayPal connection (partner onboarding, seller
50
+ * credentials, cached app access token), the plugin settings singleton,
51
+ * webhook registration/event records, metrics, and audit logging. The payment
52
+ * providers run in the isolated payment-module container and therefore read
53
+ * the same tables through `PayPalCredentialResolver` instead of this service.
54
+ */
44
55
  class PayPalModuleService extends MedusaService({
45
56
  PayPalConnection,
46
57
  PayPalMetric,
@@ -51,8 +62,13 @@ class PayPalModuleService extends MedusaService({
51
62
  private tokenRefreshPromise: Promise<string> | null = null
52
63
  // Raw knex connection for the atomic metric upsert; null when the container
53
64
  // doesn't expose it (recordMetric then falls back to the ORM path).
54
- private pgForMetrics: { raw: (sql: string, bindings: unknown[]) => Promise<unknown> } | null =
55
- null
65
+ private pgForMetrics: {
66
+ raw: (sql: string, bindings: unknown[]) => Promise<unknown>
67
+ } | null = null
68
+ // Only probe PayPal for a stale legacy webhook URL once per process per
69
+ // environment — this runs on admin status reads and must stay cheap.
70
+ private webhookUrlMigrationChecked: Record<string, boolean> = {}
71
+ private webhookHealScheduled: Record<string, boolean> = {}
56
72
 
57
73
  constructor(...args: any[]) {
58
74
  // MedusaService's generated constructor signature varies across framework
@@ -78,7 +94,10 @@ class PayPalModuleService extends MedusaService({
78
94
 
79
95
  private async ensureSettingsDefaults() {
80
96
  const data = await this.getSettingsData()
81
- const onboarding = { ...(data.onboarding_config || {}) } as Record<string, any>
97
+ const onboarding = { ...(data.onboarding_config || {}) } as Record<
98
+ string,
99
+ any
100
+ >
82
101
  const apiDetails = { ...(data.api_details || {}) } as Record<string, any>
83
102
  let changed = false
84
103
 
@@ -134,6 +153,10 @@ class PayPalModuleService extends MedusaService({
134
153
  return { onboarding, apiDetails }
135
154
  }
136
155
 
156
+ /**
157
+ * Onboarding + API-detail settings with plugin defaults filled in (and
158
+ * persisted) for any key that is still unset.
159
+ */
137
160
  async getApiDetails() {
138
161
  const { onboarding, apiDetails } = await this.ensureSettingsDefaults()
139
162
  return {
@@ -143,12 +166,16 @@ class PayPalModuleService extends MedusaService({
143
166
  }
144
167
 
145
168
  private getAlertWebhookUrls() {
146
- return (this.cfg.alertWebhookUrls || []).map((url) => url.trim()).filter(Boolean)
169
+ return (this.cfg.alertWebhookUrls || [])
170
+ .map((url) => url.trim())
171
+ .filter(Boolean)
147
172
  }
148
173
 
149
174
  private async getPartnerMerchantId(env: Environment) {
150
175
  const { onboarding } = await this.ensureSettingsDefaults()
151
- return env === "live" ? onboarding.partner_merchant_id_live : onboarding.partner_merchant_id_sandbox
176
+ return env === "live"
177
+ ? onboarding.partner_merchant_id_live
178
+ : onboarding.partner_merchant_id_sandbox
152
179
  }
153
180
 
154
181
  private async getCurrentRow(): Promise<any | null> {
@@ -172,7 +199,12 @@ class PayPalModuleService extends MedusaService({
172
199
  private getEnvCreds(
173
200
  row: any,
174
201
  env: Environment
175
- ): { clientId?: string; clientSecret?: string; sellerMerchantId?: string; sellerEmail?: string } {
202
+ ): {
203
+ clientId?: string
204
+ clientSecret?: string
205
+ sellerMerchantId?: string
206
+ sellerEmail?: string
207
+ } {
176
208
  const meta = (row?.metadata || {}) as any
177
209
  const creds = meta?.credentials?.[env] || {}
178
210
  return {
@@ -180,7 +212,8 @@ class PayPalModuleService extends MedusaService({
180
212
  // Secrets are encrypted at rest when PAYPAL_ENCRYPTION_KEY is set; decrypt
181
213
  // here so every consumer (auth, status) sees plaintext. Legacy plaintext
182
214
  // values pass through unchanged.
183
- clientSecret: decryptSecret(creds.client_secret || creds.clientSecret) || undefined,
215
+ clientSecret:
216
+ decryptSecret(creds.client_secret || creds.clientSecret) || undefined,
184
217
  sellerMerchantId:
185
218
  creds.seller_merchant_id ||
186
219
  creds.sellerMerchantId ||
@@ -264,7 +297,7 @@ class PayPalModuleService extends MedusaService({
264
297
  }
265
298
 
266
299
  const baseUrl = getPayPalApiBase(env)
267
- const accessToken = accessTokenOverride ?? await this.getAppAccessToken()
300
+ const accessToken = accessTokenOverride ?? (await this.getAppAccessToken())
268
301
 
269
302
  const resp = await paypalFetch(
270
303
  `${baseUrl}/v1/customer/partners/${encodeURIComponent(
@@ -285,7 +318,10 @@ class PayPalModuleService extends MedusaService({
285
318
  try {
286
319
  json = text ? JSON.parse(text) : {}
287
320
  } catch (e: any) {
288
- console.warn("[PayPal] Failed to parse response JSON — using empty object:", e?.message)
321
+ console.warn(
322
+ "[PayPal] Failed to parse response JSON — using empty object:",
323
+ e?.message
324
+ )
289
325
  }
290
326
 
291
327
  if (!resp.ok) {
@@ -302,7 +338,9 @@ class PayPalModuleService extends MedusaService({
302
338
  credentials: { clientId: string; clientSecret: string }
303
339
  ) {
304
340
  const baseUrl = getPayPalApiBase(env)
305
- const basic = Buffer.from(`${credentials.clientId}:${credentials.clientSecret}`).toString("base64")
341
+ const basic = Buffer.from(
342
+ `${credentials.clientId}:${credentials.clientSecret}`
343
+ ).toString("base64")
306
344
 
307
345
  const body = new URLSearchParams()
308
346
  body.set("grant_type", "client_credentials")
@@ -322,16 +360,23 @@ class PayPalModuleService extends MedusaService({
322
360
  try {
323
361
  json = text ? JSON.parse(text) : {}
324
362
  } catch (e: any) {
325
- console.warn("[PayPal] Failed to parse app token response JSON:", e?.message)
363
+ console.warn(
364
+ "[PayPal] Failed to parse app token response JSON:",
365
+ e?.message
366
+ )
326
367
  }
327
368
 
328
369
  if (!res.ok) {
329
- throw new Error(`PayPal client_credentials failed (${res.status}): ${text || JSON.stringify(json)}`)
370
+ throw new Error(
371
+ `PayPal client_credentials failed (${res.status}): ${text || JSON.stringify(json)}`
372
+ )
330
373
  }
331
374
 
332
375
  const accessToken = String(json.access_token || "")
333
376
  if (!accessToken) {
334
- throw new Error("PayPal client_credentials succeeded but access_token is missing.")
377
+ throw new Error(
378
+ "PayPal client_credentials succeeded but access_token is missing."
379
+ )
335
380
  }
336
381
 
337
382
  return { accessToken, tokenPayload: json }
@@ -358,26 +403,39 @@ class PayPalModuleService extends MedusaService({
358
403
  }
359
404
 
360
405
  let sellerEmail = this.extractSellerEmail(tokenPayload || undefined)
361
- let sellerMerchantId = String(
362
- tokenPayload?.merchant_id || tokenPayload?.payer_id || tokenPayload?.account_id || ""
363
- ).trim() || null
406
+ let sellerMerchantId =
407
+ String(
408
+ tokenPayload?.merchant_id ||
409
+ tokenPayload?.payer_id ||
410
+ tokenPayload?.account_id ||
411
+ ""
412
+ ).trim() || null
364
413
 
365
414
  try {
366
- const userInfoResp = await paypalFetch(`${baseUrl}/v1/identity/oauth2/userinfo?schema=paypalv1`, {
367
- method: "GET",
368
- headers: {
369
- Authorization: `Bearer ${accessToken}`,
370
- "Content-Type": "application/json",
371
- Accept: "application/json",
372
- "PayPal-Partner-Attribution-Id": this.bnCode,
373
- },
374
- })
415
+ const userInfoResp = await paypalFetch(
416
+ `${baseUrl}/v1/identity/oauth2/userinfo?schema=paypalv1`,
417
+ {
418
+ method: "GET",
419
+ headers: {
420
+ Authorization: `Bearer ${accessToken}`,
421
+ "Content-Type": "application/json",
422
+ Accept: "application/json",
423
+ "PayPal-Partner-Attribution-Id": this.bnCode,
424
+ },
425
+ }
426
+ )
375
427
  if (userInfoResp.ok) {
376
428
  const userInfo = await userInfoResp.json().catch(() => ({}))
377
429
  sellerEmail = sellerEmail || this.extractSellerEmail(userInfo)
378
430
  sellerMerchantId =
379
431
  sellerMerchantId ||
380
- String(userInfo?.merchant_id || userInfo?.payer_id || userInfo?.user_id || userInfo?.sub || "").trim() ||
432
+ String(
433
+ userInfo?.merchant_id ||
434
+ userInfo?.payer_id ||
435
+ userInfo?.user_id ||
436
+ userInfo?.sub ||
437
+ ""
438
+ ).trim() ||
381
439
  null
382
440
  }
383
441
  } catch (e: any) {
@@ -402,10 +460,16 @@ class PayPalModuleService extends MedusaService({
402
460
  if (credsResp.ok) {
403
461
  const credsJson = await credsResp.json().catch(() => ({}))
404
462
  sellerEmail = sellerEmail || this.extractSellerEmail(credsJson)
405
- sellerMerchantId = sellerMerchantId || String(credsJson?.merchant_id || "").trim() || null
463
+ sellerMerchantId =
464
+ sellerMerchantId ||
465
+ String(credsJson?.merchant_id || "").trim() ||
466
+ null
406
467
  }
407
468
  } catch (e: any) {
408
- console.warn("[PayPal] direct credential profile lookup failed:", e?.message || e)
469
+ console.warn(
470
+ "[PayPal] direct credential profile lookup failed:",
471
+ e?.message || e
472
+ )
409
473
  }
410
474
  }
411
475
 
@@ -439,10 +503,17 @@ class PayPalModuleService extends MedusaService({
439
503
 
440
504
  if (sellerMerchantId && !sellerEmail) {
441
505
  try {
442
- const details = await this.fetchMerchantIntegrationDetails(env, sellerMerchantId, input.accessToken)
506
+ const details = await this.fetchMerchantIntegrationDetails(
507
+ env,
508
+ sellerMerchantId,
509
+ input.accessToken
510
+ )
443
511
  sellerEmail = this.extractSellerEmail(details)
444
512
  } catch (e: any) {
445
- console.warn("[PayPal] merchant integration lookup failed:", e?.message || e)
513
+ console.warn(
514
+ "[PayPal] merchant integration lookup failed:",
515
+ e?.message || e
516
+ )
446
517
  }
447
518
  }
448
519
 
@@ -466,6 +537,12 @@ class PayPalModuleService extends MedusaService({
466
537
  })
467
538
  }
468
539
 
540
+ /**
541
+ * Switch the active environment (`sandbox` | `live`). Credentials are stored
542
+ * per environment, so switching never discards the other environment's
543
+ * credentials — it only changes which set is active and clears the cached
544
+ * app token.
545
+ */
469
546
  async setEnvironment(env: Environment) {
470
547
  const nextEnv: Environment = env === "sandbox" ? "sandbox" : "live"
471
548
  const row = await this.getCurrentRow()
@@ -515,7 +592,16 @@ class PayPalModuleService extends MedusaService({
515
592
  return await this.getCurrentRow()
516
593
  }
517
594
 
518
- async createOnboardingLink(input?: { email?: string; products?: string[]; env?: Environment }) {
595
+ /**
596
+ * Request a PayPal partner-referral onboarding URL from the partner service.
597
+ * Returns the URL to open in PayPal's mini-browser plus the `return_url` the
598
+ * popup lands on afterwards.
599
+ */
600
+ async createOnboardingLink(input?: {
601
+ email?: string
602
+ products?: string[]
603
+ env?: Environment
604
+ }) {
519
605
  const { onboarding } = await this.ensureSettingsDefaults()
520
606
  // Honor an explicit environment from the caller so the generated link can't
521
607
  // depend on a racing "set environment" request having landed first.
@@ -539,7 +625,9 @@ class PayPalModuleService extends MedusaService({
539
625
  const email = (input?.email || "").trim()
540
626
 
541
627
  if (!partner_merchant_id) {
542
- throw new Error("Missing PAYPAL_PARTNER_MERCHANT_ID_* env for current environment")
628
+ throw new Error(
629
+ "Missing PAYPAL_PARTNER_MERCHANT_ID_* env for current environment"
630
+ )
543
631
  }
544
632
 
545
633
  const form = new URLSearchParams()
@@ -579,7 +667,9 @@ class PayPalModuleService extends MedusaService({
579
667
  try {
580
668
  json = JSON.parse(trimmed)
581
669
  } catch {
582
- throw new Error(`Invalid onboarding link response (not JSON / URL): ${trimmed.slice(0, 200)}`)
670
+ throw new Error(
671
+ `Invalid onboarding link response (not JSON / URL): ${trimmed.slice(0, 200)}`
672
+ )
583
673
  }
584
674
 
585
675
  if (json?.body) {
@@ -600,7 +690,11 @@ class PayPalModuleService extends MedusaService({
600
690
  }
601
691
  }
602
692
 
603
- if (json?.name && json?.message && (json?.debug_id || json?.details || json?.links)) {
693
+ if (
694
+ json?.name &&
695
+ json?.message &&
696
+ (json?.debug_id || json?.details || json?.links)
697
+ ) {
604
698
  const debug = json.debug_id ? ` debug_id=${json.debug_id}` : ""
605
699
  const details = Array.isArray(json.details)
606
700
  ? json.details
@@ -615,17 +709,25 @@ class PayPalModuleService extends MedusaService({
615
709
  .join("; ")
616
710
  : ""
617
711
 
618
- throw new Error(`PayPal onboarding error: ${json.name}: ${json.message}.${debug}${details ? ` Details: ${details}` : ""}`)
712
+ throw new Error(
713
+ `PayPal onboarding error: ${json.name}: ${json.message}.${debug}${details ? ` Details: ${details}` : ""}`
714
+ )
619
715
  }
620
716
 
621
- if (json?.onboarding_url && String(json.onboarding_url).startsWith("http")) {
717
+ if (
718
+ json?.onboarding_url &&
719
+ String(json.onboarding_url).startsWith("http")
720
+ ) {
622
721
  return { onboarding_url: String(json.onboarding_url), return_url }
623
722
  }
624
723
 
625
724
  const links = Array.isArray(json?.links) ? json.links : null
626
725
  if (links) {
627
726
  const action = links.find(
628
- (l: any) => l?.rel === "action_url" || l?.rel === "actionUrl" || l?.rel === "action-url"
727
+ (l: any) =>
728
+ l?.rel === "action_url" ||
729
+ l?.rel === "actionUrl" ||
730
+ l?.rel === "action-url"
629
731
  )
630
732
  const href = action?.href ? String(action.href) : null
631
733
  if (href && href.startsWith("http")) {
@@ -638,6 +740,7 @@ class PayPalModuleService extends MedusaService({
638
740
  )
639
741
  }
640
742
 
743
+ /** Mark the connection as onboarding-in-progress (creates the row if needed). */
641
744
  async startOnboarding() {
642
745
  const row = await this.getCurrentRow()
643
746
  const env = await this.getCurrentEnvironment()
@@ -654,6 +757,7 @@ class PayPalModuleService extends MedusaService({
654
757
  })
655
758
  }
656
759
 
760
+ /** Persist the `authCode`/`sharedId` PayPal hands back after onboarding. */
657
761
  async saveOnboardCallback(input: { authCode: string; sharedId: string }) {
658
762
  const row = await this.getCurrentRow()
659
763
  const env = await this.getCurrentEnvironment()
@@ -676,12 +780,19 @@ class PayPalModuleService extends MedusaService({
676
780
  })
677
781
  }
678
782
 
783
+ /**
784
+ * Complete partner onboarding: exchange the single-use `authCode` for a
785
+ * seller access token, fetch the seller's REST credentials, and store them.
786
+ * Idempotent — a repeated exchange of an already-consumed code is a no-op
787
+ * when credentials for that environment are already saved.
788
+ */
679
789
  async exchangeAndSaveSellerCredentials(input: {
680
790
  authCode: string
681
791
  sharedId: string
682
792
  env?: "sandbox" | "live"
683
793
  }) {
684
- const env = (input.env || (await this.getCurrentEnvironment())) as Environment
794
+ const env = (input.env ||
795
+ (await this.getCurrentEnvironment())) as Environment
685
796
 
686
797
  // Onboarding completion can now arrive via several redundant paths
687
798
  // (partner.js's onboardingCallback in the opener, the return_url bridge that
@@ -697,13 +808,18 @@ class PayPalModuleService extends MedusaService({
697
808
  }
698
809
  }
699
810
 
700
- await this.saveOnboardCallback({ authCode: input.authCode, sharedId: input.sharedId })
811
+ await this.saveOnboardCallback({
812
+ authCode: input.authCode,
813
+ sharedId: input.sharedId,
814
+ })
701
815
  const baseUrl = getPayPalApiBase(env)
702
816
 
703
817
  const { onboarding } = await this.ensureSettingsDefaults()
704
818
  const sellerNonce = (onboarding.seller_nonce || "").trim()
705
819
  if (!sellerNonce) {
706
- throw new Error("PayPal seller nonce is not configured. Set PAYPAL_SELLER_NONCE.")
820
+ throw new Error(
821
+ "PayPal seller nonce is not configured. Set PAYPAL_SELLER_NONCE."
822
+ )
707
823
  }
708
824
 
709
825
  const tokenBody = new URLSearchParams()
@@ -749,7 +865,9 @@ class PayPalModuleService extends MedusaService({
749
865
 
750
866
  const sellerAccessToken = String(tokenJson.access_token || "")
751
867
  if (!sellerAccessToken) {
752
- throw new Error("PayPal token exchange succeeded but access_token is missing.")
868
+ throw new Error(
869
+ "PayPal token exchange succeeded but access_token is missing."
870
+ )
753
871
  }
754
872
 
755
873
  const partnerMerchantId = await this.getPartnerMerchantId(env)
@@ -774,7 +892,10 @@ class PayPalModuleService extends MedusaService({
774
892
  try {
775
893
  credJson = credText ? JSON.parse(credText) : {}
776
894
  } catch (e: any) {
777
- console.warn("[PayPal] Failed to parse token response JSON:", e?.message)
895
+ console.warn(
896
+ "[PayPal] Failed to parse credentials response JSON:",
897
+ e?.message
898
+ )
778
899
  }
779
900
 
780
901
  if (!credRes.ok) {
@@ -784,7 +905,9 @@ class PayPalModuleService extends MedusaService({
784
905
  }
785
906
 
786
907
  const clientId = String(credJson.client_id || credJson.clientId || "")
787
- const clientSecret = String(credJson.client_secret || credJson.clientSecret || "")
908
+ const clientSecret = String(
909
+ credJson.client_secret || credJson.clientSecret || ""
910
+ )
788
911
  if (!clientId || !clientSecret) {
789
912
  throw new Error(
790
913
  `PayPal credentials response missing client_id/client_secret. Keys: ${Object.keys(credJson || {}).join(", ")}`
@@ -793,8 +916,13 @@ class PayPalModuleService extends MedusaService({
793
916
 
794
917
  let sellerEmail = this.extractSellerEmail(credJson, tokenJson)
795
918
  let sellerMerchantId =
796
- String(credJson.payer_id || credJson.merchant_id || tokenJson.payer_id || tokenJson.merchant_id || "").trim() ||
797
- null
919
+ String(
920
+ credJson.payer_id ||
921
+ credJson.merchant_id ||
922
+ tokenJson.payer_id ||
923
+ tokenJson.merchant_id ||
924
+ ""
925
+ ).trim() || null
798
926
 
799
927
  if (!sellerEmail) {
800
928
  const merchantCandidates = [
@@ -802,18 +930,27 @@ class PayPalModuleService extends MedusaService({
802
930
  String(credJson.merchant_id || "").trim(),
803
931
  String(tokenJson.payer_id || "").trim(),
804
932
  String(tokenJson.merchant_id || "").trim(),
805
- ].filter(Boolean).filter((v, i, arr) => arr.indexOf(v) === i)
933
+ ]
934
+ .filter(Boolean)
935
+ .filter((v, i, arr) => arr.indexOf(v) === i)
806
936
 
807
937
  for (const merchantId of merchantCandidates) {
808
938
  try {
809
- const merchantDetails = await this.fetchMerchantIntegrationDetails(env, merchantId, sellerAccessToken)
939
+ const merchantDetails = await this.fetchMerchantIntegrationDetails(
940
+ env,
941
+ merchantId,
942
+ sellerAccessToken
943
+ )
810
944
  sellerMerchantId = sellerMerchantId || merchantId
811
945
  sellerEmail = this.extractSellerEmail(merchantDetails)
812
946
  if (sellerEmail) {
813
947
  break
814
948
  }
815
949
  } catch (e: any) {
816
- console.warn(`[PayPal] Merchant integration lookup for ${merchantId} failed:`, e?.message || e)
950
+ console.warn(
951
+ `[PayPal] Merchant integration lookup for ${merchantId} failed:`,
952
+ e?.message || e
953
+ )
817
954
  }
818
955
  }
819
956
  }
@@ -828,17 +965,33 @@ class PayPalModuleService extends MedusaService({
828
965
  if (!sellerEmail && sellerMerchantId) {
829
966
  try {
830
967
  const appAccessToken = await this.getAppAccessToken()
831
- const details = await this.fetchMerchantIntegrationDetails(env, sellerMerchantId, appAccessToken)
968
+ const details = await this.fetchMerchantIntegrationDetails(
969
+ env,
970
+ sellerMerchantId,
971
+ appAccessToken
972
+ )
832
973
  sellerEmail = this.extractSellerEmail(details)
833
974
  if (sellerEmail) {
834
- await this.saveSellerCredentials({ clientId, clientSecret, sellerMerchantId, sellerEmail })
975
+ await this.saveSellerCredentials({
976
+ clientId,
977
+ clientSecret,
978
+ sellerMerchantId,
979
+ sellerEmail,
980
+ })
835
981
  }
836
982
  } catch (e: any) {
837
- console.warn("[PayPal] Post-save merchant_id email lookup failed:", e?.message || e)
983
+ console.warn(
984
+ "[PayPal] Post-save merchant_id email lookup failed:",
985
+ e?.message || e
986
+ )
838
987
  }
839
988
  }
840
989
  }
841
990
 
991
+ /**
992
+ * Store seller REST credentials for an environment (encrypted at rest when
993
+ * `PAYPAL_ENCRYPTION_KEY` is set) and make sure a webhook is registered.
994
+ */
842
995
  async saveSellerCredentials(input: {
843
996
  clientId: string
844
997
  clientSecret: string
@@ -852,9 +1005,15 @@ class PayPalModuleService extends MedusaService({
852
1005
 
853
1006
  const existingCreds = row ? this.getEnvCreds(row, env) : {}
854
1007
  const nextSellerMerchantId =
855
- (input.sellerMerchantId || "").trim() || existingCreds.sellerMerchantId || row?.seller_merchant_id || null
1008
+ (input.sellerMerchantId || "").trim() ||
1009
+ existingCreds.sellerMerchantId ||
1010
+ row?.seller_merchant_id ||
1011
+ null
856
1012
  const nextSellerEmail =
857
- (input.sellerEmail || "").trim() || existingCreds.sellerEmail || row?.seller_email || null
1013
+ (input.sellerEmail || "").trim() ||
1014
+ existingCreds.sellerEmail ||
1015
+ row?.seller_email ||
1016
+ null
858
1017
 
859
1018
  // Encrypt once and store the same ciphertext in both the metadata copy and
860
1019
  // the denormalized column (no-op when encryption is disabled).
@@ -923,12 +1082,17 @@ class PayPalModuleService extends MedusaService({
923
1082
  return updated
924
1083
  }
925
1084
 
1085
+ /**
1086
+ * Save manually-entered credentials, then best-effort look up the seller's
1087
+ * merchant id / email from PayPal so the admin UI can display them.
1088
+ */
926
1089
  async saveAndHydrateSellerCredentials(input: {
927
1090
  clientId: string
928
1091
  clientSecret: string
929
1092
  environment?: Environment
930
1093
  }) {
931
- const env = (input.environment || (await this.getCurrentEnvironment())) as Environment
1094
+ const env = (input.environment ||
1095
+ (await this.getCurrentEnvironment())) as Environment
932
1096
 
933
1097
  await this.saveSellerCredentials({
934
1098
  clientId: input.clientId,
@@ -957,7 +1121,10 @@ class PayPalModuleService extends MedusaService({
957
1121
  await this.syncRowFieldsFromMetadata(refreshedRow, env)
958
1122
  }
959
1123
  } catch (e: any) {
960
- console.warn("[PayPal] saveAndHydrateSellerCredentials lookup failed:", e?.message || e)
1124
+ console.warn(
1125
+ "[PayPal] saveAndHydrateSellerCredentials lookup failed:",
1126
+ e?.message || e
1127
+ )
961
1128
  }
962
1129
 
963
1130
  // This is a write context (credentials were just saved), so it is allowed to
@@ -994,11 +1161,6 @@ class PayPalModuleService extends MedusaService({
994
1161
  }
995
1162
  }
996
1163
 
997
- // Only probe PayPal for a stale legacy webhook URL once per process per
998
- // environment — this runs on admin status reads and must stay cheap.
999
- private webhookUrlMigrationChecked: Record<string, boolean> = {}
1000
- private webhookHealScheduled: Record<string, boolean> = {}
1001
-
1002
1164
  private async migrateLegacyWebhookUrl(env: string, webhookId: string) {
1003
1165
  if (this.webhookUrlMigrationChecked[env]) return
1004
1166
  this.webhookUrlMigrationChecked[env] = true
@@ -1035,9 +1197,7 @@ class PayPalModuleService extends MedusaService({
1035
1197
  "Content-Type": "application/json",
1036
1198
  "PayPal-Partner-Attribution-Id": this.bnCode,
1037
1199
  },
1038
- body: JSON.stringify([
1039
- { op: "replace", path: "/url", value: newUrl },
1040
- ]),
1200
+ body: JSON.stringify([{ op: "replace", path: "/url", value: newUrl }]),
1041
1201
  }
1042
1202
  )
1043
1203
  if (patchResp.ok) {
@@ -1056,19 +1216,24 @@ class PayPalModuleService extends MedusaService({
1056
1216
  private async ensureWebhookRegistration() {
1057
1217
  const env = await this.getCurrentEnvironment()
1058
1218
  const { apiDetails } = await this.ensureSettingsDefaults()
1059
- const webhookIds = { ...(apiDetails.webhook_ids || {}) } as Record<string, string>
1219
+ const webhookIds = { ...(apiDetails.webhook_ids || {}) } as Record<
1220
+ string,
1221
+ string
1222
+ >
1060
1223
 
1061
1224
  if (webhookIds[env]) {
1062
1225
  // Existing installs registered the webhook at /store/paypal/webhook,
1063
1226
  // which Medusa's publishable-key middleware blocks for external callers.
1064
1227
  // Migrate the registered URL to /hooks/paypal/webhook in place
1065
1228
  // (best-effort — a failure keeps the stored id and current behavior).
1066
- await this.migrateLegacyWebhookUrl(env, webhookIds[env]).catch((e: any) => {
1067
- console.warn(
1068
- "[PayPal] webhook URL migration check failed:",
1069
- e?.message || e
1070
- )
1071
- })
1229
+ await this.migrateLegacyWebhookUrl(env, webhookIds[env]).catch(
1230
+ (e: any) => {
1231
+ console.warn(
1232
+ "[PayPal] webhook URL migration check failed:",
1233
+ e?.message || e
1234
+ )
1235
+ }
1236
+ )
1072
1237
  return webhookIds[env]
1073
1238
  }
1074
1239
 
@@ -1094,7 +1259,9 @@ class PayPalModuleService extends MedusaService({
1094
1259
 
1095
1260
  const listJson = await listResp.json().catch(() => ({}))
1096
1261
  if (!listResp.ok) {
1097
- throw new Error(`PayPal webhook list failed (${listResp.status}): ${JSON.stringify(listJson)}`)
1262
+ throw new Error(
1263
+ `PayPal webhook list failed (${listResp.status}): ${JSON.stringify(listJson)}`
1264
+ )
1098
1265
  }
1099
1266
 
1100
1267
  const existing = Array.isArray(listJson?.webhooks)
@@ -1104,30 +1271,33 @@ class PayPalModuleService extends MedusaService({
1104
1271
  let webhookId = existing?.id ? String(existing.id) : ""
1105
1272
 
1106
1273
  if (!webhookId) {
1107
- const createResp = await paypalFetch(`${baseUrl}/v1/notifications/webhooks`, {
1108
- method: "POST",
1109
- headers: {
1110
- Authorization: `Bearer ${accessToken}`,
1111
- "Content-Type": "application/json",
1112
- "PayPal-Partner-Attribution-Id": this.bnCode,
1113
- },
1114
- body: JSON.stringify({
1115
- url: webhookUrl,
1116
- event_types: [
1117
- { name: "CHECKOUT.ORDER.APPROVED" },
1118
- { name: "CHECKOUT.ORDER.CANCELLED" },
1119
- { name: "PAYMENT.CAPTURE.COMPLETED" },
1120
- { name: "PAYMENT.CAPTURE.DENIED" },
1121
- { name: "PAYMENT.CAPTURE.REFUNDED" },
1122
- { name: "PAYMENT.CAPTURE.REVERSED" },
1123
- { name: "PAYMENT.AUTHORIZATION.CREATED" },
1124
- { name: "PAYMENT.AUTHORIZATION.VOIDED" },
1125
- { name: "PAYMENT.AUTHORIZATION.DENIED" },
1126
- { name: "PAYMENT.REFUND.COMPLETED" },
1127
- { name: "PAYMENT.REFUND.DENIED" },
1128
- ],
1129
- }),
1130
- })
1274
+ const createResp = await paypalFetch(
1275
+ `${baseUrl}/v1/notifications/webhooks`,
1276
+ {
1277
+ method: "POST",
1278
+ headers: {
1279
+ Authorization: `Bearer ${accessToken}`,
1280
+ "Content-Type": "application/json",
1281
+ "PayPal-Partner-Attribution-Id": this.bnCode,
1282
+ },
1283
+ body: JSON.stringify({
1284
+ url: webhookUrl,
1285
+ event_types: [
1286
+ { name: "CHECKOUT.ORDER.APPROVED" },
1287
+ { name: "CHECKOUT.ORDER.CANCELLED" },
1288
+ { name: "PAYMENT.CAPTURE.COMPLETED" },
1289
+ { name: "PAYMENT.CAPTURE.DENIED" },
1290
+ { name: "PAYMENT.CAPTURE.REFUNDED" },
1291
+ { name: "PAYMENT.CAPTURE.REVERSED" },
1292
+ { name: "PAYMENT.AUTHORIZATION.CREATED" },
1293
+ { name: "PAYMENT.AUTHORIZATION.VOIDED" },
1294
+ { name: "PAYMENT.AUTHORIZATION.DENIED" },
1295
+ { name: "PAYMENT.REFUND.COMPLETED" },
1296
+ { name: "PAYMENT.REFUND.DENIED" },
1297
+ ],
1298
+ }),
1299
+ }
1300
+ )
1131
1301
 
1132
1302
  const createJson = await createResp.json().catch(() => ({}))
1133
1303
  if (!createResp.ok) {
@@ -1188,13 +1358,18 @@ class PayPalModuleService extends MedusaService({
1188
1358
  const env = envOverride ?? (await this.getCurrentEnvironment())
1189
1359
 
1190
1360
  if (!row) {
1191
- return { environment: env, status: "disconnected" as Status, seller_client_id_present: false }
1361
+ return {
1362
+ environment: env,
1363
+ status: "disconnected" as Status,
1364
+ seller_client_id_present: false,
1365
+ }
1192
1366
  }
1193
1367
 
1194
1368
  const c = this.getEnvCreds(row, env)
1195
1369
  const hasCreds = !!(c.clientId && c.clientSecret)
1196
1370
  let sellerEmail: string | null = c.sellerEmail || row.seller_email || null
1197
- let sellerMerchantId: string | null = c.sellerMerchantId || row.seller_merchant_id || null
1371
+ let sellerMerchantId: string | null =
1372
+ c.sellerMerchantId || row.seller_merchant_id || null
1198
1373
 
1199
1374
  // Self-heal the webhook registration for already-connected merchants:
1200
1375
  // installs that registered the webhook at the old (blocked)
@@ -1224,13 +1399,21 @@ class PayPalModuleService extends MedusaService({
1224
1399
  const refreshedRow = await this.getCurrentRow()
1225
1400
  if (refreshedRow) {
1226
1401
  const refreshedCreds = this.getEnvCreds(refreshedRow, env)
1227
- sellerEmail = refreshedCreds.sellerEmail || refreshedRow.seller_email || sellerEmail
1402
+ sellerEmail =
1403
+ refreshedCreds.sellerEmail ||
1404
+ refreshedRow.seller_email ||
1405
+ sellerEmail
1228
1406
  sellerMerchantId =
1229
- refreshedCreds.sellerMerchantId || refreshedRow.seller_merchant_id || sellerMerchantId
1407
+ refreshedCreds.sellerMerchantId ||
1408
+ refreshedRow.seller_merchant_id ||
1409
+ sellerMerchantId
1230
1410
  }
1231
1411
  }
1232
1412
  } catch (e: any) {
1233
- console.warn("[PayPal] status direct credential lookup failed:", e?.message || e)
1413
+ console.warn(
1414
+ "[PayPal] status direct credential lookup failed:",
1415
+ e?.message || e
1416
+ )
1234
1417
  }
1235
1418
  }
1236
1419
 
@@ -1248,6 +1431,11 @@ class PayPalModuleService extends MedusaService({
1248
1431
  }
1249
1432
  }
1250
1433
 
1434
+ /**
1435
+ * Remove the active environment's credentials. The other environment (if
1436
+ * connected) is untouched, so the row stays "connected" when it still holds
1437
+ * a usable credential set.
1438
+ */
1251
1439
  async disconnect() {
1252
1440
  const row = await this.getCurrentRow()
1253
1441
  if (!row) return
@@ -1258,7 +1446,12 @@ class PayPalModuleService extends MedusaService({
1258
1446
  delete creds[env]
1259
1447
 
1260
1448
  const hasAnyCreds = Object.values(creds).some((v: any) => {
1261
- return v && typeof v === "object" && (v as any).client_id && (v as any).client_secret
1449
+ return (
1450
+ v &&
1451
+ typeof v === "object" &&
1452
+ (v as any).client_id &&
1453
+ (v as any).client_secret
1454
+ )
1262
1455
  })
1263
1456
 
1264
1457
  await this.updatePayPalConnections({
@@ -1285,19 +1478,29 @@ class PayPalModuleService extends MedusaService({
1285
1478
  await this.recordAuditEvent("disconnected", { environment: env })
1286
1479
  }
1287
1480
 
1481
+ /**
1482
+ * Cached client-credentials access token for the active environment.
1483
+ * Refreshes single-flight when the stored token is within two minutes of
1484
+ * expiry so concurrent callers never race to mint duplicate tokens.
1485
+ */
1288
1486
  async getAppAccessToken(): Promise<string> {
1289
1487
  const row = await this.getCurrentRow()
1290
1488
 
1291
1489
  if (!row) {
1292
- throw new Error("PayPal connection row not found. Please complete onboarding.")
1490
+ throw new Error(
1491
+ "PayPal connection row not found. Please complete onboarding."
1492
+ )
1293
1493
  }
1294
1494
 
1295
- const expiresAt = row.app_access_token_expires_at ? new Date(row.app_access_token_expires_at as string) : null
1495
+ const expiresAt = row.app_access_token_expires_at
1496
+ ? new Date(row.app_access_token_expires_at as string)
1497
+ : null
1296
1498
  if (row.app_access_token && expiresAt) {
1297
1499
  const msLeft = expiresAt.getTime() - Date.now()
1298
1500
  // Token is encrypted at rest when a key is configured; decrypt the cached
1299
1501
  // value (legacy plaintext passes through unchanged).
1300
- if (msLeft > 2 * 60 * 1000) return decryptSecret(row.app_access_token as string) as string
1502
+ if (msLeft > 2 * 60 * 1000)
1503
+ return decryptSecret(row.app_access_token as string) as string
1301
1504
  }
1302
1505
 
1303
1506
  if (this.tokenRefreshPromise) {
@@ -1315,7 +1518,9 @@ class PayPalModuleService extends MedusaService({
1315
1518
  const env = await this.getCurrentEnvironment()
1316
1519
  const creds = await this.getActiveCredentials()
1317
1520
  const baseUrl = getPayPalApiBase(env)
1318
- const basic = Buffer.from(`${creds.client_id}:${creds.client_secret}`).toString("base64")
1521
+ const basic = Buffer.from(
1522
+ `${creds.client_id}:${creds.client_secret}`
1523
+ ).toString("base64")
1319
1524
 
1320
1525
  const body = new URLSearchParams()
1321
1526
  body.set("grant_type", "client_credentials")
@@ -1332,11 +1537,16 @@ class PayPalModuleService extends MedusaService({
1332
1537
  })
1333
1538
 
1334
1539
  const json = await res.json().catch(() => ({}))
1335
- if (!res.ok) throw new Error(`PayPal client_credentials failed (${res.status}): ${JSON.stringify(json)}`)
1540
+ if (!res.ok)
1541
+ throw new Error(
1542
+ `PayPal client_credentials failed (${res.status}): ${JSON.stringify(json)}`
1543
+ )
1336
1544
 
1337
1545
  const accessToken = String(json.access_token || "")
1338
1546
  if (!accessToken) {
1339
- throw new Error("PayPal client_credentials succeeded but access_token is missing.")
1547
+ throw new Error(
1548
+ "PayPal client_credentials succeeded but access_token is missing."
1549
+ )
1340
1550
  }
1341
1551
  const expiresIn = Number(json.expires_in || 3600)
1342
1552
  const newExpiresAt = new Date(Date.now() + expiresIn * 1000)
@@ -1350,6 +1560,7 @@ class PayPalModuleService extends MedusaService({
1350
1560
  return accessToken
1351
1561
  }
1352
1562
 
1563
+ /** Mint a browser `client_token` (required by the hosted card fields SDK). */
1353
1564
  async generateClientToken(opts?: { locale?: string }): Promise<string> {
1354
1565
  const env = await this.getCurrentEnvironment()
1355
1566
  const baseUrl = getPayPalApiBase(env)
@@ -1369,17 +1580,22 @@ class PayPalModuleService extends MedusaService({
1369
1580
 
1370
1581
  const json = await res.json().catch(() => ({}))
1371
1582
  if (!res.ok) {
1372
- throw new Error(`PayPal generate-token failed (${res.status}): ${JSON.stringify(json)}`)
1583
+ throw new Error(
1584
+ `PayPal generate-token failed (${res.status}): ${JSON.stringify(json)}`
1585
+ )
1373
1586
  }
1374
1587
 
1375
1588
  const token = String((json as any)?.client_token || "")
1376
1589
  if (!token) {
1377
- throw new Error("PayPal client_token is missing in generate-token response")
1590
+ throw new Error(
1591
+ "PayPal client_token is missing in generate-token response"
1592
+ )
1378
1593
  }
1379
1594
 
1380
1595
  return token
1381
1596
  }
1382
1597
 
1598
+ /** The plugin settings singleton (`{ data }`), never null. */
1383
1599
  async getSettings() {
1384
1600
  // Deterministic singleton read: always the OLDEST row. If a first-boot race
1385
1601
  // ever created a duplicate settings row, every reader (here and the
@@ -1417,6 +1633,7 @@ class PayPalModuleService extends MedusaService({
1417
1633
  return result
1418
1634
  }
1419
1635
 
1636
+ /** Deep-merge `patch` into the settings singleton and return the result. */
1420
1637
  async saveSettings(patch: Record<string, any>) {
1421
1638
  // Same deterministic ordering as getSettings so reads and writes always
1422
1639
  // target the same singleton row.
@@ -1454,12 +1671,15 @@ class PayPalModuleService extends MedusaService({
1454
1671
  return { data: next }
1455
1672
  }
1456
1673
 
1674
+ /** Decrypted REST credentials for the active environment; throws if unset. */
1457
1675
  async getActiveCredentials() {
1458
1676
  const row = await this.getCurrentRow()
1459
1677
  const env = await this.getCurrentEnvironment()
1460
1678
 
1461
1679
  if (!row) {
1462
- throw new Error("PayPal connection row not found. Please complete onboarding.")
1680
+ throw new Error(
1681
+ "PayPal connection row not found. Please complete onboarding."
1682
+ )
1463
1683
  }
1464
1684
 
1465
1685
  const c = this.getEnvCreds(row, env)
@@ -1478,6 +1698,7 @@ class PayPalModuleService extends MedusaService({
1478
1698
  }
1479
1699
  }
1480
1700
 
1701
+ /** Fetch a PayPal order (`GET /v2/checkout/orders/{id}`). */
1481
1702
  async getOrderDetails(orderId: string) {
1482
1703
  if (!orderId) {
1483
1704
  throw new Error("PayPal orderId is required")
@@ -1509,6 +1730,11 @@ class PayPalModuleService extends MedusaService({
1509
1730
  return JSON.parse(text)
1510
1731
  }
1511
1732
 
1733
+ /**
1734
+ * Insert a webhook event row. Returns `{ created: false, event }` instead of
1735
+ * throwing when `event_id` already exists, so the webhook route can treat a
1736
+ * redelivery as a duplicate.
1737
+ */
1512
1738
  async createWebhookEventRecord(input: {
1513
1739
  event_id: string
1514
1740
  event_type: string
@@ -1544,13 +1770,16 @@ class PayPalModuleService extends MedusaService({
1544
1770
  code === "23505" ||
1545
1771
  (message.includes("unique") && message.includes("event_id"))
1546
1772
  ) {
1547
- const existing = await this.listPayPalWebhookEvents({ event_id: input.event_id })
1773
+ const existing = await this.listPayPalWebhookEvents({
1774
+ event_id: input.event_id,
1775
+ })
1548
1776
  return { created: false, event: existing?.[0] ?? null }
1549
1777
  }
1550
1778
  throw error
1551
1779
  }
1552
1780
  }
1553
1781
 
1782
+ /** Update processing state on a webhook event row. */
1554
1783
  async updateWebhookEventRecord(input: {
1555
1784
  id: string
1556
1785
  status?: string
@@ -1580,7 +1809,10 @@ class PayPalModuleService extends MedusaService({
1580
1809
  * sensitive keys redacted. It never throws — audit logging must not break the
1581
1810
  * caller's payment flow.
1582
1811
  */
1583
- async recordAuditEvent(eventType: string, metadata?: Record<string, unknown>) {
1812
+ async recordAuditEvent(
1813
+ eventType: string,
1814
+ metadata?: Record<string, unknown>
1815
+ ) {
1584
1816
  try {
1585
1817
  console.info(
1586
1818
  JSON.stringify({
@@ -1596,6 +1828,10 @@ class PayPalModuleService extends MedusaService({
1596
1828
  return null
1597
1829
  }
1598
1830
 
1831
+ /**
1832
+ * Increment a named counter in `paypal_metric`, merging any metadata.
1833
+ * Best-effort — never throws.
1834
+ */
1599
1835
  async recordMetric(name: string, metadata?: Record<string, unknown>) {
1600
1836
  // Preferred path: single atomic INSERT ... ON CONFLICT (same statement the
1601
1837
  // credential resolver uses), so concurrent routes/webhooks never lose
@@ -1642,15 +1878,26 @@ class PayPalModuleService extends MedusaService({
1642
1878
 
1643
1879
  return await this.updatePayPalMetrics({ id: row.id, name, data: next })
1644
1880
  } catch (e: unknown) {
1645
- console.warn("[PayPal] recordMetric failed:", e instanceof Error ? e.message : e)
1881
+ console.warn(
1882
+ "[PayPal] recordMetric failed:",
1883
+ e instanceof Error ? e.message : e
1884
+ )
1646
1885
  return null
1647
1886
  }
1648
1887
  }
1649
1888
 
1650
- async recordPaymentLog(eventType: string, metadata?: Record<string, unknown>) {
1889
+ /** Audit-log a payment event under the `payment_` prefix. */
1890
+ async recordPaymentLog(
1891
+ eventType: string,
1892
+ metadata?: Record<string, unknown>
1893
+ ) {
1651
1894
  return await this.recordAuditEvent(`payment_${eventType}`, metadata)
1652
1895
  }
1653
1896
 
1897
+ /**
1898
+ * POST an operational alert to every configured `PAYPAL_ALERT_WEBHOOK_URLS`
1899
+ * endpoint. Delivery results are audit-logged; failures never throw.
1900
+ */
1654
1901
  async sendAlert(input: {
1655
1902
  type: string
1656
1903
  message: string