@easypayment/medusa-payment-paypal 0.7.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 (268) hide show
  1. package/.medusa/server/src/admin/index.js +1267 -0
  2. package/.medusa/server/src/admin/index.mjs +1268 -0
  3. package/.medusa/server/src/api/admin/payment-collections/[id]/payment-sessions/route.d.ts +3 -0
  4. package/.medusa/server/src/api/admin/payment-collections/[id]/payment-sessions/route.d.ts.map +1 -0
  5. package/.medusa/server/src/api/admin/payment-collections/[id]/payment-sessions/route.js +18 -0
  6. package/.medusa/server/src/api/admin/payment-collections/[id]/payment-sessions/route.js.map +1 -0
  7. package/.medusa/server/src/api/admin/paypal/disconnect/route.d.ts +3 -0
  8. package/.medusa/server/src/api/admin/paypal/disconnect/route.d.ts.map +1 -0
  9. package/.medusa/server/src/api/admin/paypal/disconnect/route.js +9 -0
  10. package/.medusa/server/src/api/admin/paypal/disconnect/route.js.map +1 -0
  11. package/.medusa/server/src/api/admin/paypal/environment/route.d.ts +4 -0
  12. package/.medusa/server/src/api/admin/paypal/environment/route.d.ts.map +1 -0
  13. package/.medusa/server/src/api/admin/paypal/environment/route.js +23 -0
  14. package/.medusa/server/src/api/admin/paypal/environment/route.js.map +1 -0
  15. package/.medusa/server/src/api/admin/paypal/onboard-complete/route.d.ts +4 -0
  16. package/.medusa/server/src/api/admin/paypal/onboard-complete/route.d.ts.map +1 -0
  17. package/.medusa/server/src/api/admin/paypal/onboard-complete/route.js +31 -0
  18. package/.medusa/server/src/api/admin/paypal/onboard-complete/route.js.map +1 -0
  19. package/.medusa/server/src/api/admin/paypal/onboarding-link/route.d.ts +4 -0
  20. package/.medusa/server/src/api/admin/paypal/onboarding-link/route.d.ts.map +1 -0
  21. package/.medusa/server/src/api/admin/paypal/onboarding-link/route.js +35 -0
  22. package/.medusa/server/src/api/admin/paypal/onboarding-link/route.js.map +1 -0
  23. package/.medusa/server/src/api/admin/paypal/onboarding-status/route.d.ts +3 -0
  24. package/.medusa/server/src/api/admin/paypal/onboarding-status/route.d.ts.map +1 -0
  25. package/.medusa/server/src/api/admin/paypal/onboarding-status/route.js +19 -0
  26. package/.medusa/server/src/api/admin/paypal/onboarding-status/route.js.map +1 -0
  27. package/.medusa/server/src/api/admin/paypal/save-credentials/route.d.ts +3 -0
  28. package/.medusa/server/src/api/admin/paypal/save-credentials/route.d.ts.map +1 -0
  29. package/.medusa/server/src/api/admin/paypal/save-credentials/route.js +17 -0
  30. package/.medusa/server/src/api/admin/paypal/save-credentials/route.js.map +1 -0
  31. package/.medusa/server/src/api/admin/paypal/settings/route.d.ts +4 -0
  32. package/.medusa/server/src/api/admin/paypal/settings/route.d.ts.map +1 -0
  33. package/.medusa/server/src/api/admin/paypal/settings/route.js +14 -0
  34. package/.medusa/server/src/api/admin/paypal/settings/route.js.map +1 -0
  35. package/.medusa/server/src/api/admin/paypal/status/route.d.ts +3 -0
  36. package/.medusa/server/src/api/admin/paypal/status/route.d.ts.map +1 -0
  37. package/.medusa/server/src/api/admin/paypal/status/route.js +11 -0
  38. package/.medusa/server/src/api/admin/paypal/status/route.js.map +1 -0
  39. package/.medusa/server/src/api/middlewares.d.ts +3 -0
  40. package/.medusa/server/src/api/middlewares.d.ts.map +1 -0
  41. package/.medusa/server/src/api/middlewares.js +16 -0
  42. package/.medusa/server/src/api/middlewares.js.map +1 -0
  43. package/.medusa/server/src/api/store/payment-collections/[id]/payment-sessions/route.d.ts +3 -0
  44. package/.medusa/server/src/api/store/payment-collections/[id]/payment-sessions/route.d.ts.map +1 -0
  45. package/.medusa/server/src/api/store/payment-collections/[id]/payment-sessions/route.js +43 -0
  46. package/.medusa/server/src/api/store/payment-collections/[id]/payment-sessions/route.js.map +1 -0
  47. package/.medusa/server/src/api/store/paypal/capture-order/route.d.ts +3 -0
  48. package/.medusa/server/src/api/store/paypal/capture-order/route.d.ts.map +1 -0
  49. package/.medusa/server/src/api/store/paypal/capture-order/route.js +204 -0
  50. package/.medusa/server/src/api/store/paypal/capture-order/route.js.map +1 -0
  51. package/.medusa/server/src/api/store/paypal/config/route.d.ts +3 -0
  52. package/.medusa/server/src/api/store/paypal/config/route.d.ts.map +1 -0
  53. package/.medusa/server/src/api/store/paypal/config/route.js +77 -0
  54. package/.medusa/server/src/api/store/paypal/config/route.js.map +1 -0
  55. package/.medusa/server/src/api/store/paypal/create-order/route.d.ts +3 -0
  56. package/.medusa/server/src/api/store/paypal/create-order/route.d.ts.map +1 -0
  57. package/.medusa/server/src/api/store/paypal/create-order/route.js +361 -0
  58. package/.medusa/server/src/api/store/paypal/create-order/route.js.map +1 -0
  59. package/.medusa/server/src/api/store/paypal/settings/route.d.ts +3 -0
  60. package/.medusa/server/src/api/store/paypal/settings/route.d.ts.map +1 -0
  61. package/.medusa/server/src/api/store/paypal/settings/route.js +20 -0
  62. package/.medusa/server/src/api/store/paypal/settings/route.js.map +1 -0
  63. package/.medusa/server/src/api/store/paypal/webhook/route.d.ts +3 -0
  64. package/.medusa/server/src/api/store/paypal/webhook/route.d.ts.map +1 -0
  65. package/.medusa/server/src/api/store/paypal/webhook/route.js +250 -0
  66. package/.medusa/server/src/api/store/paypal/webhook/route.js.map +1 -0
  67. package/.medusa/server/src/api/store/paypal-complete/route.d.ts +3 -0
  68. package/.medusa/server/src/api/store/paypal-complete/route.d.ts.map +1 -0
  69. package/.medusa/server/src/api/store/paypal-complete/route.js +76 -0
  70. package/.medusa/server/src/api/store/paypal-complete/route.js.map +1 -0
  71. package/.medusa/server/src/index.d.ts +2 -0
  72. package/.medusa/server/src/index.d.ts.map +1 -0
  73. package/.medusa/server/src/index.js +9 -0
  74. package/.medusa/server/src/index.js.map +1 -0
  75. package/.medusa/server/src/jobs/paypal-webhook-retry.d.ts +7 -0
  76. package/.medusa/server/src/jobs/paypal-webhook-retry.d.ts.map +1 -0
  77. package/.medusa/server/src/jobs/paypal-webhook-retry.js +132 -0
  78. package/.medusa/server/src/jobs/paypal-webhook-retry.js.map +1 -0
  79. package/.medusa/server/src/modules/paypal/clients/paypal-seller.client.d.ts +15 -0
  80. package/.medusa/server/src/modules/paypal/clients/paypal-seller.client.d.ts.map +1 -0
  81. package/.medusa/server/src/modules/paypal/clients/paypal-seller.client.js +67 -0
  82. package/.medusa/server/src/modules/paypal/clients/paypal-seller.client.js.map +1 -0
  83. package/.medusa/server/src/modules/paypal/index.d.ts +64 -0
  84. package/.medusa/server/src/modules/paypal/index.d.ts.map +1 -0
  85. package/.medusa/server/src/modules/paypal/index.js +13 -0
  86. package/.medusa/server/src/modules/paypal/index.js.map +1 -0
  87. package/.medusa/server/src/modules/paypal/migrations/20260115120000_create_paypal_connection.d.ts +6 -0
  88. package/.medusa/server/src/modules/paypal/migrations/20260115120000_create_paypal_connection.d.ts.map +1 -0
  89. package/.medusa/server/src/modules/paypal/migrations/20260115120000_create_paypal_connection.js +36 -0
  90. package/.medusa/server/src/modules/paypal/migrations/20260115120000_create_paypal_connection.js.map +1 -0
  91. package/.medusa/server/src/modules/paypal/migrations/20260123090000_create_paypal_settings.d.ts +6 -0
  92. package/.medusa/server/src/modules/paypal/migrations/20260123090000_create_paypal_settings.d.ts.map +1 -0
  93. package/.medusa/server/src/modules/paypal/migrations/20260123090000_create_paypal_settings.js +25 -0
  94. package/.medusa/server/src/modules/paypal/migrations/20260123090000_create_paypal_settings.js.map +1 -0
  95. package/.medusa/server/src/modules/paypal/migrations/20260201090000_create_paypal_webhook_event.d.ts +6 -0
  96. package/.medusa/server/src/modules/paypal/migrations/20260201090000_create_paypal_webhook_event.d.ts.map +1 -0
  97. package/.medusa/server/src/modules/paypal/migrations/20260201090000_create_paypal_webhook_event.js +32 -0
  98. package/.medusa/server/src/modules/paypal/migrations/20260201090000_create_paypal_webhook_event.js.map +1 -0
  99. package/.medusa/server/src/modules/paypal/migrations/20260401090000_create_paypal_metric.d.ts +6 -0
  100. package/.medusa/server/src/modules/paypal/migrations/20260401090000_create_paypal_metric.d.ts.map +1 -0
  101. package/.medusa/server/src/modules/paypal/migrations/20260401090000_create_paypal_metric.js +30 -0
  102. package/.medusa/server/src/modules/paypal/migrations/20260401090000_create_paypal_metric.js.map +1 -0
  103. package/.medusa/server/src/modules/paypal/migrations/20260701090000_add_paypal_webhook_event_processing.d.ts +6 -0
  104. package/.medusa/server/src/modules/paypal/migrations/20260701090000_add_paypal_webhook_event_processing.d.ts.map +1 -0
  105. package/.medusa/server/src/modules/paypal/migrations/20260701090000_add_paypal_webhook_event_processing.js +34 -0
  106. package/.medusa/server/src/modules/paypal/migrations/20260701090000_add_paypal_webhook_event_processing.js.map +1 -0
  107. package/.medusa/server/src/modules/paypal/migrations/20261101090000_remove_paypal_reconciliation_status.d.ts +6 -0
  108. package/.medusa/server/src/modules/paypal/migrations/20261101090000_remove_paypal_reconciliation_status.d.ts.map +1 -0
  109. package/.medusa/server/src/modules/paypal/migrations/20261101090000_remove_paypal_reconciliation_status.js +28 -0
  110. package/.medusa/server/src/modules/paypal/migrations/20261101090000_remove_paypal_reconciliation_status.js.map +1 -0
  111. package/.medusa/server/src/modules/paypal/migrations/20261201090000_remove_paypal_audit_log.d.ts +6 -0
  112. package/.medusa/server/src/modules/paypal/migrations/20261201090000_remove_paypal_audit_log.d.ts.map +1 -0
  113. package/.medusa/server/src/modules/paypal/migrations/20261201090000_remove_paypal_audit_log.js +29 -0
  114. package/.medusa/server/src/modules/paypal/migrations/20261201090000_remove_paypal_audit_log.js.map +1 -0
  115. package/.medusa/server/src/modules/paypal/migrations/20270101090000_set_paypal_environment_default_live.d.ts +6 -0
  116. package/.medusa/server/src/modules/paypal/migrations/20270101090000_set_paypal_environment_default_live.d.ts.map +1 -0
  117. package/.medusa/server/src/modules/paypal/migrations/20270101090000_set_paypal_environment_default_live.js +14 -0
  118. package/.medusa/server/src/modules/paypal/migrations/20270101090000_set_paypal_environment_default_live.js.map +1 -0
  119. package/.medusa/server/src/modules/paypal/migrations/20270102090000_add_paypal_seller_email.d.ts +6 -0
  120. package/.medusa/server/src/modules/paypal/migrations/20270102090000_add_paypal_seller_email.d.ts.map +1 -0
  121. package/.medusa/server/src/modules/paypal/migrations/20270102090000_add_paypal_seller_email.js +14 -0
  122. package/.medusa/server/src/modules/paypal/migrations/20270102090000_add_paypal_seller_email.js.map +1 -0
  123. package/.medusa/server/src/modules/paypal/migrations/20270103090000_add_paypal_seller_merchant_id.d.ts +6 -0
  124. package/.medusa/server/src/modules/paypal/migrations/20270103090000_add_paypal_seller_merchant_id.d.ts.map +1 -0
  125. package/.medusa/server/src/modules/paypal/migrations/20270103090000_add_paypal_seller_merchant_id.js +14 -0
  126. package/.medusa/server/src/modules/paypal/migrations/20270103090000_add_paypal_seller_merchant_id.js.map +1 -0
  127. package/.medusa/server/src/modules/paypal/migrations/20270201000000_add_webhook_dead_letter.d.ts +6 -0
  128. package/.medusa/server/src/modules/paypal/migrations/20270201000000_add_webhook_dead_letter.d.ts.map +1 -0
  129. package/.medusa/server/src/modules/paypal/migrations/20270201000000_add_webhook_dead_letter.js +20 -0
  130. package/.medusa/server/src/modules/paypal/migrations/20270201000000_add_webhook_dead_letter.js.map +1 -0
  131. package/.medusa/server/src/modules/paypal/models/paypal_connection.d.ts +16 -0
  132. package/.medusa/server/src/modules/paypal/models/paypal_connection.d.ts.map +1 -0
  133. package/.medusa/server/src/modules/paypal/models/paypal_connection.js +19 -0
  134. package/.medusa/server/src/modules/paypal/models/paypal_connection.js.map +1 -0
  135. package/.medusa/server/src/modules/paypal/models/paypal_metric.d.ts +7 -0
  136. package/.medusa/server/src/modules/paypal/models/paypal_metric.d.ts.map +1 -0
  137. package/.medusa/server/src/modules/paypal/models/paypal_metric.js +10 -0
  138. package/.medusa/server/src/modules/paypal/models/paypal_metric.js.map +1 -0
  139. package/.medusa/server/src/modules/paypal/models/paypal_settings.d.ts +6 -0
  140. package/.medusa/server/src/modules/paypal/models/paypal_settings.d.ts.map +1 -0
  141. package/.medusa/server/src/modules/paypal/models/paypal_settings.js +9 -0
  142. package/.medusa/server/src/modules/paypal/models/paypal_settings.js.map +1 -0
  143. package/.medusa/server/src/modules/paypal/models/paypal_webhook_event.d.ts +17 -0
  144. package/.medusa/server/src/modules/paypal/models/paypal_webhook_event.d.ts.map +1 -0
  145. package/.medusa/server/src/modules/paypal/models/paypal_webhook_event.js +20 -0
  146. package/.medusa/server/src/modules/paypal/models/paypal_webhook_event.js.map +1 -0
  147. package/.medusa/server/src/modules/paypal/payment-provider/card-service.d.ts +32 -0
  148. package/.medusa/server/src/modules/paypal/payment-provider/card-service.d.ts.map +1 -0
  149. package/.medusa/server/src/modules/paypal/payment-provider/card-service.js +625 -0
  150. package/.medusa/server/src/modules/paypal/payment-provider/card-service.js.map +1 -0
  151. package/.medusa/server/src/modules/paypal/payment-provider/index.d.ts +6 -0
  152. package/.medusa/server/src/modules/paypal/payment-provider/index.d.ts.map +1 -0
  153. package/.medusa/server/src/modules/paypal/payment-provider/index.js +18 -0
  154. package/.medusa/server/src/modules/paypal/payment-provider/index.js.map +1 -0
  155. package/.medusa/server/src/modules/paypal/payment-provider/service.d.ts +39 -0
  156. package/.medusa/server/src/modules/paypal/payment-provider/service.d.ts.map +1 -0
  157. package/.medusa/server/src/modules/paypal/payment-provider/service.js +869 -0
  158. package/.medusa/server/src/modules/paypal/payment-provider/service.js.map +1 -0
  159. package/.medusa/server/src/modules/paypal/payment-provider/webhook-utils.d.ts +3 -0
  160. package/.medusa/server/src/modules/paypal/payment-provider/webhook-utils.d.ts.map +1 -0
  161. package/.medusa/server/src/modules/paypal/payment-provider/webhook-utils.js +74 -0
  162. package/.medusa/server/src/modules/paypal/payment-provider/webhook-utils.js.map +1 -0
  163. package/.medusa/server/src/modules/paypal/service.d.ts +266 -0
  164. package/.medusa/server/src/modules/paypal/service.d.ts.map +1 -0
  165. package/.medusa/server/src/modules/paypal/service.js +1149 -0
  166. package/.medusa/server/src/modules/paypal/service.js.map +1 -0
  167. package/.medusa/server/src/modules/paypal/types/config.d.ts +12 -0
  168. package/.medusa/server/src/modules/paypal/types/config.d.ts.map +1 -0
  169. package/.medusa/server/src/modules/paypal/types/config.js +24 -0
  170. package/.medusa/server/src/modules/paypal/types/config.js.map +1 -0
  171. package/.medusa/server/src/modules/paypal/utils/amounts.d.ts +3 -0
  172. package/.medusa/server/src/modules/paypal/utils/amounts.d.ts.map +1 -0
  173. package/.medusa/server/src/modules/paypal/utils/amounts.js +40 -0
  174. package/.medusa/server/src/modules/paypal/utils/amounts.js.map +1 -0
  175. package/.medusa/server/src/modules/paypal/utils/currencies.d.ts +19 -0
  176. package/.medusa/server/src/modules/paypal/utils/currencies.d.ts.map +1 -0
  177. package/.medusa/server/src/modules/paypal/utils/currencies.js +69 -0
  178. package/.medusa/server/src/modules/paypal/utils/currencies.js.map +1 -0
  179. package/.medusa/server/src/modules/paypal/utils/paypal-auth.d.ts +10 -0
  180. package/.medusa/server/src/modules/paypal/utils/paypal-auth.d.ts.map +1 -0
  181. package/.medusa/server/src/modules/paypal/utils/paypal-auth.js +30 -0
  182. package/.medusa/server/src/modules/paypal/utils/paypal-auth.js.map +1 -0
  183. package/.medusa/server/src/modules/paypal/utils/provider-ids.d.ts +5 -0
  184. package/.medusa/server/src/modules/paypal/utils/provider-ids.d.ts.map +1 -0
  185. package/.medusa/server/src/modules/paypal/utils/provider-ids.js +16 -0
  186. package/.medusa/server/src/modules/paypal/utils/provider-ids.js.map +1 -0
  187. package/.medusa/server/src/modules/paypal/webhook-processor.d.ts +29 -0
  188. package/.medusa/server/src/modules/paypal/webhook-processor.d.ts.map +1 -0
  189. package/.medusa/server/src/modules/paypal/webhook-processor.js +267 -0
  190. package/.medusa/server/src/modules/paypal/webhook-processor.js.map +1 -0
  191. package/.medusa/server/src/providers/paypal/index.d.ts +5 -0
  192. package/.medusa/server/src/providers/paypal/index.d.ts.map +1 -0
  193. package/.medusa/server/src/providers/paypal/index.js +10 -0
  194. package/.medusa/server/src/providers/paypal/index.js.map +1 -0
  195. package/.medusa/server/src/providers/paypal_card/index.d.ts +5 -0
  196. package/.medusa/server/src/providers/paypal_card/index.d.ts.map +1 -0
  197. package/.medusa/server/src/providers/paypal_card/index.js +10 -0
  198. package/.medusa/server/src/providers/paypal_card/index.js.map +1 -0
  199. package/.medusa/server/src/subscribers/paypal-order-invoice.d.ts +6 -0
  200. package/.medusa/server/src/subscribers/paypal-order-invoice.d.ts.map +1 -0
  201. package/.medusa/server/src/subscribers/paypal-order-invoice.js +124 -0
  202. package/.medusa/server/src/subscribers/paypal-order-invoice.js.map +1 -0
  203. package/LICENSE +21 -0
  204. package/README.md +172 -0
  205. package/package.json +80 -0
  206. package/src/admin/index.ts +7 -0
  207. package/src/admin/routes/settings/paypal/_components/Tabs.tsx +48 -0
  208. package/src/admin/routes/settings/paypal/_components/Toast.tsx +51 -0
  209. package/src/admin/routes/settings/paypal/additional-settings/page.tsx +199 -0
  210. package/src/admin/routes/settings/paypal/advanced-card-payments/page.tsx +183 -0
  211. package/src/admin/routes/settings/paypal/apple-pay/page.tsx +5 -0
  212. package/src/admin/routes/settings/paypal/connection/page.tsx +699 -0
  213. package/src/admin/routes/settings/paypal/google-pay/page.tsx +5 -0
  214. package/src/admin/routes/settings/paypal/page.tsx +13 -0
  215. package/src/admin/routes/settings/paypal/pay-later-messaging/page.tsx +5 -0
  216. package/src/admin/routes/settings/paypal/paypal-settings/page.tsx +351 -0
  217. package/src/api/admin/payment-collections/[id]/payment-sessions/route.ts +24 -0
  218. package/src/api/admin/paypal/disconnect/route.ts +8 -0
  219. package/src/api/admin/paypal/environment/route.ts +25 -0
  220. package/src/api/admin/paypal/onboard-complete/route.ts +34 -0
  221. package/src/api/admin/paypal/onboarding-link/route.ts +45 -0
  222. package/src/api/admin/paypal/onboarding-status/route.ts +17 -0
  223. package/src/api/admin/paypal/save-credentials/route.ts +22 -0
  224. package/src/api/admin/paypal/settings/route.ts +14 -0
  225. package/src/api/admin/paypal/status/route.ts +12 -0
  226. package/src/api/middlewares.ts +14 -0
  227. package/src/api/store/payment-collections/[id]/payment-sessions/route.ts +56 -0
  228. package/src/api/store/paypal/capture-order/route.ts +265 -0
  229. package/src/api/store/paypal/config/route.ts +100 -0
  230. package/src/api/store/paypal/create-order/route.ts +449 -0
  231. package/src/api/store/paypal/settings/route.ts +19 -0
  232. package/src/api/store/paypal/webhook/route.ts +325 -0
  233. package/src/api/store/paypal-complete/route.ts +95 -0
  234. package/src/index.ts +1 -0
  235. package/src/jobs/paypal-webhook-retry.ts +149 -0
  236. package/src/modules/paypal/clients/paypal-seller.client.ts +62 -0
  237. package/src/modules/paypal/index.ts +8 -0
  238. package/src/modules/paypal/migrations/20260115120000_create_paypal_connection.ts +33 -0
  239. package/src/modules/paypal/migrations/20260123090000_create_paypal_settings.ts +22 -0
  240. package/src/modules/paypal/migrations/20260201090000_create_paypal_webhook_event.ts +29 -0
  241. package/src/modules/paypal/migrations/20260401090000_create_paypal_metric.ts +27 -0
  242. package/src/modules/paypal/migrations/20260701090000_add_paypal_webhook_event_processing.ts +31 -0
  243. package/src/modules/paypal/migrations/20261101090000_remove_paypal_reconciliation_status.ts +25 -0
  244. package/src/modules/paypal/migrations/20261201090000_remove_paypal_audit_log.ts +26 -0
  245. package/src/modules/paypal/migrations/20270101090000_set_paypal_environment_default_live.ts +11 -0
  246. package/src/modules/paypal/migrations/20270102090000_add_paypal_seller_email.ts +11 -0
  247. package/src/modules/paypal/migrations/20270103090000_add_paypal_seller_merchant_id.ts +11 -0
  248. package/src/modules/paypal/migrations/20270201000000_add_webhook_dead_letter.ts +17 -0
  249. package/src/modules/paypal/models/paypal_connection.ts +23 -0
  250. package/src/modules/paypal/models/paypal_metric.ts +9 -0
  251. package/src/modules/paypal/models/paypal_settings.ts +8 -0
  252. package/src/modules/paypal/models/paypal_webhook_event.ts +19 -0
  253. package/src/modules/paypal/payment-provider/README.md +22 -0
  254. package/src/modules/paypal/payment-provider/card-service.ts +767 -0
  255. package/src/modules/paypal/payment-provider/index.ts +15 -0
  256. package/src/modules/paypal/payment-provider/service.ts +1039 -0
  257. package/src/modules/paypal/payment-provider/webhook-utils.ts +88 -0
  258. package/src/modules/paypal/service.ts +1416 -0
  259. package/src/modules/paypal/types/config.ts +33 -0
  260. package/src/modules/paypal/utils/amounts.ts +41 -0
  261. package/src/modules/paypal/utils/currencies.ts +84 -0
  262. package/src/modules/paypal/utils/paypal-auth.ts +31 -0
  263. package/src/modules/paypal/utils/provider-ids.ts +15 -0
  264. package/src/modules/paypal/webhook-processor.ts +363 -0
  265. package/src/providers/paypal/index.ts +8 -0
  266. package/src/providers/paypal_card/index.ts +8 -0
  267. package/src/subscribers/paypal-order-invoice.ts +171 -0
  268. package/tsconfig.json +31 -0
