@easypayment/medusa-payment-paypal 1.3.2 → 1.3.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 (52) hide show
  1. package/.medusa/server/src/admin/index.js +99 -15
  2. package/.medusa/server/src/admin/index.mjs +99 -15
  3. package/.medusa/server/src/api/admin/paypal/logs/route.d.ts +10 -0
  4. package/.medusa/server/src/api/admin/paypal/logs/route.d.ts.map +1 -0
  5. package/.medusa/server/src/api/admin/paypal/logs/route.js +43 -0
  6. package/.medusa/server/src/api/admin/paypal/logs/route.js.map +1 -0
  7. package/.medusa/server/src/api/middlewares.d.ts.map +1 -1
  8. package/.medusa/server/src/api/middlewares.js +22 -4
  9. package/.medusa/server/src/api/middlewares.js.map +1 -1
  10. package/.medusa/server/src/api/store/paypal/create-order/route.d.ts.map +1 -1
  11. package/.medusa/server/src/api/store/paypal/create-order/route.js +10 -24
  12. package/.medusa/server/src/api/store/paypal/create-order/route.js.map +1 -1
  13. package/.medusa/server/src/api/utils/request-logger.d.ts +11 -0
  14. package/.medusa/server/src/api/utils/request-logger.d.ts.map +1 -0
  15. package/.medusa/server/src/api/utils/request-logger.js +69 -0
  16. package/.medusa/server/src/api/utils/request-logger.js.map +1 -0
  17. package/.medusa/server/src/modules/paypal/payment-provider/base-provider.d.ts +3 -3
  18. package/.medusa/server/src/modules/paypal/service.d.ts.map +1 -1
  19. package/.medusa/server/src/modules/paypal/service.js +12 -1
  20. package/.medusa/server/src/modules/paypal/service.js.map +1 -1
  21. package/.medusa/server/src/modules/paypal/types/config.d.ts +10 -0
  22. package/.medusa/server/src/modules/paypal/types/config.d.ts.map +1 -1
  23. package/.medusa/server/src/modules/paypal/types/config.js +14 -20
  24. package/.medusa/server/src/modules/paypal/types/config.js.map +1 -1
  25. package/.medusa/server/src/modules/paypal/utils/credential-resolver.d.ts.map +1 -1
  26. package/.medusa/server/src/modules/paypal/utils/credential-resolver.js +10 -0
  27. package/.medusa/server/src/modules/paypal/utils/credential-resolver.js.map +1 -1
  28. package/.medusa/server/src/modules/paypal/utils/paypal-fetch.d.ts.map +1 -1
  29. package/.medusa/server/src/modules/paypal/utils/paypal-fetch.js +39 -0
  30. package/.medusa/server/src/modules/paypal/utils/paypal-fetch.js.map +1 -1
  31. package/.medusa/server/src/modules/paypal/utils/request-logger.d.ts +62 -0
  32. package/.medusa/server/src/modules/paypal/utils/request-logger.d.ts.map +1 -0
  33. package/.medusa/server/src/modules/paypal/utils/request-logger.js +297 -0
  34. package/.medusa/server/src/modules/paypal/utils/request-logger.js.map +1 -0
  35. package/.medusa/server/src/modules/paypal/utils/storefront-url.d.ts +21 -0
  36. package/.medusa/server/src/modules/paypal/utils/storefront-url.d.ts.map +1 -0
  37. package/.medusa/server/src/modules/paypal/utils/storefront-url.js +25 -0
  38. package/.medusa/server/src/modules/paypal/utils/storefront-url.js.map +1 -0
  39. package/CHANGELOG.md +27 -0
  40. package/README.md +194 -190
  41. package/package.json +1 -1
  42. package/src/admin/routes/settings/paypal/additional-settings/page.tsx +87 -0
  43. package/src/api/admin/paypal/logs/route.ts +50 -0
  44. package/src/api/middlewares.ts +22 -4
  45. package/src/api/store/paypal/create-order/route.ts +10 -28
  46. package/src/api/utils/request-logger.ts +84 -0
  47. package/src/modules/paypal/service.ts +14 -1
  48. package/src/modules/paypal/types/config.ts +15 -24
  49. package/src/modules/paypal/utils/credential-resolver.ts +9 -0
  50. package/src/modules/paypal/utils/paypal-fetch.ts +42 -0
  51. package/src/modules/paypal/utils/request-logger.ts +358 -0
  52. package/src/modules/paypal/utils/storefront-url.ts +41 -0