@@ -0,0 +1,1039 @@
1
+ import { AbstractPaymentProvider } from "@medusajs/framework/utils"
2
+ import { randomUUID } from "crypto"
3
+ import type {
4
+ AuthorizePaymentInput,
5
+ AuthorizePaymentOutput,
6
+ CapturePaymentInput,
7
+ CapturePaymentOutput,
8
+ CancelPaymentInput,
9
+ CancelPaymentOutput,
10
+ CreateAccountHolderInput,
11
+ CreateAccountHolderOutput,
12
+ DeletePaymentInput,
13
+ DeletePaymentOutput,
14
+ GetPaymentStatusInput,
15
+ GetPaymentStatusOutput,
16
+ InitiatePaymentInput,
17
+ InitiatePaymentOutput,
18
+ RefundPaymentInput,
19
+ RefundPaymentOutput,
20
+ RetrievePaymentInput,
21
+ RetrievePaymentOutput,
22
+ UpdatePaymentInput,
23
+ UpdatePaymentOutput,
24
+ ProviderWebhookPayload,
25
+ WebhookActionResult,
26
+ } from "@medusajs/framework/types"
27
+ import { formatAmountForPayPal, getCurrencyExponent } from "../utils/amounts"
28
+ import {
29
+ assertPayPalCurrencySupported,
30
+ normalizeCurrencyCode,
31
+ } from "../utils/currencies"
32
+ import type PayPalModuleService from "../service"
33
+ import { getPayPalWebhookActionAndData } from "./webhook-utils"
34
+
35
+ type Options = {}
36
+
37
+ const BN_CODE = "MBJTechnolabs_SI_SPB"
38
+
39
+ function generateSessionId() {
40
+ try {
41
+ return randomUUID()
42
+ } catch {
43
+ return `pp_${Date.now()}_${Math.random().toString(16).slice(2)}`
44
+ }
45
+ }
46
+
47
+ class PayPalPaymentProvider extends AbstractPaymentProvider<Options> {
48
+ static identifier = "paypal"
49
+
50
+ protected readonly options_: Options
51
+
52
+ constructor(cradle: Record<string, any>, options: Options) {
53
+ super(cradle, options)
54
+ this.options_ = options
55
+ }
56
+
57
+ private resolvePayPalService() {
58
+ const container = this.container as {
59
+ resolve<T>(key: string): T
60
+ }
61
+ try {
62
+ return container.resolve<PayPalModuleService>("paypal_onboarding")
63
+ } catch {
64
+ return null
65
+ }
66
+ }
67
+
68
+ async resolveSettings() {
69
+ const paypal = this.resolvePayPalService()
70
+ if (!paypal) {
71
+ try {
72
+ const { Pool: _SettingsPool } = require("pg")
73
+ const _sPool = new _SettingsPool({ connectionString: process.env.DATABASE_URL })
74
+ const _sResult = await _sPool
75
+ .query("SELECT data FROM paypal_settings ORDER BY created_at DESC LIMIT 1")
76
+ .finally(() => _sPool.end())
77
+ const _sData = _sResult.rows[0]?.data || {}
78
+ return {
79
+ additionalSettings: (_sData.additional_settings || {}) as Record<string, unknown>,
80
+ apiDetails: (_sData.api_details || {}) as Record<string, unknown>,
81
+ }
82
+ } catch {
83
+ return {
84
+ additionalSettings: {} as Record<string, unknown>,
85
+ apiDetails: {} as Record<string, unknown>,
86
+ }
87
+ }
88
+ }
89
+ const settings = await paypal.getSettings().catch(() => ({}))
90
+ const data =
91
+ settings && typeof settings === "object" && "data" in settings
92
+ ? ((settings as any).data ?? {})
93
+ : {}
94
+ return {
95
+ additionalSettings: (data.additional_settings || {}) as Record<string, unknown>,
96
+ apiDetails: (data.api_details || {}) as Record<string, unknown>,
97
+ }
98
+ }
99
+
100
+ private async resolveCurrencyOverride() {
101
+ const { apiDetails } = await this.resolveSettings()
102
+ if (typeof apiDetails.currency_code === "string" && (apiDetails.currency_code as string).trim()) {
103
+ return normalizeCurrencyCode(apiDetails.currency_code as string)
104
+ }
105
+ return normalizeCurrencyCode(process.env.PAYPAL_CURRENCY || "EUR")
106
+ }
107
+
108
+ private async getPayPalAccessToken() {
109
+ const paypal = this.resolvePayPalService()
110
+ if (!paypal) {
111
+ const { Pool: _FbPool } = require("pg")
112
+ const _fbPool = new _FbPool({ connectionString: process.env.DATABASE_URL })
113
+ const _fbResult = await _fbPool
114
+ .query(
115
+ "SELECT metadata, environment, seller_client_id, seller_client_secret FROM paypal_connection WHERE status='connected' ORDER BY created_at DESC LIMIT 1"
116
+ )
117
+ .finally(() => _fbPool.end())
118
+ const _fbRow = _fbResult.rows[0]
119
+ if (!_fbRow) throw new Error("No active PayPal connection found in DB")
120
+ const _fbEnv = _fbRow.environment || "sandbox"
121
+ const _fbCreds =
122
+ (_fbRow.metadata && _fbRow.metadata.credentials && _fbRow.metadata.credentials[_fbEnv]) || {}
123
+ const _fbId = _fbCreds.client_id || _fbRow.seller_client_id
124
+ const _fbSec = _fbCreds.client_secret || _fbRow.seller_client_secret
125
+ const _fbBase =
126
+ _fbEnv === "live" ? "https://api-m.paypal.com" : "https://api-m.sandbox.paypal.com"
127
+ const _fbAuth = Buffer.from(`${_fbId}:${_fbSec}`).toString("base64")
128
+ const _fbResp = await fetch(`${_fbBase}/v1/oauth2/token`, {
129
+ method: "POST",
130
+ headers: {
131
+ Authorization: `Basic ${_fbAuth}`,
132
+ "Content-Type": "application/x-www-form-urlencoded",
133
+ "PayPal-Partner-Attribution-Id": BN_CODE,
134
+ },
135
+ body: "grant_type=client_credentials",
136
+ })
137
+ const _fbText = await _fbResp.text()
138
+ if (!_fbResp.ok) throw new Error(`PayPal token error (${_fbResp.status}): ${_fbText}`)
139
+ const _fbJson = JSON.parse(_fbText)
140
+ return { accessToken: String(_fbJson.access_token), base: _fbBase }
141
+ }
142
+ const creds = await paypal.getActiveCredentials()
143
+ const base =
144
+ creds.environment === "live"
145
+ ? "https://api-m.paypal.com"
146
+ : "https://api-m.sandbox.paypal.com"
147
+ const auth = Buffer.from(`${creds.client_id}:${creds.client_secret}`).toString("base64")
148
+
149
+ const resp = await fetch(`${base}/v1/oauth2/token`, {
150
+ method: "POST",
151
+ headers: {
152
+ Authorization: `Basic ${auth}`,
153
+ "Content-Type": "application/x-www-form-urlencoded",
154
+ "PayPal-Partner-Attribution-Id": BN_CODE,
155
+ },
156
+ body: "grant_type=client_credentials",
157
+ })
158
+
159
+ const text = await resp.text()
160
+ if (!resp.ok) {
161
+ throw new Error(`PayPal token error (${resp.status}): ${text}`)
162
+ }
163
+
164
+ const json = JSON.parse(text)
165
+ return { accessToken: String(json.access_token), base }
166
+ }
167
+
168
+ private async getOrderDetails(orderId: string) {
169
+ const { accessToken, base } = await this.getPayPalAccessToken()
170
+ const resp = await fetch(`${base}/v2/checkout/orders/${orderId}`, {
171
+ method: "GET",
172
+ headers: {
173
+ Authorization: `Bearer ${accessToken}`,
174
+ "Content-Type": "application/json",
175
+ "PayPal-Partner-Attribution-Id": BN_CODE,
176
+ },
177
+ })
178
+
179
+ const text = await resp.text()
180
+ if (!resp.ok) {
181
+ throw new Error(`PayPal get order error (${resp.status}): ${text}`)
182
+ }
183
+
184
+ return JSON.parse(text)
185
+ }
186
+
187
+ private getIdempotencyKey(
188
+ input: { context?: { idempotency_key?: string } },
189
+ suffix: string
190
+ ) {
191
+ const key = input?.context?.idempotency_key?.trim()
192
+ if (key) {
193
+ return `${key}-${suffix}`
194
+ }
195
+ return `pp-${suffix}-${generateSessionId()}`
196
+ }
197
+
198
+ private async normalizePaymentData(input: { data?: Record<string, unknown> }) {
199
+ const data = (input.data || {}) as Record<string, any>
200
+ const amount = Number(data.amount ?? 0)
201
+ const currencyOverride = await this.resolveCurrencyOverride()
202
+ const currencyCode = normalizeCurrencyCode(
203
+ data.currency_code || currencyOverride || "EUR"
204
+ )
205
+ assertPayPalCurrencySupported({
206
+ currencyCode,
207
+ paypalCurrencyOverride: currencyOverride,
208
+ })
209
+ return { data, amount, currencyCode }
210
+ }
211
+
212
+ private mapCaptureStatus(status?: string) {
213
+ const normalized = String(status || "").toUpperCase()
214
+ if (!normalized) return null
215
+ if (normalized === "COMPLETED") return "captured"
216
+ if (normalized === "PENDING") return "pending"
217
+ if (["DENIED", "DECLINED", "FAILED"].includes(normalized)) return "error"
218
+ if (["REFUNDED", "PARTIALLY_REFUNDED", "REVERSED"].includes(normalized)) return "canceled"
219
+ return null
220
+ }
221
+
222
+ private mapAuthorizationStatus(status?: string) {
223
+ const normalized = String(status || "").toUpperCase()
224
+ if (!normalized) return null
225
+ if (["CREATED", "APPROVED", "PENDING"].includes(normalized)) return "authorized"
226
+ if (["VOIDED", "EXPIRED"].includes(normalized)) return "canceled"
227
+ if (["DENIED", "DECLINED", "FAILED"].includes(normalized)) return "error"
228
+ return null
229
+ }
230
+
231
+ private serializeError(error: unknown) {
232
+ if (error instanceof Error) {
233
+ const errorWithCause = error as Error & { cause?: unknown }
234
+ const cause = errorWithCause.cause
235
+ return {
236
+ name: error.name,
237
+ message: error.message,
238
+ stack: error.stack,
239
+ cause:
240
+ cause instanceof Error
241
+ ? { name: cause.name, message: cause.message, stack: cause.stack }
242
+ : cause,
243
+ }
244
+ }
245
+ return { message: String(error) }
246
+ }
247
+
248
+ private mapOrderStatus(status?: string) {
249
+ const normalized = String(status || "").toUpperCase()
250
+ if (!normalized) return "pending"
251
+ if (normalized === "COMPLETED") return "captured"
252
+ if (normalized === "APPROVED") return "authorized"
253
+ if (["VOIDED", "CANCELLED"].includes(normalized)) return "canceled"
254
+ if (["CREATED", "SAVED", "PAYER_ACTION_REQUIRED"].includes(normalized)) return "pending"
255
+ if (["FAILED", "EXPIRED"].includes(normalized)) return "error"
256
+ return "pending"
257
+ }
258
+
259
+ private async recordFailure(eventType: string, metadata?: Record<string, unknown>) {
260
+ const paypal = this.resolvePayPalService()
261
+ if (!paypal) return
262
+ try {
263
+ await paypal.recordPaymentLog(eventType, metadata)
264
+ await paypal.recordAuditEvent(eventType, metadata)
265
+ await paypal.recordMetric(eventType)
266
+ } catch {
267
+ }
268
+ }
269
+
270
+ private async recordSuccess(metricName: string) {
271
+ const paypal = this.resolvePayPalService()
272
+ if (!paypal) return
273
+ try {
274
+ await paypal.recordMetric(metricName)
275
+ } catch {
276
+ }
277
+ }
278
+
279
+ private async recordPaymentEvent(eventType: string, metadata?: Record<string, unknown>) {
280
+ const paypal = this.resolvePayPalService()
281
+ if (!paypal) return
282
+ try {
283
+ await paypal.recordPaymentLog(eventType, metadata)
284
+ } catch {
285
+ }
286
+ }
287
+
288
+ async createAccountHolder(
289
+ input: CreateAccountHolderInput
290
+ ): Promise<CreateAccountHolderOutput> {
291
+ const customerId = input.context?.customer?.id
292
+ const externalId = customerId ? `paypal_${customerId}` : `paypal_${generateSessionId()}`
293
+ return {
294
+ id: externalId,
295
+ data: {
296
+ email: input.context?.customer?.email || null,
297
+ customer_id: customerId || null,
298
+ },
299
+ }
300
+ }
301
+
302
+ async initiatePayment(input: InitiatePaymentInput): Promise<InitiatePaymentOutput> {
303
+ const providerId = (input.data as Record<string, any> | undefined)?.provider_id
304
+ try {
305
+ const currencyOverride = await this.resolveCurrencyOverride()
306
+ const currencyCode = normalizeCurrencyCode(
307
+ input.currency_code || currencyOverride || "EUR"
308
+ )
309
+ assertPayPalCurrencySupported({
310
+ currencyCode,
311
+ paypalCurrencyOverride: currencyOverride,
312
+ })
313
+ return {
314
+ id: generateSessionId(),
315
+ data: {
316
+ ...(input.data || {}),
317
+ ...(providerId ? { provider_id: providerId } : {}),
318
+ amount: input.amount,
319
+ currency_code: currencyCode,
320
+ },
321
+ }
322
+ } catch (error) {
323
+ await this.recordFailure("initiate_failed", {
324
+ error: this.serializeError(error),
325
+ currency_code: input.currency_code,
326
+ amount: input.amount,
327
+ provider_id: providerId,
328
+ data: input.data ?? null,
329
+ })
330
+ throw error
331
+ }
332
+ }
333
+
334
+ async updatePayment(input: UpdatePaymentInput): Promise<UpdatePaymentOutput> {
335
+ const currencyOverride = await this.resolveCurrencyOverride()
336
+ const currencyCode = normalizeCurrencyCode(
337
+ input.currency_code || currencyOverride || "EUR"
338
+ )
339
+ assertPayPalCurrencySupported({
340
+ currencyCode,
341
+ paypalCurrencyOverride: currencyOverride,
342
+ })
343
+ const providerId = (input.data as Record<string, any> | undefined)?.provider_id
344
+ return {
345
+ data: {
346
+ ...(input.data || {}),
347
+ ...(providerId ? { provider_id: providerId } : {}),
348
+ amount: input.amount,
349
+ currency_code: currencyCode,
350
+ },
351
+ }
352
+ }
353
+
354
+ async authorizePayment(
355
+ input: AuthorizePaymentInput
356
+ ): Promise<AuthorizePaymentOutput> {
357
+ const { data, amount, currencyCode } = await this.normalizePaymentData(input)
358
+ const existingPayPal = (data.paypal || {}) as Record<string, any>
359
+
360
+ const { additionalSettings } = await this.resolveSettings()
361
+ const paymentActionRaw =
362
+ typeof additionalSettings.paymentAction === "string"
363
+ ? additionalSettings.paymentAction
364
+ : "capture"
365
+ const returnStatus = paymentActionRaw === "authorize" ? "authorized" : "captured"
366
+ const timestampKey = paymentActionRaw === "authorize" ? "authorized_at" : "captured_at"
367
+
368
+ if (
369
+ existingPayPal.capture_id ||
370
+ existingPayPal.authorization_id ||
371
+ (data as any).authorized_at ||
372
+ (data as any).captured_at
373
+ ) {
374
+ console.info("[PayPal] authorizePayment: session already processed, returning", returnStatus)
375
+ return {
376
+ status: returnStatus,
377
+ data: {
378
+ ...(input.data || {}),
379
+ [timestampKey]: (data as any)[timestampKey] || new Date().toISOString(),
380
+ },
381
+ }
382
+ }
383
+
384
+ const orderId = String(existingPayPal.order_id || data.order_id || "")
385
+ if (orderId) {
386
+ try {
387
+ console.info("[PayPal] authorizePayment: fetching live order status for", orderId)
388
+ const order = await this.getOrderDetails(orderId)
389
+ const capture = order?.purchase_units?.[0]?.payments?.captures?.[0]
390
+ const authorization = order?.purchase_units?.[0]?.payments?.authorizations?.[0]
391
+
392
+ if (capture?.id || authorization?.id) {
393
+ console.info("[PayPal] authorizePayment: order already processed by PayPal, returning", returnStatus)
394
+ return {
395
+ status: returnStatus,
396
+ data: {
397
+ ...(input.data || {}),
398
+ paypal: {
399
+ ...existingPayPal,
400
+ order_id: orderId,
401
+ order,
402
+ authorization_id: authorization?.id || existingPayPal.authorization_id,
403
+ capture_id: capture?.id || existingPayPal.capture_id,
404
+ },
405
+ [timestampKey]: new Date().toISOString(),
406
+ },
407
+ }
408
+ }
409
+
410
+ if (["APPROVED", "CREATED", "SAVED"].includes(String(order?.status || "").toUpperCase())) {
411
+ console.info("[PayPal] authorizePayment: order approved, marking authorized")
412
+ return {
413
+ status: "authorized",
414
+ data: {
415
+ ...(input.data || {}),
416
+ paypal: {
417
+ ...existingPayPal,
418
+ order_id: orderId,
419
+ order,
420
+ },
421
+ authorized_at: new Date().toISOString(),
422
+ },
423
+ }
424
+ }
425
+ } catch (e: any) {
426
+ console.warn("[PayPal] authorizePayment: order lookup failed:", e?.message)
427
+ }
428
+ }
429
+
430
+ const requestId = this.getIdempotencyKey(input, "authorize")
431
+ let debugId: string | null = null
432
+ const orderIntent = paymentActionRaw === "authorize" ? "AUTHORIZE" : "CAPTURE"
433
+
434
+ try {
435
+ const { accessToken, base } = await this.getPayPalAccessToken()
436
+ const value = formatAmountForPayPal(amount, currencyCode || "EUR")
437
+
438
+ const orderPayload = {
439
+ intent: orderIntent,
440
+ purchase_units: [
441
+ {
442
+ reference_id: data.cart_id || data.payment_collection_id || undefined,
443
+ custom_id:
444
+ data.session_id || data.cart_id || data.payment_collection_id || undefined,
445
+ amount: {
446
+ currency_code: currencyCode || "EUR",
447
+ value,
448
+ },
449
+ },
450
+ ],
451
+ custom_id:
452
+ data.session_id || data.cart_id || data.payment_collection_id || undefined,
453
+ }
454
+
455
+ const ppResp = await fetch(`${base}/v2/checkout/orders`, {
456
+ method: "POST",
457
+ headers: {
458
+ Authorization: `Bearer ${accessToken}`,
459
+ "Content-Type": "application/json",
460
+ "PayPal-Request-Id": requestId,
461
+ "PayPal-Partner-Attribution-Id": BN_CODE,
462
+ },
463
+ body: JSON.stringify(orderPayload),
464
+ })
465
+
466
+ const ppText = await ppResp.text()
467
+ debugId = ppResp.headers.get("paypal-debug-id")
468
+ if (!ppResp.ok) {
469
+ throw new Error(
470
+ `PayPal create order error (${ppResp.status}): ${ppText}${
471
+ debugId ? ` debug_id=${debugId}` : ""
472
+ }`
473
+ )
474
+ }
475
+
476
+ const order = JSON.parse(ppText) as Record<string, any>
477
+ const newOrderId = String(order.id || "")
478
+
479
+ if (!order || !newOrderId) {
480
+ throw new Error("Unable to resolve PayPal order details for authorization.")
481
+ }
482
+
483
+ const existingAuthorization =
484
+ order?.purchase_units?.[0]?.payments?.authorizations?.[0] || null
485
+
486
+ let authorization: any = null
487
+ if (existingAuthorization) {
488
+ authorization = order
489
+ } else {
490
+ const authorizeResp = await fetch(
491
+ `${base}/v2/checkout/orders/${newOrderId}/authorize`,
492
+ {
493
+ method: "POST",
494
+ headers: {
495
+ Authorization: `Bearer ${accessToken}`,
496
+ "Content-Type": "application/json",
497
+ "PayPal-Request-Id": `${requestId}-auth`,
498
+ "PayPal-Partner-Attribution-Id": BN_CODE,
499
+ },
500
+ }
501
+ )
502
+
503
+ const authorizeText = await authorizeResp.text()
504
+ const authorizeDebugId = authorizeResp.headers.get("paypal-debug-id")
505
+ if (!authorizeResp.ok) {
506
+ throw new Error(
507
+ `PayPal authorize order error (${authorizeResp.status}): ${authorizeText}${
508
+ authorizeDebugId ? ` debug_id=${authorizeDebugId}` : ""
509
+ }`
510
+ )
511
+ }
512
+
513
+ authorization = JSON.parse(authorizeText)
514
+ }
515
+
516
+ const authorizationId =
517
+ authorization?.purchase_units?.[0]?.payments?.authorizations?.[0]?.id ||
518
+ existingAuthorization?.id
519
+
520
+ await this.recordSuccess("authorize_success")
521
+ await this.recordPaymentEvent("authorize", {
522
+ order_id: newOrderId,
523
+ authorization_id: authorizationId,
524
+ amount,
525
+ currency_code: currencyCode,
526
+ request_id: requestId,
527
+ })
528
+
529
+ return {
530
+ status: "authorized",
531
+ data: {
532
+ ...(input.data || {}),
533
+ paypal: {
534
+ ...((input.data || {}).paypal as Record<string, unknown>),
535
+ order_id: newOrderId,
536
+ order: order || authorization,
537
+ authorization_id: authorizationId,
538
+ authorizations:
539
+ authorization?.purchase_units?.[0]?.payments?.authorizations || [],
540
+ },
541
+ authorized_at: new Date().toISOString(),
542
+ },
543
+ }
544
+ } catch (error: any) {
545
+ await this.recordFailure("authorize_failed", {
546
+ request_id: requestId,
547
+ cart_id: data.cart_id,
548
+ payment_collection_id: data.payment_collection_id,
549
+ debug_id: debugId,
550
+ message: error?.message,
551
+ })
552
+ throw error
553
+ }
554
+ }
555
+
556
+ async retrievePayment(input: RetrievePaymentInput): Promise<RetrievePaymentOutput> {
557
+ const data = (input.data || {}) as Record<string, any>
558
+ const paypalData = (data.paypal || {}) as Record<string, any>
559
+ const orderId = String(paypalData.order_id || data.order_id || "")
560
+ if (!orderId) {
561
+ return { data: { ...(input.data || {}) } }
562
+ }
563
+
564
+ const order = await this.getOrderDetails(orderId)
565
+ const capture = order?.purchase_units?.[0]?.payments?.captures?.[0]
566
+ const authorization = order?.purchase_units?.[0]?.payments?.authorizations?.[0]
567
+
568
+ return {
569
+ data: {
570
+ ...(input.data || {}),
571
+ paypal: {
572
+ ...((input.data || {}).paypal as Record<string, unknown>),
573
+ order,
574
+ authorization_id: authorization?.id || paypalData.authorization_id,
575
+ capture_id: capture?.id || paypalData.capture_id,
576
+ },
577
+ },
578
+ }
579
+ }
580
+
581
+ async getPaymentStatus(input: GetPaymentStatusInput): Promise<GetPaymentStatusOutput> {
582
+ const data = (input.data || {}) as Record<string, any>
583
+ const paypalData = (data.paypal || {}) as Record<string, any>
584
+ const orderId = String(paypalData.order_id || data.order_id || "")
585
+ if (!orderId) {
586
+ return { status: "pending", data: { ...(input.data || {}) } }
587
+ }
588
+
589
+ try {
590
+ const order = await this.getOrderDetails(orderId)
591
+ const capture = order?.purchase_units?.[0]?.payments?.captures?.[0]
592
+ const authorization = order?.purchase_units?.[0]?.payments?.authorizations?.[0]
593
+ const mappedStatus =
594
+ this.mapCaptureStatus(capture?.status) ||
595
+ this.mapAuthorizationStatus(authorization?.status) ||
596
+ this.mapOrderStatus(order?.status) ||
597
+ "pending"
598
+
599
+ await this.recordSuccess("status_success")
600
+ return {
601
+ status: mappedStatus,
602
+ data: {
603
+ ...(input.data || {}),
604
+ paypal: {
605
+ ...((input.data || {}).paypal as Record<string, unknown>),
606
+ order,
607
+ authorization_id: authorization?.id || paypalData.authorization_id,
608
+ capture_id: capture?.id || paypalData.capture_id,
609
+ },
610
+ },
611
+ }
612
+ } catch (error: any) {
613
+ await this.recordFailure("status_failed", {
614
+ order_id: orderId,
615
+ message: error?.message,
616
+ })
617
+ throw error
618
+ }
619
+ }
620
+
621
+ async capturePayment(input: CapturePaymentInput): Promise<CapturePaymentOutput> {
622
+ const data = (input.data || {}) as Record<string, any>
623
+ const paypalData = (data.paypal || {}) as Record<string, any>
624
+ const orderId = String(paypalData.order_id || data.order_id || "")
625
+ let authorizationId = String(
626
+ paypalData.authorization_id || data.authorization_id || ""
627
+ )
628
+ if (!orderId) {
629
+ throw new Error("PayPal order_id is required to capture payment")
630
+ }
631
+
632
+ if (paypalData.capture_id || paypalData.capture) {
633
+ return {
634
+ data: {
635
+ ...(input.data || {}),
636
+ paypal: {
637
+ ...((input.data || {}).paypal as Record<string, unknown>),
638
+ capture_id: paypalData.capture_id,
639
+ capture: paypalData.capture,
640
+ },
641
+ captured_at: new Date().toISOString(),
642
+ },
643
+ }
644
+ }
645
+
646
+ const requestId = this.getIdempotencyKey(input, `capture-${orderId}`)
647
+ const { amount, currencyCode } = await this.normalizePaymentData(input)
648
+ let debugId: string | null = null
649
+
650
+ try {
651
+ const { accessToken, base } = await this.getPayPalAccessToken()
652
+ const order = await this.getOrderDetails(orderId).catch(() => null)
653
+ const existingCapture = order?.purchase_units?.[0]?.payments?.captures?.[0]
654
+ if (existingCapture?.id) {
655
+ return {
656
+ data: {
657
+ ...(input.data || {}),
658
+ paypal: {
659
+ ...((input.data || {}).paypal as Record<string, unknown>),
660
+ capture_id: existingCapture.id,
661
+ capture: existingCapture,
662
+ },
663
+ captured_at: new Date().toISOString(),
664
+ },
665
+ }
666
+ }
667
+
668
+ const resolvedIntent = String(
669
+ order?.intent || paypalData.order?.intent || data.intent || ""
670
+ ).toUpperCase()
671
+
672
+ if (!authorizationId && resolvedIntent === "AUTHORIZE") {
673
+ const authorizeResp = await fetch(
674
+ `${base}/v2/checkout/orders/${orderId}/authorize`,
675
+ {
676
+ method: "POST",
677
+ headers: {
678
+ Authorization: `Bearer ${accessToken}`,
679
+ "Content-Type": "application/json",
680
+ "PayPal-Request-Id": `${requestId}-auth`,
681
+ "PayPal-Partner-Attribution-Id": BN_CODE,
682
+ },
683
+ }
684
+ )
685
+ const authorizeText = await authorizeResp.text()
686
+ debugId = authorizeResp.headers.get("paypal-debug-id")
687
+ if (!authorizeResp.ok) {
688
+ throw new Error(
689
+ `PayPal authorize order error (${authorizeResp.status}): ${authorizeText}${
690
+ debugId ? ` debug_id=${debugId}` : ""
691
+ }`
692
+ )
693
+ }
694
+ const authorization = JSON.parse(authorizeText)
695
+ authorizationId =
696
+ authorization?.purchase_units?.[0]?.payments?.authorizations?.[0]?.id
697
+ }
698
+
699
+ const isFinalCapture =
700
+ paypalData.is_final_capture ??
701
+ data.is_final_capture ??
702
+ data.final_capture ??
703
+ undefined
704
+ const captureExponent = getCurrencyExponent(currencyCode || "EUR")
705
+ const capturePayload =
706
+ amount > 0
707
+ ? {
708
+ amount: {
709
+ currency_code: currencyCode || "EUR",
710
+ value: amount.toFixed(captureExponent),
711
+ },
712
+ ...(typeof isFinalCapture === "boolean"
713
+ ? { is_final_capture: isFinalCapture }
714
+ : {}),
715
+ }
716
+ : {
717
+ ...(typeof isFinalCapture === "boolean"
718
+ ? { is_final_capture: isFinalCapture }
719
+ : {}),
720
+ }
721
+
722
+ const captureUrl = authorizationId
723
+ ? `${base}/v2/payments/authorizations/${authorizationId}/capture`
724
+ : `${base}/v2/checkout/orders/${orderId}/capture`
725
+
726
+ const ppResp = await fetch(captureUrl, {
727
+ method: "POST",
728
+ headers: {
729
+ Authorization: `Bearer ${accessToken}`,
730
+ "Content-Type": "application/json",
731
+ "PayPal-Request-Id": requestId,
732
+ "PayPal-Partner-Attribution-Id": BN_CODE,
733
+ },
734
+ body: JSON.stringify(capturePayload),
735
+ })
736
+
737
+ const ppText = await ppResp.text()
738
+ debugId = ppResp.headers.get("paypal-debug-id")
739
+ if (!ppResp.ok) {
740
+ throw new Error(
741
+ `PayPal capture error (${ppResp.status}): ${ppText}${
742
+ debugId ? ` debug_id=${debugId}` : ""
743
+ }`
744
+ )
745
+ }
746
+
747
+ const capture = JSON.parse(ppText)
748
+ const captureId =
749
+ capture?.id || capture?.purchase_units?.[0]?.payments?.captures?.[0]?.id
750
+ const existingCaptures = Array.isArray(paypalData.captures) ? paypalData.captures : []
751
+ const captureEntry = {
752
+ id: captureId,
753
+ status: capture?.status,
754
+ amount: capture?.amount,
755
+ raw: capture,
756
+ }
757
+
758
+ await this.recordSuccess("capture_success")
759
+ await this.recordPaymentEvent("capture", {
760
+ order_id: orderId,
761
+ capture_id: captureId,
762
+ authorization_id: authorizationId || undefined,
763
+ amount,
764
+ currency_code: currencyCode,
765
+ request_id: requestId,
766
+ })
767
+
768
+ return {
769
+ data: {
770
+ ...(input.data || {}),
771
+ paypal: {
772
+ ...((input.data || {}).paypal as Record<string, unknown>),
773
+ order_id: orderId,
774
+ capture_id: captureId,
775
+ capture,
776
+ authorization_id: authorizationId || paypalData.authorization_id,
777
+ captures: [...existingCaptures, captureEntry],
778
+ },
779
+ captured_at: new Date().toISOString(),
780
+ },
781
+ }
782
+ } catch (error: any) {
783
+ await this.recordFailure("capture_failed", {
784
+ order_id: orderId,
785
+ request_id: requestId,
786
+ debug_id: debugId,
787
+ message: error?.message,
788
+ })
789
+ throw error
790
+ }
791
+ }
792
+
793
+ async refundPayment(input: RefundPaymentInput): Promise<RefundPaymentOutput> {
794
+ const data = (input.data || {}) as Record<string, any>
795
+ const paypalData = (data.paypal || {}) as Record<string, any>
796
+ const captureId = String(paypalData.capture_id || data.capture_id || "")
797
+ const refundReason = String(
798
+ paypalData.refund_reason || data.refund_reason || data.reason || ""
799
+ ).trim()
800
+ const refundReasonCode = String(
801
+ paypalData.refund_reason_code || data.refund_reason_code || data.reason_code || ""
802
+ ).trim()
803
+ if (!captureId) {
804
+ return {
805
+ data: {
806
+ ...(input.data || {}),
807
+ refunded_at: new Date().toISOString(),
808
+ },
809
+ }
810
+ }
811
+
812
+ const requestId = this.getIdempotencyKey(input, `refund-${captureId}`)
813
+
814
+ const currencyOverride = await this.resolveCurrencyOverride()
815
+ const currencyCode = normalizeCurrencyCode(
816
+ data.currency_code || currencyOverride || "EUR"
817
+ )
818
+
819
+ const exponent = currencyCode.toUpperCase() === "JPY" ? 0
820
+ : ["BHD", "JOD", "KWD", "OMR", "TND"].includes(currencyCode.toUpperCase()) ? 3
821
+ : 2
822
+ const refundAmount = Number(input.amount ?? 0)
823
+ const refundValue = refundAmount > 0 ? refundAmount.toFixed(exponent) : null
824
+
825
+ let debugId: string | null = null
826
+
827
+ try {
828
+ const { accessToken, base } = await this.getPayPalAccessToken()
829
+ const refundPayload: Record<string, any> =
830
+ refundValue
831
+ ? {
832
+ amount: {
833
+ currency_code: currencyCode || "EUR",
834
+ value: refundValue,
835
+ },
836
+ }
837
+ : {}
838
+
839
+ if (refundReason) {
840
+ refundPayload.note_to_payer = refundReason
841
+ }
842
+
843
+ const ppResp = await fetch(`${base}/v2/payments/captures/${captureId}/refund`, {
844
+ method: "POST",
845
+ headers: {
846
+ Authorization: `Bearer ${accessToken}`,
847
+ "Content-Type": "application/json",
848
+ "PayPal-Request-Id": requestId,
849
+ "PayPal-Partner-Attribution-Id": BN_CODE,
850
+ },
851
+ body: JSON.stringify(refundPayload),
852
+ })
853
+
854
+ const ppText = await ppResp.text()
855
+ debugId = ppResp.headers.get("paypal-debug-id")
856
+ if (!ppResp.ok) {
857
+ throw new Error(
858
+ `PayPal refund error (${ppResp.status}): ${ppText}${
859
+ debugId ? ` debug_id=${debugId}` : ""
860
+ }`
861
+ )
862
+ }
863
+
864
+ const refund = JSON.parse(ppText)
865
+ const existingRefunds = Array.isArray(paypalData.refunds) ? paypalData.refunds : []
866
+ const refundEntry = {
867
+ id: refund?.id,
868
+ status: refund?.status,
869
+ amount: refund?.amount,
870
+ reason: refundReason || refund?.note_to_payer,
871
+ reason_code: refundReasonCode || refund?.reason_code,
872
+ raw: refund,
873
+ }
874
+
875
+ await this.recordSuccess("refund_success")
876
+ await this.recordPaymentEvent("refund", {
877
+ capture_id: captureId,
878
+ refund_id: refund?.id,
879
+ amount: refundAmount,
880
+ currency_code: currencyCode,
881
+ request_id: requestId,
882
+ reason: refundReason,
883
+ reason_code: refundReasonCode,
884
+ })
885
+
886
+ return {
887
+ data: {
888
+ ...(input.data || {}),
889
+ paypal: {
890
+ ...((input.data || {}).paypal as Record<string, unknown>),
891
+ refund_id: refund?.id,
892
+ refund_status: refund?.status,
893
+ refund_reason: refundReason || refund?.note_to_payer,
894
+ refund_reason_code: refundReasonCode || refund?.reason_code,
895
+ refunds: [...existingRefunds, refundEntry],
896
+ refund,
897
+ },
898
+ refunded_at: new Date().toISOString(),
899
+ },
900
+ }
901
+ } catch (error: any) {
902
+ await this.recordFailure("refund_failed", {
903
+ capture_id: captureId,
904
+ request_id: requestId,
905
+ debug_id: debugId,
906
+ message: error?.message,
907
+ })
908
+ throw error
909
+ }
910
+ }
911
+
912
+ async cancelPayment(input: CancelPaymentInput): Promise<CancelPaymentOutput> {
913
+ const data = (input.data || {}) as Record<string, any>
914
+ const paypalData = (data.paypal || {}) as Record<string, any>
915
+ const orderId = String(paypalData.order_id || data.order_id || "")
916
+ const captureId = String(paypalData.capture_id || data.capture_id || "")
917
+ const storedAuthorizationId = String(
918
+ paypalData.authorization_id || data.authorization_id || ""
919
+ )
920
+ let debugId: string | null = null
921
+
922
+ try {
923
+ const order = orderId ? await this.getOrderDetails(orderId) : null
924
+ const intent = String(order?.intent || "").toUpperCase()
925
+ const authorizationId =
926
+ order?.purchase_units?.[0]?.payments?.authorizations?.[0]?.id ||
927
+ storedAuthorizationId
928
+
929
+ if (intent === "AUTHORIZE" && authorizationId) {
930
+ const { accessToken, base } = await this.getPayPalAccessToken()
931
+ const requestId = this.getIdempotencyKey(input, `void-${authorizationId}`)
932
+
933
+ const resp = await fetch(
934
+ `${base}/v2/payments/authorizations/${authorizationId}/void`,
935
+ {
936
+ method: "POST",
937
+ headers: {
938
+ Authorization: `Bearer ${accessToken}`,
939
+ "Content-Type": "application/json",
940
+ "PayPal-Request-Id": requestId,
941
+ "PayPal-Partner-Attribution-Id": BN_CODE,
942
+ },
943
+ }
944
+ )
945
+
946
+ if (!resp.ok) {
947
+ const text = await resp.text()
948
+ debugId = resp.headers.get("paypal-debug-id")
949
+ throw new Error(
950
+ `PayPal void error (${resp.status}): ${text}${
951
+ debugId ? ` debug_id=${debugId}` : ""
952
+ }`
953
+ )
954
+ }
955
+
956
+ await this.recordSuccess("void_success")
957
+ await this.recordPaymentEvent("void", {
958
+ order_id: orderId,
959
+ authorization_id: authorizationId,
960
+ })
961
+ } else if (captureId) {
962
+ const { accessToken, base } = await this.getPayPalAccessToken()
963
+ const requestId = this.getIdempotencyKey(input, `refund-${captureId}`)
964
+
965
+ const resp = await fetch(`${base}/v2/payments/captures/${captureId}/refund`, {
966
+ method: "POST",
967
+ headers: {
968
+ Authorization: `Bearer ${accessToken}`,
969
+ "Content-Type": "application/json",
970
+ "PayPal-Request-Id": requestId,
971
+ "PayPal-Partner-Attribution-Id": BN_CODE,
972
+ },
973
+ body: JSON.stringify({}),
974
+ })
975
+
976
+ if (!resp.ok) {
977
+ const text = await resp.text()
978
+ debugId = resp.headers.get("paypal-debug-id")
979
+ throw new Error(
980
+ `PayPal refund error (${resp.status}): ${text}${
981
+ debugId ? ` debug_id=${debugId}` : ""
982
+ }`
983
+ )
984
+ }
985
+
986
+ const refund = await resp.json().catch(() => ({}))
987
+ const existingRefunds = Array.isArray(paypalData.refunds) ? paypalData.refunds : []
988
+ const refundEntry = {
989
+ id: refund?.id,
990
+ status: refund?.status,
991
+ amount: refund?.amount,
992
+ raw: refund,
993
+ }
994
+ paypalData.refund_id = refund?.id
995
+ paypalData.refund_status = refund?.status
996
+ paypalData.refunds = [...existingRefunds, refundEntry]
997
+
998
+ await this.recordSuccess("cancel_refund_success")
999
+ }
1000
+
1001
+ return {
1002
+ data: {
1003
+ ...(input.data || {}),
1004
+ paypal: {
1005
+ ...((input.data || {}).paypal as Record<string, unknown>),
1006
+ order: order || undefined,
1007
+ authorization_id: authorizationId || storedAuthorizationId,
1008
+ capture_id: captureId || paypalData.capture_id,
1009
+ refund_id: paypalData.refund_id,
1010
+ refund_status: paypalData.refund_status,
1011
+ refunds: paypalData.refunds,
1012
+ },
1013
+ canceled_at: new Date().toISOString(),
1014
+ },
1015
+ }
1016
+ } catch (error: any) {
1017
+ await this.recordFailure("cancel_failed", {
1018
+ order_id: orderId,
1019
+ capture_id: captureId,
1020
+ debug_id: debugId,
1021
+ message: error?.message,
1022
+ })
1023
+ throw error
1024
+ }
1025
+ }
1026
+
1027
+ async deletePayment(_input: DeletePaymentInput): Promise<DeletePaymentOutput> {
1028
+ return { data: {} }
1029
+ }
1030
+
1031
+ async getWebhookActionAndData(
1032
+ payload: ProviderWebhookPayload["payload"]
1033
+ ): Promise<WebhookActionResult> {
1034
+ return getPayPalWebhookActionAndData(payload)
1035
+ }
1036
+ }
1037
+
1038
+ export default PayPalPaymentProvider
1039
+ export { PayPalPaymentProvider }