package/README.md CHANGED
@@ -1,190 +1,194 @@
1
- # PayPal for Medusa
2
-
3
- **Accept PayPal and credit card payments in your Medusa v2 store — built by an official PayPal Partner.**
4
-
5
- [![npm version](https://img.shields.io/npm/v/@easypayment/medusa-payment-paypal?color=blue&label=npm)](https://www.npmjs.com/package/@easypayment/medusa-payment-paypal)
6
- [![npm downloads](https://img.shields.io/npm/dm/@easypayment/medusa-payment-paypal?color=blue&label=downloads)](https://www.npmjs.com/package/@easypayment/medusa-payment-paypal)
7
- [![License: MIT](https://img.shields.io/badge/License-MIT-green.svg)](LICENSE)
8
- [![Medusa v2](https://img.shields.io/badge/Medusa-v2-9b59b6)](https://medusajs.com)
9
- [![PayPal PPCP](https://img.shields.io/badge/PayPal-PPCP-003087)](https://developer.paypal.com)
10
-
11
- ---
12
-
13
- ## ✨ What you get
14
-
15
- | Feature | Details |
16
- |---|---|
17
- | 🔵 **PayPal Buttons** | One-click PayPal checkout for your customers |
18
- | 💳 **Card Payments** | Secure credit & debit card fields, hosted by PayPal (PCI compliant) |
19
- | 🛠 **Admin Dashboard** | Connect your PayPal account and manage everything from Medusa Admin |
20
- | 🌍 **Test & Live modes** | Try everything safely in Sandbox before going live |
21
- | 🔐 **3D Secure** | Extra card security, configurable in one click |
22
- | 🔄 **Reliable by design** | Payments are verified with PayPal at every step — webhooks, retries, and safety nets are handled for you |
23
-
24
- ---
25
-
26
- ## ✅ Requirements
27
-
28
- - Medusa **v2.12+**
29
- - Node.js **20+**
30
- - PostgreSQL
31
-
32
- ---
33
-
34
- ## 🚀 Installation
35
-
36
- In your Medusa backend folder, run:
37
-
38
- ```bash
39
- npm install @easypayment/medusa-payment-paypal
40
- ```
41
-
42
- ---
43
-
44
- ## ⚙️ Setup — 5 steps
45
-
46
- ### 1. Add the plugin to `medusa-config.ts`
47
-
48
- ```ts
49
- import { loadEnv, defineConfig } from "@medusajs/framework/utils"
50
-
51
- loadEnv(process.env.NODE_ENV || "development", process.cwd())
52
-
53
- export default defineConfig({
54
- projectConfig: {
55
- databaseUrl: process.env.DATABASE_URL,
56
- http: {
57
- storeCors: process.env.STORE_CORS!,
58
- adminCors: process.env.ADMIN_CORS!,
59
- authCors: process.env.AUTH_CORS!,
60
- jwtSecret: process.env.JWT_SECRET || "supersecret",
61
- cookieSecret: process.env.COOKIE_SECRET || "supersecret",
62
- },
63
- },
64
-
65
- plugins: [
66
- {
67
- resolve: "@easypayment/medusa-payment-paypal",
68
- options: {},
69
- },
70
- ],
71
-
72
- modules: [
73
- {
74
- resolve: "@medusajs/medusa/payment",
75
- options: {
76
- providers: [
77
- {
78
- // PayPal Buttons
79
- resolve: "@easypayment/medusa-payment-paypal/providers/paypal",
80
- id: "paypal",
81
- options: {},
82
- dependencies: ["paypal_onboarding"],
83
- },
84
- {
85
- // Card payments
86
- resolve: "@easypayment/medusa-payment-paypal/providers/paypal_card",
87
- id: "paypal_card",
88
- options: {},
89
- dependencies: ["paypal_onboarding"],
90
- },
91
- ],
92
- },
93
- },
94
- ],
95
- })
96
- ```
97
-
98
- ### 2. Run database migrations
99
-
100
- ```bash
101
- npx medusa db:migrate
102
- ```
103
-
104
- ### 3. Connect your PayPal account
105
-
106
- 1. Start your Medusa server
107
- 2. Open **Medusa Admin → Settings → PayPal**
108
- 3. Choose **Sandbox** (testing) or **Live** (real payments)
109
- 4. Click **Connect to PayPal** and follow the steps
110
-
111
- That's it — your credentials are saved automatically. Webhooks are registered for you too.
112
-
113
- > 💡 Prefer manual setup? Click **Insert credentials manually** and paste your Client ID and Secret from [developer.paypal.com](https://developer.paypal.com/dashboard/).
114
-
115
- ### 4. Turn PayPal on in your region
116
-
117
- Go to **Medusa Admin → Settings → Regions → your region** and enable:
118
-
119
- | Payment provider | What it is |
120
- |---|---|
121
- | `pp_paypal_paypal` | PayPal Buttons |
122
- | `pp_paypal_card_paypal_card` | Card payments |
123
-
124
- ### 5. Add PayPal to your storefront
125
-
126
- The checkout UI comes as a separate package — install it in your **storefront** project:
127
-
128
- 📦 **[@easypayment/medusa-paypal-ui](https://www.npmjs.com/package/@easypayment/medusa-paypal-ui)** — ready-made PayPal components for Next.js storefronts, with a step-by-step guide.
129
-
130
- ---
131
-
132
- ## 🎨 Customize (optional)
133
-
134
- Everything is managed in **Medusa Admin → Settings → PayPal** — changes apply instantly, no restart needed:
135
-
136
- - **PayPal Settings** — turn PayPal on/off, button color, shape, and label
137
- - **Advanced Card Payments** — turn card payments on/off, 3D Secure mode
138
- - **Additional Settings** — capture vs. authorize, brand name shown at PayPal, invoice prefix
139
-
140
- ---
141
-
142
- ## 🔐 Going live — two things we recommend
143
-
144
- 1. **`PAYPAL_ENCRYPTION_KEY`** — set this to any long random text in your server's environment. Your PayPal credentials are then stored encrypted in the database. Keep the key safe: if it's lost, just reconnect PayPal.
145
- 2. **`MEDUSA_BACKEND_URL`** — set this to your backend's public address (e.g. `https://api.mystore.com`) so PayPal can reach your store for payment notifications.
146
-
147
- <details>
148
- <summary><b>Advanced options</b> (for developers — everything works without these)</summary>
149
-
150
- <br>
151
-
152
- | Variable | Default | What it does |
153
- |---|---|---|
154
- | `STOREFRONT_URL` | *(unset)* | Storefront address used for PayPal return/cancel pages (can also be set in Admin) |
155
- | `PAYPAL_ENCRYPTION_STRICT` | `false` | `true` = refuse to save credentials unencrypted |
156
- | `PAYPAL_SELLER_NONCE` | *(auto)* | Set a fixed random string when running multiple server instances |
157
- | `PAYPAL_ADMIN_ORIGIN` | first `ADMIN_CORS` entry | Restricts the onboarding popup to your admin URL |
158
- | `PAYPAL_WEBHOOK_COMPLETE_CART` | `true` | Safety net that finishes an order when the payment succeeded but the buyer's browser closed. `false` disables it |
159
- | `PAYPAL_RATE_LIMIT_MAX` / `PAYPAL_RATE_LIMIT_WINDOW_MS` | *(off)* / `60000` | Optional request limit for the public checkout routes |
160
- | `PAYPAL_WEBHOOK_RATE_LIMIT_MAX` / `PAYPAL_WEBHOOK_RATE_LIMIT_WINDOW_MS` | *(off)* / `60000` | Optional request limit for the webhook endpoint (separate from the above) |
161
- | `PAYPAL_WEBHOOK_REPLAY_WINDOW_MINUTES` | `60` | Rejects webhook deliveries older than this |
162
- | `PAYPAL_WEBHOOK_STALE_PROCESSING_MS` | `300000` | When the retry job re-picks-up interrupted webhook events |
163
- | `PAYPAL_WEBHOOK_ID_LIVE` / `PAYPAL_WEBHOOK_ID_SANDBOX` | *(auto)* | Manual webhook-id override (normally automatic) |
164
- | `PAYPAL_HTTP_TIMEOUT_MS` | `30000` | Timeout for calls to PayPal |
165
- | `PAYPAL_CURRENCY` | `EUR` | Fallback currency if none is configured |
166
- | `PAYPAL_ALERT_WEBHOOK_URLS` | *(unset)* | Comma-separated URLs that receive operational alerts (including dead-lettered webhook events) |
167
- | `PAYPAL_SETTINGS_CACHE_MS` | `15000` | In-process cache for plugin settings reads; `0` disables |
168
- | `PAYPAL_SEND_SHIPPING_ADDRESS` | `false` | `true` sends the cart's shipping address on PayPal orders (`SET_PROVIDED_ADDRESS`) — improves PayPal Seller Protection eligibility |
169
- | `PAYPAL_PARTNER_SERVICE_URL` | *(built-in)* | Override the partner onboarding service used by the connect flow |
170
- | `PAYPAL_PARTNER_MERCHANT_ID_SANDBOX` / `PAYPAL_PARTNER_MERCHANT_ID_LIVE` | *(built-in)* | Override the partner merchant ids used for onboarding |
171
-
172
- **Declined cards:** when PayPal declines a capture, `/store/paypal/capture-order` responds `402` with a buyer-friendly `message` plus a structured `decline` object — `{ code, message, retryable, avs_code?, cvv_code? }` — so storefronts can show "insufficient funds, try another card" and decide whether to offer a retry.
173
-
174
- **Monitoring:** operational counters live in the `paypal_metric` table; every webhook is recorded in `paypal_webhook_event` with automatic retries (events that exhaust retries are dead-lettered **and pushed to `PAYPAL_ALERT_WEBHOOK_URLS`**); audit events are logged as JSON lines tagged `"log":"paypal_audit"` (secrets redacted).
175
-
176
- </details>
177
-
178
- ---
179
-
180
- ## 💬 Support
181
-
182
- - 🐛 **Found a bug?** [Open an issue](https://github.com/easypaymentplugins/medusa-paypal/issues)
183
- - 💡 **Questions or feature requests?** [Start a discussion](https://github.com/easypaymentplugins/medusa-paypal/discussions)
184
- - 🛍 **Storefront UI package:** [@easypayment/medusa-paypal-ui](https://www.npmjs.com/package/@easypayment/medusa-paypal-ui)
185
-
186
- ---
187
-
188
- ## 📄 License
189
-
190
- MIT © [Easy Payment](https://www.npmjs.com/package/@easypayment/medusa-payment-paypal)
1
+ # PayPal for Medusa
2
+
3
+ **Accept PayPal and credit card payments in your Medusa v2 store — built by an official PayPal Partner.**
4
+
5
+ [![npm version](https://img.shields.io/npm/v/@easypayment/medusa-payment-paypal?color=blue&label=npm)](https://www.npmjs.com/package/@easypayment/medusa-payment-paypal)
6
+ [![npm downloads](https://img.shields.io/npm/dm/@easypayment/medusa-payment-paypal?color=blue&label=downloads)](https://www.npmjs.com/package/@easypayment/medusa-payment-paypal)
7
+ [![License: MIT](https://img.shields.io/badge/License-MIT-green.svg)](LICENSE)
8
+ [![Medusa v2](https://img.shields.io/badge/Medusa-v2-9b59b6)](https://medusajs.com)
9
+ [![PayPal PPCP](https://img.shields.io/badge/PayPal-PPCP-003087)](https://developer.paypal.com)
10
+
11
+ ---
12
+
13
+ ## ✨ What you get
14
+
15
+ | Feature | Details |
16
+ |---|---|
17
+ | 🔵 **PayPal Buttons** | One-click PayPal checkout for your customers |
18
+ | 💳 **Card Payments** | Secure credit & debit card fields, hosted by PayPal (PCI compliant) |
19
+ | 🛠 **Admin Dashboard** | Connect your PayPal account and manage everything from Medusa Admin |
20
+ | 🌍 **Test & Live modes** | Try everything safely in Sandbox before going live |
21
+ | 🔐 **3D Secure** | Extra card security, configurable in one click |
22
+ | 🔄 **Reliable by design** | Payments are verified with PayPal at every step — webhooks, retries, and safety nets are handled for you |
23
+
24
+ ---
25
+
26
+ ## ✅ Requirements
27
+
28
+ - Medusa **v2.12+**
29
+ - Node.js **20+**
30
+ - PostgreSQL
31
+
32
+ ---
33
+
34
+ ## 🚀 Installation
35
+
36
+ In your Medusa backend folder, run:
37
+
38
+ ```bash
39
+ npm install @easypayment/medusa-payment-paypal
40
+ ```
41
+
42
+ ---
43
+
44
+ ## ⚙️ Setup — 5 steps
45
+
46
+ ### 1. Add the plugin to `medusa-config.ts`
47
+
48
+ ```ts
49
+ import { loadEnv, defineConfig } from "@medusajs/framework/utils"
50
+
51
+ loadEnv(process.env.NODE_ENV || "development", process.cwd())
52
+
53
+ export default defineConfig({
54
+ projectConfig: {
55
+ databaseUrl: process.env.DATABASE_URL,
56
+ http: {
57
+ storeCors: process.env.STORE_CORS!,
58
+ adminCors: process.env.ADMIN_CORS!,
59
+ authCors: process.env.AUTH_CORS!,
60
+ jwtSecret: process.env.JWT_SECRET || "supersecret",
61
+ cookieSecret: process.env.COOKIE_SECRET || "supersecret",
62
+ },
63
+ },
64
+
65
+ plugins: [
66
+ {
67
+ resolve: "@easypayment/medusa-payment-paypal",
68
+ options: {},
69
+ },
70
+ ],
71
+
72
+ modules: [
73
+ {
74
+ resolve: "@medusajs/medusa/payment",
75
+ options: {
76
+ providers: [
77
+ {
78
+ // PayPal Buttons
79
+ resolve: "@easypayment/medusa-payment-paypal/providers/paypal",
80
+ id: "paypal",
81
+ options: {},
82
+ dependencies: ["paypal_onboarding"],
83
+ },
84
+ {
85
+ // Card payments
86
+ resolve: "@easypayment/medusa-payment-paypal/providers/paypal_card",
87
+ id: "paypal_card",
88
+ options: {},
89
+ dependencies: ["paypal_onboarding"],
90
+ },
91
+ ],
92
+ },
93
+ },
94
+ ],
95
+ })
96
+ ```
97
+
98
+ ### 2. Run database migrations
99
+
100
+ ```bash
101
+ npx medusa db:migrate
102
+ ```
103
+
104
+ ### 3. Connect your PayPal account
105
+
106
+ 1. Start your Medusa server
107
+ 2. Open **Medusa Admin → Settings → PayPal**
108
+ 3. Choose **Sandbox** (testing) or **Live** (real payments)
109
+ 4. Click **Connect to PayPal** and follow the steps
110
+
111
+ That's it — your credentials are saved automatically. Webhooks are registered for you too.
112
+
113
+ > 💡 Prefer manual setup? Click **Insert credentials manually** and paste your Client ID and Secret from [developer.paypal.com](https://developer.paypal.com/dashboard/).
114
+
115
+ ### 4. Turn PayPal on in your region
116
+
117
+ Go to **Medusa Admin → Settings → Regions → your region** and enable:
118
+
119
+ | Payment provider | What it is |
120
+ |---|---|
121
+ | `pp_paypal_paypal` | PayPal Buttons |
122
+ | `pp_paypal_card_paypal_card` | Card payments |
123
+
124
+ ### 5. Add PayPal to your storefront
125
+
126
+ The checkout UI comes as a separate package — install it in your **storefront** project:
127
+
128
+ 📦 **[@easypayment/medusa-paypal-ui](https://www.npmjs.com/package/@easypayment/medusa-paypal-ui)** — ready-made PayPal components for Next.js storefronts, with a step-by-step guide.
129
+
130
+ ---
131
+
132
+ ## 🎨 Customize (optional)
133
+
134
+ Everything is managed in **Medusa Admin → Settings → PayPal** — changes apply instantly, no restart needed:
135
+
136
+ - **PayPal Settings** — turn PayPal on/off, button color, shape, and label
137
+ - **Advanced Card Payments** — turn card payments on/off, 3D Secure mode
138
+ - **Additional Settings** — capture vs. authorize, brand name shown at PayPal, invoice prefix
139
+
140
+ ---
141
+
142
+ ## 🔐 Going live — two things we recommend
143
+
144
+ 1. **`PAYPAL_ENCRYPTION_KEY`** — set this to any long random text in your server's environment. Your PayPal credentials are then stored encrypted in the database. Keep the key safe: if it's lost, just reconnect PayPal.
145
+ 2. **`MEDUSA_BACKEND_URL`** — set this to your backend's public address (e.g. `https://api.mystore.com`) so PayPal can reach your store for payment notifications.
146
+
147
+ <details>
148
+ <summary><b>Advanced options</b> (for developers — everything works without these)</summary>
149
+
150
+ <br>
151
+
152
+ | Variable | Default | What it does |
153
+ |---|---|---|
154
+ | `STOREFRONT_URL` | *(request origin, if listed in `STORE_CORS`)* | Storefront address used for PayPal return/cancel pages (can also be set in Admin) |
155
+ | `PAYPAL_ENCRYPTION_STRICT` | `false` | `true` = refuse to save credentials unencrypted |
156
+ | `PAYPAL_SELLER_NONCE` | *(partner service nonce)* | Only change this if you also run your own `PAYPAL_PARTNER_SERVICE_URL`; it must match the nonce that service puts in its onboarding links |
157
+ | `PAYPAL_ADMIN_ORIGIN` | first `ADMIN_CORS` entry | Restricts the onboarding popup to your admin URL |
158
+ | `PAYPAL_WEBHOOK_COMPLETE_CART` | `true` | Safety net that finishes an order when the payment succeeded but the buyer's browser closed. `false` disables it |
159
+ | `PAYPAL_RATE_LIMIT_MAX` / `PAYPAL_RATE_LIMIT_WINDOW_MS` | *(off)* / `60000` | Optional request limit for the public checkout routes |
160
+ | `PAYPAL_WEBHOOK_RATE_LIMIT_MAX` / `PAYPAL_WEBHOOK_RATE_LIMIT_WINDOW_MS` | *(off)* / `60000` | Optional request limit for the webhook endpoint (separate from the above) |
161
+ | `PAYPAL_WEBHOOK_REPLAY_WINDOW_MINUTES` | `60` | Rejects webhook deliveries older than this |
162
+ | `PAYPAL_WEBHOOK_STALE_PROCESSING_MS` | `300000` | When the retry job re-picks-up interrupted webhook events |
163
+ | `PAYPAL_WEBHOOK_ID_LIVE` / `PAYPAL_WEBHOOK_ID_SANDBOX` | *(auto)* | Manual webhook-id override (normally automatic) |
164
+ | `PAYPAL_HTTP_TIMEOUT_MS` | `30000` | Timeout for calls to PayPal |
165
+ | `PAYPAL_CURRENCY` | `EUR` | Fallback currency if none is configured |
166
+ | `PAYPAL_ALERT_WEBHOOK_URLS` | *(unset)* | Comma-separated URLs that receive operational alerts (including dead-lettered webhook events) |
167
+ | `PAYPAL_SETTINGS_CACHE_MS` | `15000` | In-process cache for plugin settings reads; `0` disables |
168
+ | `PAYPAL_REQUEST_LOG` | *(off)* | `1`/`true` force-enables the request/response log file regardless of the admin toggle (normally enabled from **Settings → PayPal → Additional Settings**) |
169
+ | `PAYPAL_LOG_DIR` | `./logs` | Directory for the `paypal-requests-YYYY-MM-DD.log` file written when logging is on |
170
+ | `PAYPAL_SEND_SHIPPING_ADDRESS` | `false` | `true` sends the cart's shipping address on PayPal orders (`SET_PROVIDED_ADDRESS`) — improves PayPal Seller Protection eligibility |
171
+ | `PAYPAL_PARTNER_SERVICE_URL` | *(built-in)* | Override the partner onboarding service used by the connect flow |
172
+ | `PAYPAL_PARTNER_MERCHANT_ID_SANDBOX` / `PAYPAL_PARTNER_MERCHANT_ID_LIVE` | *(built-in)* | Override the partner merchant ids used for onboarding |
173
+
174
+ **Declined cards:** when PayPal declines a capture, `/store/paypal/capture-order` responds `402` with a buyer-friendly `message` plus a structured `decline` object — `{ code, message, retryable, avs_code?, cvv_code? }` — so storefronts can show "insufficient funds, try another card" and decide whether to offer a retry.
175
+
176
+ **Monitoring:** operational counters live in the `paypal_metric` table; every webhook is recorded in `paypal_webhook_event` with automatic retries (events that exhaust retries are dead-lettered **and pushed to `PAYPAL_ALERT_WEBHOOK_URLS`**); audit events are logged as JSON lines tagged `"log":"paypal_audit"` (secrets redacted).
177
+
178
+ **Integration log for PayPal review:** turn on **Settings → PayPal → Additional Settings → Request/response logging** (off by default) to append every PayPal API call and every plugin API request/response to `logs/paypal-requests-YYYY-MM-DD.log`. Credentials are redacted while the `PayPal-Partner-Attribution-Id` (BN code) is kept, so the file is safe to hand to PayPal's go-live review. Download it from the same settings page (**Download log**) or at `GET /admin/paypal/logs?download=1`. Turn it back off once the review is complete.
179
+
180
+ </details>
181
+
182
+ ---
183
+
184
+ ## 💬 Support
185
+
186
+ - 🐛 **Found a bug?** [Open an issue](https://github.com/easypaymentplugins/medusa-paypal/issues)
187
+ - 💡 **Questions or feature requests?** [Start a discussion](https://github.com/easypaymentplugins/medusa-paypal/discussions)
188
+ - 🛍 **Storefront UI package:** [@easypayment/medusa-paypal-ui](https://www.npmjs.com/package/@easypayment/medusa-paypal-ui)
189
+
190
+ ---
191
+
192
+ ## 📄 License
193
+
194
+ MIT © [Easy Payment](https://www.npmjs.com/package/@easypayment/medusa-payment-paypal)
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@easypayment/medusa-payment-paypal",
3
- "version": "1.3.2",
3
+ "version": "1.3.4",
4
4
  "description": "PayPal & credit card payments for Medusa v2 — PayPal Buttons, hosted card fields, 3D Secure, and an admin dashboard. Built by a PayPal Partner.",
5
5
  "author": "EasyPayment Plugins",
6
6
  "license": "MIT",
@@ -16,6 +16,7 @@ type AdditionalSettingsForm = {
16
16
  sendItemDetails: boolean
17
17
  invoicePrefix: string
18
18
  creditCardStatementName: string
19
+ debugLogging: boolean
19
20
  }
20
21
 
21
22
  const DEFAULT_FORM: AdditionalSettingsForm = {
@@ -26,6 +27,7 @@ const DEFAULT_FORM: AdditionalSettingsForm = {
26
27
  sendItemDetails: true,
27
28
  invoicePrefix: "PP-",
28
29
  creditCardStatementName: "PayPal",
30
+ debugLogging: false,
29
31
  }
30
32
 
31
33
  /** Overlay saved values on the defaults, ignoring `undefined` entries. */
@@ -47,11 +49,55 @@ export default function AdditionalSettingsTab() {
47
49
  }))
48
50
  const [loading, setLoading] = useState(false)
49
51
  const [saving, setSaving] = useState(false)
52
+ const [downloading, setDownloading] = useState(false)
50
53
  const [toast, setToast] = useState<ToastState>(null)
51
54
  const didInit = useRef(false)
52
55
 
53
56
  const dismissToast = useCallback(() => setToast(null), [])
54
57
 
58
+ async function onDownloadLog() {
59
+ try {
60
+ setDownloading(true)
61
+ setToast(null)
62
+ const headers: Record<string, string> = { Accept: "text/plain" }
63
+ if (typeof window !== "undefined") {
64
+ const token = (window as any).__medusa__?.token
65
+ if (token) headers["Authorization"] = `Bearer ${token}`
66
+ }
67
+ const res = await fetch("/admin/paypal/logs?download=1", {
68
+ headers,
69
+ credentials: "include",
70
+ })
71
+ if (!res.ok) {
72
+ if (res.status === 404) {
73
+ throw new Error(
74
+ "No log file yet. Enable logging, run a test transaction, then download."
75
+ )
76
+ }
77
+ throw new Error(`Download failed (${res.status})`)
78
+ }
79
+ const blob = await res.blob()
80
+ const dispo = res.headers.get("Content-Disposition") || ""
81
+ const match = dispo.match(/filename="?([^"]+)"?/)
82
+ const filename = match?.[1] || "paypal-requests.log"
83
+ const url = URL.createObjectURL(blob)
84
+ const a = document.createElement("a")
85
+ a.href = url
86
+ a.download = filename
87
+ document.body.appendChild(a)
88
+ a.click()
89
+ a.remove()
90
+ URL.revokeObjectURL(url)
91
+ } catch (e: unknown) {
92
+ setToast({
93
+ kind: "error",
94
+ message: e instanceof Error ? e.message : "Failed to download log",
95
+ })
96
+ } finally {
97
+ setDownloading(false)
98
+ }
99
+ }
100
+
55
101
  useEffect(() => {
56
102
  if (didInit.current) return
57
103
  didInit.current = true
@@ -240,6 +286,47 @@ export default function AdditionalSettingsTab() {
240
286
  </FieldRow>
241
287
  </div>
242
288
  </SectionCard>
289
+
290
+ <SectionCard
291
+ title="Integration logging (PayPal review)"
292
+ description="Write every PayPal API request/response and plugin API request/response to a log file you can download and send to PayPal for integration approval. Credentials (auth tokens, client secrets, card fields) are redacted; the BN code is kept. Keep this OFF in normal production use."
293
+ right={
294
+ <div className="flex items-center gap-3">
295
+ <button
296
+ type="button"
297
+ onClick={onDownloadLog}
298
+ disabled={downloading}
299
+ className="transition-fg relative inline-flex w-fit items-center justify-center overflow-hidden rounded-md outline-none shadow-buttons-neutral text-ui-fg-base bg-ui-button-neutral after:transition-fg after:absolute after:inset-0 after:content-[''] after:button-neutral-gradient hover:bg-ui-button-neutral-hover hover:after:button-neutral-hover-gradient active:bg-ui-button-neutral-pressed active:after:button-neutral-pressed-gradient focus-visible:shadow-buttons-neutral-focus disabled:bg-ui-bg-disabled disabled:border-ui-border-base disabled:text-ui-fg-disabled disabled:shadow-buttons-neutral disabled:after:hidden txt-compact-small-plus px-3 py-1.5"
300
+ >
301
+ {downloading ? "Preparing…" : "Download log"}
302
+ </button>
303
+ </div>
304
+ }
305
+ >
306
+ <div className="divide-y divide-ui-border-base">
307
+ <FieldRow
308
+ label="Request/response logging"
309
+ hint="When enabled, the plugin appends each request and response to logs/paypal-requests-YYYY-MM-DD.log (path configurable via PAYPAL_LOG_DIR). Remember to save after toggling."
310
+ >
311
+ <label className="inline-flex items-center gap-2">
312
+ <input
313
+ type="checkbox"
314
+ checked={form.debugLogging}
315
+ onChange={(e) =>
316
+ setForm((p) => ({
317
+ ...p,
318
+ debugLogging: e.target.checked,
319
+ }))
320
+ }
321
+ className="h-4 w-4 rounded border-ui-border-base"
322
+ />
323
+ <span className="text-sm text-ui-fg-base">
324
+ Enable request/response log file
325
+ </span>
326
+ </label>
327
+ </FieldRow>
328
+ </div>
329
+ </SectionCard>
243
330
  </div>
244
331
  </div>
245
332
  )
@@ -0,0 +1,50 @@
1
+ import fs from "fs"
2
+ import path from "path"
3
+ import type { MedusaRequest, MedusaResponse } from "@medusajs/framework/http"
4
+ import {
5
+ isRequestLoggingEnabled,
6
+ listLogFiles,
7
+ resolveLogFile,
8
+ } from "../../../../modules/paypal/utils/request-logger"
9
+
10
+ /**
11
+ * GET /admin/paypal/logs
12
+ * → { enabled, files: [{ name, size, modified }] }
13
+ *
14
+ * GET /admin/paypal/logs?file=<name>&download=1 (file optional → newest)
15
+ * → the raw log file as a text/plain attachment, for sending to PayPal.
16
+ */
17
+ export async function GET(req: MedusaRequest, res: MedusaResponse) {
18
+ try {
19
+ const query = req.query as Record<string, string | undefined>
20
+ const wantsDownload =
21
+ query.download === "1" ||
22
+ query.download === "true" ||
23
+ typeof query.file === "string"
24
+
25
+ if (wantsDownload) {
26
+ const filePath = resolveLogFile(query.file)
27
+ if (!filePath) {
28
+ return res.status(404).json({ message: "Log file not found" })
29
+ }
30
+ const name = path.basename(filePath)
31
+ res.setHeader("Content-Type", "text/plain; charset=utf-8")
32
+ res.setHeader(
33
+ "Content-Disposition",
34
+ `attachment; filename="${name}"`
35
+ )
36
+ return res.send(fs.readFileSync(filePath, "utf8"))
37
+ }
38
+
39
+ return res.json({
40
+ enabled: isRequestLoggingEnabled(),
41
+ files: listLogFiles(),
42
+ })
43
+ } catch (e: unknown) {
44
+ console.error(
45
+ "[PayPal] logs GET failed:",
46
+ e instanceof Error ? e.message : e
47
+ )
48
+ return res.status(500).json({ message: "Failed to read PayPal logs" })
49
+ }
50
+ }
@@ -1,8 +1,30 @@
1
1
  import { defineMiddlewares } from "@medusajs/framework/http"
2
2
  import { createRateLimiter } from "./utils/rate-limit"
3
+ import { createInboundLogger } from "./utils/request-logger"
3
4
 
4
5
  export default defineMiddlewares({
5
6
  routes: [
7
+ // Opt-in request/response logging for the plugin's API routes. One catch-all
8
+ // per namespace is enough — every /store/paypal/*, /admin/paypal/* and
9
+ // /hooks/paypal/* request matches its namespace entry, and the logger
10
+ // de-dupes per request so overlapping matchers can't double-log. It is a
11
+ // pass-through unless logging is enabled in settings.
12
+ {
13
+ matcher: "/store/paypal/:path*",
14
+ middlewares: [createInboundLogger()],
15
+ },
16
+ {
17
+ matcher: "/store/paypal-complete",
18
+ middlewares: [createInboundLogger()],
19
+ },
20
+ {
21
+ matcher: "/admin/paypal/:path*",
22
+ middlewares: [createInboundLogger()],
23
+ },
24
+ {
25
+ matcher: "/hooks/paypal/:path*",
26
+ middlewares: [createInboundLogger()],
27
+ },
6
28
  {
7
29
  // Keep the exact bytes PayPal signed (`req.rawBody`) so webhook signature
8
30
  // verification hashes the original payload, not a re-serialized copy. This
@@ -61,9 +83,5 @@ export default defineMiddlewares({
61
83
  method: ["GET"],
62
84
  middlewares: [createRateLimiter("config")],
63
85
  },
64
- {
65
- matcher: "/store/paypal/:path*",
66
- middlewares: [],
67
- },
68
86
  ],
69
87
  })