@edutecka-mz/edpay-sdk 1.0.2 → 1.6.0

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 (70) hide show
  1. package/CHANGELOG.md +17 -0
  2. package/README.md +126 -18
  3. package/dist/client.d.ts +9 -5
  4. package/dist/client.d.ts.map +1 -1
  5. package/dist/client.js +36 -16
  6. package/dist/client.js.map +1 -1
  7. package/dist/contacts.d.ts +32 -0
  8. package/dist/contacts.d.ts.map +1 -0
  9. package/dist/contacts.js +129 -0
  10. package/dist/contacts.js.map +1 -0
  11. package/dist/edpay.js +5 -1
  12. package/dist/exceptions.d.ts +8 -1
  13. package/dist/exceptions.d.ts.map +1 -1
  14. package/dist/exceptions.js +7 -1
  15. package/dist/exceptions.js.map +1 -1
  16. package/dist/frontend.d.ts +1 -0
  17. package/dist/frontend.d.ts.map +1 -1
  18. package/dist/frontend.js +23 -4
  19. package/dist/frontend.js.map +1 -1
  20. package/dist/index.d.ts +2 -0
  21. package/dist/index.d.ts.map +1 -1
  22. package/dist/index.js +1 -0
  23. package/dist/index.js.map +1 -1
  24. package/dist/resources/customers.d.ts +3 -2
  25. package/dist/resources/customers.d.ts.map +1 -1
  26. package/dist/resources/customers.js +8 -3
  27. package/dist/resources/customers.js.map +1 -1
  28. package/dist/resources/fx.d.ts +8 -0
  29. package/dist/resources/fx.d.ts.map +1 -0
  30. package/dist/resources/fx.js +19 -0
  31. package/dist/resources/fx.js.map +1 -0
  32. package/dist/resources/invoices.d.ts +1 -4
  33. package/dist/resources/invoices.d.ts.map +1 -1
  34. package/dist/resources/invoices.js +6 -13
  35. package/dist/resources/invoices.js.map +1 -1
  36. package/dist/resources/payments.d.ts +13 -3
  37. package/dist/resources/payments.d.ts.map +1 -1
  38. package/dist/resources/payments.js +36 -3
  39. package/dist/resources/payments.js.map +1 -1
  40. package/dist/resources/public.d.ts +8 -0
  41. package/dist/resources/public.d.ts.map +1 -0
  42. package/dist/resources/public.js +14 -0
  43. package/dist/resources/public.js.map +1 -0
  44. package/dist/resources/subscriptions.d.ts +1 -6
  45. package/dist/resources/subscriptions.d.ts.map +1 -1
  46. package/dist/resources/subscriptions.js +6 -19
  47. package/dist/resources/subscriptions.js.map +1 -1
  48. package/dist/resources/wallets.d.ts +14 -0
  49. package/dist/resources/wallets.d.ts.map +1 -0
  50. package/dist/resources/wallets.js +30 -0
  51. package/dist/resources/wallets.js.map +1 -0
  52. package/dist/resources/webhooks.d.ts +16 -0
  53. package/dist/resources/webhooks.d.ts.map +1 -0
  54. package/dist/resources/webhooks.js +37 -0
  55. package/dist/resources/webhooks.js.map +1 -0
  56. package/dist/types.d.ts +91 -40
  57. package/dist/types.d.ts.map +1 -1
  58. package/dist/webhooks.d.ts +10 -6
  59. package/dist/webhooks.d.ts.map +1 -1
  60. package/dist/webhooks.js +31 -20
  61. package/dist/webhooks.js.map +1 -1
  62. package/package.json +4 -2
  63. package/dist/resources/checkout.d.ts +0 -11
  64. package/dist/resources/checkout.d.ts.map +0 -1
  65. package/dist/resources/checkout.js +0 -25
  66. package/dist/resources/checkout.js.map +0 -1
  67. package/dist/resources/payment-links.d.ts +0 -11
  68. package/dist/resources/payment-links.d.ts.map +0 -1
  69. package/dist/resources/payment-links.js +0 -25
  70. package/dist/resources/payment-links.js.map +0 -1
package/CHANGELOG.md ADDED
@@ -0,0 +1,17 @@
1
+ # Changelog
2
+
3
+ ## 1.6.0
4
+
5
+ - Add the unified payment parent and child checkout operations for private API, hosted checkout, and link checkout.
6
+ - Add opaque-token buyer routes and checkout history on the parent payment.
7
+ - Keep the local Laravel payment lookup separate from the remote API retrieval.
8
+
9
+ ## 1.5.0
10
+
11
+ - Improve payment method handling and idempotent payment requests.
12
+
13
+ ## 1.4.0
14
+
15
+ - Add partner resources for payments, customers, payment links, invoices and invoice series, FX, wallets, webhooks, and the public payment-method catalog.
16
+ - Add hosted checkout sessions, configurable contact helpers, and method presets for supported phone methods.
17
+ - Keep public payment-method catalog and token-based checkout requests unauthenticated so private keys are not sent to public routes; session creation remains authenticated.
package/README.md CHANGED
@@ -4,7 +4,7 @@ The official JavaScript and TypeScript SDK for server-side Node.js applications.
4
4
 
5
5
  ## Requirements
6
6
 
7
- - Node.js 20 or later
7
+ - Node.js 22.23.5 or later in the 22.x line, 24.22.3 or later in the 24.x line, or 26.13.1 or later in the 26.x line.
8
8
  - npm, pnpm, or yarn
9
9
 
10
10
  ## Install
@@ -17,18 +17,58 @@ npm install @edutecka-mz/edpay-sdk
17
17
 
18
18
  The package import name is `@edutecka-mz/edpay-sdk`.
19
19
 
20
+ ## Format and validate phone contacts
21
+
22
+ The contact helpers normalize common phone input (`+258...`, `258...`, `00 258...`, or national digits), reject unsupported characters, and can validate the national length and prefixes required by the selected payment method. They default to Mozambique's calling code (`258`) and nine national digits. Pass different rules when the selected method or country uses another format; the API's payment method identifier remains dynamic.
23
+
24
+ ```typescript
25
+ import {
26
+ addCountryPrefix,
27
+ formatPhoneNumber,
28
+ normalizePhoneNumber,
29
+ phoneNumberOptionsForMethod,
30
+ removeCountryPrefix,
31
+ validatePhoneNumber,
32
+ } from "@edutecka-mz/edpay-sdk";
33
+
34
+ const contactInput = process.env.CUSTOMER_PHONE ?? "";
35
+ const selectedMethodRules = phoneNumberOptionsForMethod(process.env.EDPAY_METHOD ?? "");
36
+ if (selectedMethodRules !== null) {
37
+ if (!validatePhoneNumber(contactInput, selectedMethodRules)) {
38
+ throw new Error("Phone number is invalid for the selected method.");
39
+ }
40
+ const phoneForRequest = normalizePhoneNumber(contactInput, selectedMethodRules);
41
+ const phoneForDisplay = formatPhoneNumber(contactInput, selectedMethodRules);
42
+ const internationalPhone = addCountryPrefix(contactInput, selectedMethodRules);
43
+ const nationalPhone = removeCountryPrefix(contactInput, selectedMethodRules);
44
+ }
45
+ ```
46
+
47
+ `phoneNumberOptionsForMethod(method)` supplies the known rules for `emola` (national `86`/`87`, output `national`) and `mpesa` (`84`/`85`, output `country-code`, i.e. `258` plus national digits). It returns `null` for other method identifiers, including non-phone methods; use account-provided rules for other phone methods and skip phone validation for tokenized methods. `nationalPrefixes` and country rules remain configurable. `validatePhoneNumber` returns a boolean.
48
+
49
+ ## Load available payment methods
50
+
51
+ After creating the client, use the public catalog to populate a method selector, then send the selected `code` to the payment resource. The SDK does not hard-code gateway identifiers:
52
+
53
+ ```typescript
54
+ const catalog = await edpay.public.listPaymentMethods();
55
+ const availableMethods = catalog.data.payment_methods.filter((method) => method.enabled);
56
+ ```
57
+
20
58
  ## Create a payment from a Node.js service
21
59
 
60
+ Every partner API request requires both `EDPAY_PUBLIC_KEY` (`pk_test_` or `pk_live_`) and `EDPAY_PRIVATE_KEY` (`sk_test_` or `sk_live_`) from the same environment. The SDK rejects missing, blank, or mismatched key pairs when creating the client. Public catalog requests and buyer-facing checkout requests authenticated by a checkout token do not use the partner key pair; never put the private key in browser code.
61
+
22
62
  Store the keys in the server environment, not in source control:
23
63
 
24
64
  ```dotenv
25
65
  EDPAY_PUBLIC_KEY=pk_test_...
26
66
  EDPAY_PRIVATE_KEY=sk_test_...
27
- EDPAY_METHOD=method_id_from_payment_methods
28
67
  ```
29
68
 
30
69
  ```typescript
31
70
  import { EDPayClient } from "@edutecka-mz/edpay-sdk";
71
+ import { normalizePhoneNumber, phoneNumberOptionsForMethod } from "@edutecka-mz/edpay-sdk";
32
72
 
33
73
  const edpay = new EDPayClient({
34
74
  publicKey: process.env.EDPAY_PUBLIC_KEY!,
@@ -39,16 +79,15 @@ const edpay = new EDPayClient({
39
79
  const payment = await edpay.payments.create({
40
80
  amount_minor: 50000, // 500.00 MZN
41
81
  currency: "MZN",
42
- method: process.env.EDPAY_METHOD, // Select an ID supported by the account/API.
43
82
  reference: "ORDER-10492",
44
83
  description: "Example order",
45
- idempotencyKey: "ORDER-10492",
84
+ idempotencyKey: "ORDER-10492-CREATE-1",
46
85
  });
47
86
 
48
87
  console.log(payment);
49
88
  ```
50
89
 
51
- By default, the client uses `https://api-pay.edutecka.com`; set `baseUrl` only when EDPay provides a different API host for your account. Sandbox or production access is determined by the API keys. The client sends `X-EDPay-Public-Key` and `X-EDPay-Private-Key` headers. `idempotencyKey` is sent as the `Idempotency-Key` header. Payment amounts are expressed in minor currency units. The `method` is dynamic and should be an identifier returned by `GET /v1/public/payment-methods` or otherwise supported for the account; do not hard-code a particular gateway into a multi-gateway flow.
90
+ By default, the client uses `https://api-pay.edutecka.com`; set `baseUrl` only when EDPay provides a different API host for your account. Sandbox or production access is determined by the API keys. Partner requests send `X-EDPay-Public-Key` and `X-EDPay-Private-Key`; the public catalog and token-based checkout routes omit them. `idempotencyKey` is sent as the `Idempotency-Key` header. Payment amounts are expressed in minor currency units. `payments.create` creates only the parent payment. Select a dynamic method afterward through `privateCheckout`, or let the buyer choose in hosted or link checkout. Method fields such as `phone` or `channel` belong to that child operation and depend on the selected method.
52
91
 
53
92
  ### Browser checkout (frontend only)
54
93
 
@@ -57,6 +96,7 @@ By default, the client uses `https://api-pay.edutecka.com`; set `baseUrl` only w
57
96
  ```typescript
58
97
  import { EDPay } from "@edutecka-mz/edpay-sdk/frontend";
59
98
 
99
+ const checkoutToken = "<TOKEN_RETURNED_BY_YOUR_SERVER>";
60
100
  const checkoutClient = new EDPay({
61
101
  publicKey: process.env.NEXT_PUBLIC_EDPAY_PUBLIC_KEY!,
62
102
  environment: "sandbox",
@@ -73,50 +113,118 @@ Use the server-side `edpay` (`EDPayClient`) instance created in the first exampl
73
113
  const payment = await edpay.payments.retrieve("PAYMENT_ID");
74
114
  ```
75
115
 
76
- ## Create a hosted checkout session
116
+ ## Choose a checkout mode for one payment
77
117
 
78
- Create the session on your server, then send the customer to the hosted checkout URL returned by the API:
118
+ `payments.create` creates the parent record only. After saving its ID and reference with your order, use a child function to choose the integration. The same payment can be opened through private API processing, hosted checkout, or a shareable link checkout. A buyer can choose a method at checkout; the payment ID and reference remain unchanged.
79
119
 
80
120
  ```typescript
81
- const session = await edpay.checkout.createSession({
121
+ const payment = await edpay.payments.create({
82
122
  amount_minor: 50000,
83
123
  currency: "MZN",
84
- success_url: "https://merchant.example/checkout/success",
85
- cancel_url: "https://merchant.example/checkout/cancel",
86
124
  reference: "ORDER-10492",
87
- idempotencyKey: "ORDER-10492-checkout",
125
+ idempotencyKey: "ORDER-10492-CREATE",
88
126
  });
127
+ const paymentId = payment.data.id;
89
128
 
90
- console.log(session);
129
+ // Choose one checkout mode for this parent payment:
130
+ const checkout = await edpay.payments.publicCheckout(paymentId, {
131
+ idempotencyKey: "ORDER-10492-PUBLIC-CHECKOUT",
132
+ });
133
+ // Or call privateCheckout(paymentId, options) or linkCheckout(paymentId, options).
134
+ // Use checkout.data.token in the buyer-facing checkout. Never send partner keys to a browser.
91
135
  ```
92
136
 
93
- The SDK sends this request to `POST /v1/checkout/sessions`. Confirm payment using a verified webhook or a server-side payment lookup; a browser redirect alone is not proof of payment.
94
-
137
+ `privateCheckout` submits a method from your backend. `publicCheckout` returns a token for EDPay-hosted checkout. `linkCheckout` returns a shareable token for the same payment. `listCheckouts(paymentId)` lists private executions, public/link executions, and sessions with no submitted method; each execution keeps the checkout mode that started it. `retrieve(paymentId)` fetches current status from the API; use verified webhooks for asynchronous updates.
138
+
139
+ ## Function reference
140
+
141
+ Each row tells you what the call does and when to use it. Partner calls use the API key pair; public catalog and buyer checkout calls do not. Supply a stable `Idempotency-Key` for writes where required.
142
+
143
+ | Resource | Function | Endpoint | What it does / when to use it |
144
+ |---|---|---|---|
145
+ | Payments | `payments.create` | `POST /v1/payments` | Creates the parent payment only. Save its ID and reference, then choose a checkout mode. |
146
+ | Payments | `payments.privateCheckout` | `POST /v1/payments/{id}/private-checkout` | Submits a selected method from your server for the existing payment. Use when your backend controls the interface. |
147
+ | Payments | `payments.publicCheckout` | `POST /v1/payments/{id}/public-checkout` | Creates an opaque token for EDPay-hosted checkout on the existing payment. |
148
+ | Payments | `payments.linkCheckout` | `POST /v1/payments/{id}/link-checkout` | Creates a shareable buyer token for the existing payment; it does not create another payment. |
149
+ | Payments | `payments.listCheckouts` | `GET /v1/payments/{id}/checkouts` | Lists executions with their checkout mode and sessions where no method was submitted. |
150
+ | Payments | `payments.retrieve` | `GET /v1/payments/{id}` | Retrieves remote payment status. |
151
+ | Payments | `payments.listEvents` | `GET /v1/payments/{id}/events` | Reads recorded payment status changes. |
152
+ | Payments | `payments.list` | `GET /v1/payments` | Lists account payments for reconciliation or history. |
153
+ | Hosted checkout | `payments.getCheckout` | `GET /v1/payments/checkouts/{token}` | Loads the buyer-facing hosted or link checkout with its opaque token. |
154
+ | Hosted checkout | `payments.submitCheckoutPayment` | `POST /v1/payments/checkouts/{token}/payment` | Submits the buyer-selected method and required method fields with an idempotency key. |
155
+ | Hosted checkout | `payments.retrieveCheckoutPayment` | `GET /v1/payments/checkouts/{token}/payment` | Reads the parent payment status without exposing its ID to the buyer. |
156
+ | Hosted checkout | `payments.framePolicy` | `GET /v1/payments/checkouts/{token}/frame-policy` | Checks whether the hosted checkout can be embedded. |
157
+ | Customers | `customers.create` | `POST /v1/customers` | Creates a customer record for the authenticated account. Save customer details before associating them with payments or invoices. |
158
+ | Customers | `customers.list` | `GET /v1/customers` | Lists customers in the current account and environment. Build a customer picker or reconcile customer records. |
159
+ | Customers | `customers.retrieve` | `GET /v1/customers/{id}` | Reads one customer record. Load a customer's saved details by ID. |
160
+ | Customers | `customers.update` | `PATCH /v1/customers/{id}` | Updates the supplied customer fields. Correct or refresh a customer's details; use a stable idempotency key where required. |
161
+ | Invoices | `invoices.create` | `POST /v1/invoices` | Creates a draft invoice with its customer and line items. Prepare an invoice before issuing it to the customer. |
162
+ | Invoices | `invoices.list` | `GET /v1/invoices` | Lists invoices, optionally limited to a page size. Show or reconcile invoices for the account. |
163
+ | Invoices | `invoices.retrieve` | `GET /v1/invoices/{id}` | Reads one invoice and its current state. Load invoice details or check its lifecycle. |
164
+ | Invoices | `invoices.finalize` | `POST /v1/invoices/{id}/finalize` | Issues the draft invoice and makes it available for payment. The invoice is complete and ready to send to the customer. |
165
+ | Invoices | `invoices.voidInvoice` | `POST /v1/invoices/{id}/void` | Voids an invoice that should no longer be payable. Cancel an issued invoice according to its allowed state transitions. |
166
+ | Invoice series | `subscriptions.create` | `POST /v1/invoices/series` | Creates a schedule that issues invoices on the configured interval. Bill a customer repeatedly using a defined start date, interval, and due period. |
167
+ | Invoice series | `subscriptions.list` | `GET /v1/invoices/series` | Lists invoice series; there is no series-detail endpoint in this API version. Review recurring schedules for the account. |
168
+ | Invoice series | `subscriptions.pause` | `POST /v1/invoices/series/{id}/pause` | Pauses future invoice generation for a series. Temporarily stop recurring billing without deleting the schedule. |
169
+ | Invoice series | `subscriptions.resume` | `POST /v1/invoices/series/{id}/resume` | Resumes invoice generation for a paused series. Restart recurring billing after the pause condition has ended. |
170
+ | FX quotes | `fx.quote` | `GET /v1/fx/quote` | Returns an indicative conversion quote for an amount and currency pair. Display a conversion estimate before creating a payment. A quote is not a settlement guarantee. |
171
+ | Wallets | `wallets.list` | `GET /v1/wallets` | Lists wallets available to the authenticated account and environment. Choose a wallet before reading its balance or entries. |
172
+ | Wallets | `wallets.retrieve` | `GET /v1/wallets/{id}` | Reads one wallet's details. Load the wallet metadata for an account view. |
173
+ | Wallets | `wallets.balance` | `GET /v1/wallets/{id}/balance` | Reads the wallet's current balance. Show the available or pending balance for a wallet. |
174
+ | Wallets | `wallets.listEntries` | `GET /v1/wallets/{id}/entries` | Lists ledger entries with cursor pagination. Show a transaction statement; pass the returned cursor for the next page. |
175
+ | Webhooks | `webhooks.listEndpoints` | `GET /v1/webhooks/endpoints` | Lists configured webhook destinations. Review which event destinations are active. |
176
+ | Webhooks | `webhooks.createEndpoint` | `POST /v1/webhooks/endpoints` | Registers an HTTPS receiver and selected event types. The signing secret is shown only at creation. Connect your server to receive payment lifecycle events; store the returned secret securely. |
177
+ | Webhooks | `webhooks.updateEndpoint` | `PATCH /v1/webhooks/endpoints/{id}` | Updates a destination's URL or subscribed event types. Change a receiver without creating a second endpoint. |
178
+ | Webhooks | `webhooks.disableEndpoint` | `POST /v1/webhooks/endpoints/{id}/disable` | Stops future deliveries to an endpoint while retaining its record. Temporarily stop a destination while investigating or migrating it. |
179
+ | Webhooks | `webhooks.deleteEndpoint` | `DELETE /v1/webhooks/endpoints/{id}` | Removes a webhook endpoint. Permanently remove a destination that is no longer used. |
180
+ | Webhooks | `webhooks.listDeliveries` | `GET /v1/webhooks/deliveries` | Lists delivery attempts and their summary states. Monitor failed, pending, or completed event deliveries. |
181
+ | Webhooks | `webhooks.retrieveDelivery` | `GET /v1/webhooks/deliveries/{id}` | Reads one delivery's status and attempt metadata. Inspect one delivery before deciding whether to retry it. |
182
+ | Webhooks | `webhooks.retryDelivery` | `POST /v1/webhooks/deliveries/{id}/retry` | Queues a retry for an eligible failed delivery. Retry after fixing the receiver; the endpoint must be active. |
183
+ | Public catalog and optional support chat | `public.listPaymentMethods` | `GET /v1/public/payment-methods` | Returns active payment methods and their public requirements without partner keys. Build a method selector and validate the selected method's required fields. |
184
+ | Browser checkout (JavaScript SDK) | `EDPay.checkout` | `Browser helper` | Chooses redirect, modal, or embedded checkout from the supplied mode and container options. Start checkout in the buyer's browser with a short-lived token created by your server; use a public key only. |
185
+ | Browser checkout (JavaScript SDK) | `EDPay.redirectToCheckout` | `Browser helper` | Navigates the browser to the hosted payment page. Use the simplest checkout integration when leaving your site is acceptable. |
186
+ | Browser checkout (JavaScript SDK) | `EDPay.openModal` | `Browser helper` | Opens checkout in a modal iframe and returns a close function. Keep the buyer on the current page while showing hosted checkout. |
187
+ | Browser checkout (JavaScript SDK) | `EDPay.mount` | `Browser helper` | Mounts checkout in a supplied element and returns an unmount function. Place checkout inline inside a page layout and clean it up when the component closes. |
188
+ | Contact helpers | `normalizePhoneNumber` | `Local helper` | Removes display punctuation and returns the phone value in the configured national or international form. Prepare a phone value before validating or sending it to a method that requires one. |
189
+ | Contact helpers | `formatPhoneNumber` | `Local helper` | Formats a valid phone number for display; it does not change the API payload automatically. Show a readable phone number in a form or confirmation screen. |
190
+ | Contact helpers | `addCountryPrefix` | `Local helper` | Adds the configured country calling code to a national number. An integration needs the international form, such as 258 plus national digits. |
191
+ | Contact helpers | `removeCountryPrefix` | `Local helper` | Removes the configured country calling code and returns national digits. A selected method expects the national number without a country code. |
192
+ | Contact helpers | `validatePhoneNumber` | `Local helper` | Checks length, allowed characters, country code, and configured prefixes; returns true or false. Reject invalid input before calling the API. It does not replace server-side validation. |
193
+ | Contact helpers | `phoneNumberOptionsForMethod` | `Local helper` | Returns known contact rules for the selected method, or null when no preset exists. Load rules before validating a phone; configure rules from the live catalog for other phone methods. |
194
+ | Webhook signature verification | `verifyWebhookSignature` | `Local helper` | Checks the Payment-Signature HMAC and timestamp against the unmodified request body. Verify the signature before parsing or acting on an incoming webhook. Use the raw bytes and keep the secret server-side. |
195
+ | Client utilities | `client.request` | `Raw API request` | Sends a request to an API path without a dedicated resource wrapper. The optional authenticated argument controls whether partner key headers are sent. Use only for a supported endpoint that has no SDK method; keep private keys on the server and apply the endpoint's scope and idempotency rules. |
196
+
197
+ Responses are parsed JSON objects. API errors throw `EDPayError` with `statusCode` and `responseData`. Browser checkout uses the separate `@edutecka-mz/edpay-sdk/frontend` entry point and must receive a short-lived token created by your server.
95
198
  ## Verify webhook signatures
96
199
 
97
- Use the raw request body and the `X-EDPay-Signature` header before parsing or processing an event. For example, in a Next.js route handler:
200
+ Use the raw request body and the `Payment-Signature` header before parsing or processing an event. EDPay signs `timestamp + "." + rawBody`; the verifier also enforces a five-minute timestamp window by default. For example, in a Next.js route handler:
98
201
 
99
202
  ```typescript
100
203
  import { verifyWebhookSignature } from "@edutecka-mz/edpay-sdk";
101
204
 
102
205
  export async function POST(request: Request) {
103
206
  const rawBody = await request.text();
104
- const signature = request.headers.get("x-edpay-signature") ?? "";
207
+ const signature = request.headers.get("payment-signature") ?? "";
105
208
  const secret = process.env.EDPAY_WEBHOOK_SECRET!;
106
209
 
107
210
  if (!verifyWebhookSignature(rawBody, signature, secret)) {
108
211
  return new Response("Invalid signature", { status: 400 });
109
212
  }
110
213
 
111
- const event = JSON.parse(rawBody);
214
+ const event = JSON.parse(rawBody) as import("@edutecka-mz/edpay-sdk").EDPayWebhookEvent;
112
215
  if (event.type === "payment.succeeded") {
113
- // Update the matching order idempotently using event.data.
216
+ const orderReference = event.data.reference;
217
+ // Match the order idempotently by its merchant reference.
114
218
  }
115
219
 
116
220
  return Response.json({ received: true });
117
221
  }
118
222
  ```
119
223
 
224
+ `EDPayWebhookEvent` and `EDPayWebhookPaymentData` describe the verified event envelope and sanitized payment fields. Match orders by `data.reference`; link-checkout details are not needed for correlation. Reconciliation status/code and fee/net breakdown fields are optional because they are not present in every event. The verifier returns a boolean, so parse/cast only after signature verification.
225
+
226
+ The public support-chat route streams server-sent events and is not exposed by this release's JSON request helpers.
227
+
120
228
  ## Official documentation
121
229
 
122
230
  - [SDK installation and integration guide](https://docs-pay.edutecka.com/sdks/)
package/dist/client.d.ts CHANGED
@@ -1,22 +1,26 @@
1
1
  import type { EDPayClientOptions } from "./types.js";
2
2
  import { PaymentsResource } from "./resources/payments.js";
3
- import { CheckoutResource } from "./resources/checkout.js";
4
- import { PaymentLinksResource } from "./resources/payment-links.js";
5
3
  import { CustomersResource } from "./resources/customers.js";
6
4
  import { InvoicesResource } from "./resources/invoices.js";
7
5
  import { SubscriptionsResource } from "./resources/subscriptions.js";
6
+ import { FxResource } from "./resources/fx.js";
7
+ import { WalletsResource } from "./resources/wallets.js";
8
+ import { WebhooksResource } from "./resources/webhooks.js";
9
+ import { PublicResource } from "./resources/public.js";
8
10
  export declare class EDPayClient {
9
11
  private readonly publicKey;
10
12
  private readonly privateKey;
11
13
  private readonly baseUrl;
12
14
  private readonly timeoutMs;
13
15
  readonly payments: PaymentsResource;
14
- readonly checkout: CheckoutResource;
15
- readonly paymentLinks: PaymentLinksResource;
16
16
  readonly customers: CustomersResource;
17
17
  readonly invoices: InvoicesResource;
18
18
  readonly subscriptions: SubscriptionsResource;
19
+ readonly fx: FxResource;
20
+ readonly wallets: WalletsResource;
21
+ readonly webhooks: WebhooksResource;
22
+ readonly public: PublicResource;
19
23
  constructor(options: EDPayClientOptions);
20
- request<T = any>(method: string, path: string, body?: unknown, customHeaders?: Record<string, string>): Promise<T>;
24
+ request<T = any>(method: string, path: string, body?: unknown, customHeaders?: Record<string, string>, authenticated?: boolean): Promise<T>;
21
25
  }
22
26
  //# sourceMappingURL=client.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"client.d.ts","sourceRoot":"","sources":["../src/client.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,YAAY,CAAC;AAErD,OAAO,EAAE,gBAAgB,EAAE,MAAM,yBAAyB,CAAC;AAC3D,OAAO,EAAE,gBAAgB,EAAE,MAAM,yBAAyB,CAAC;AAC3D,OAAO,EAAE,oBAAoB,EAAE,MAAM,8BAA8B,CAAC;AACpE,OAAO,EAAE,iBAAiB,EAAE,MAAM,0BAA0B,CAAC;AAC7D,OAAO,EAAE,gBAAgB,EAAE,MAAM,yBAAyB,CAAC;AAC3D,OAAO,EAAE,qBAAqB,EAAE,MAAM,8BAA8B,CAAC;AAErE,qBAAa,WAAW;IACtB,OAAO,CAAC,QAAQ,CAAC,SAAS,CAAS;IACnC,OAAO,CAAC,QAAQ,CAAC,UAAU,CAAS;IACpC,OAAO,CAAC,QAAQ,CAAC,OAAO,CAAS;IACjC,OAAO,CAAC,QAAQ,CAAC,SAAS,CAAS;IAEnC,SAAgB,QAAQ,EAAE,gBAAgB,CAAC;IAC3C,SAAgB,QAAQ,EAAE,gBAAgB,CAAC;IAC3C,SAAgB,YAAY,EAAE,oBAAoB,CAAC;IACnD,SAAgB,SAAS,EAAE,iBAAiB,CAAC;IAC7C,SAAgB,QAAQ,EAAE,gBAAgB,CAAC;IAC3C,SAAgB,aAAa,EAAE,qBAAqB,CAAC;gBAEzC,OAAO,EAAE,kBAAkB;IAwBjC,OAAO,CAAC,CAAC,GAAG,GAAG,EACnB,MAAM,EAAE,MAAM,EACd,I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B;IAiCjC,OAAO,CAAC,CAAC,GAAG,GAAG,EACnB,MAAM,EAAE,MAAM,EACd,IAAI,EAAE,MAAM,EACZ,IAAI,CAAC,EAAE,OAAO,EACd,aAAa,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,EACtC,aAAa,UAAO,GACnB,OAAO,CAAC,CAAC,CAAC;CAqDd"}
package/dist/client.js CHANGED
@@ -3,28 +3,39 @@ Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.EDPayClient = void 0;
4
4
  const exceptions_js_1 = require("./exceptions.js");
5
5
  const payments_js_1 = require("./resources/payments.js");
6
- const checkout_js_1 = require("./resources/checkout.js");
7
- const payment_links_js_1 = require("./resources/payment-links.js");
8
6
  const customers_js_1 = require("./resources/customers.js");
9
7
  const invoices_js_1 = require("./resources/invoices.js");
10
8
  const subscriptions_js_1 = require("./resources/subscriptions.js");
9
+ const fx_js_1 = require("./resources/fx.js");
10
+ const wallets_js_1 = require("./resources/wallets.js");
11
+ const webhooks_js_1 = require("./resources/webhooks.js");
12
+ const public_js_1 = require("./resources/public.js");
11
13
  class EDPayClient {
12
14
  publicKey;
13
15
  privateKey;
14
16
  baseUrl;
15
17
  timeoutMs;
16
18
  payments;
17
- checkout;
18
- paymentLinks;
19
19
  customers;
20
20
  invoices;
21
21
  subscriptions;
22
+ fx;
23
+ wallets;
24
+ webhooks;
25
+ public;
22
26
  constructor(options) {
23
- if (!options?.publicKey || !options?.privateKey) {
24
- throw new Error("EDPayClient requires both publicKey and privateKey.");
27
+ const publicKey = options?.publicKey?.trim();
28
+ const privateKey = options?.privateKey?.trim();
29
+ const publicMode = publicKey?.match(/^pk_(test|live)_[a-fA-F0-9]{24}$/)?.[1] ?? null;
30
+ const privateMode = privateKey?.match(/^sk_(test|live)_[a-fA-F0-9]{64}$/)?.[1] ?? null;
31
+ if (!publicMode || !privateMode) {
32
+ throw new Error("EDPayClient requires a valid publicKey (pk_test_/pk_live_ plus 24 hex characters) and privateKey (sk_test_/sk_live_ plus 64 hex characters).");
25
33
  }
26
- this.publicKey = options.publicKey;
27
- this.privateKey = options.privateKey;
34
+ if (publicMode !== privateMode) {
35
+ throw new Error("EDPay publicKey and privateKey must use the same environment (test or live).");
36
+ }
37
+ this.publicKey = publicKey;
38
+ this.privateKey = privateKey;
28
39
  this.timeoutMs = options.timeoutMs ?? 30000;
29
40
  if (options.baseUrl) {
30
41
  this.baseUrl = options.baseUrl.replace(/\/+$/, "");
@@ -34,22 +45,26 @@ class EDPayClient {
34
45
  options.baseUrl || "https://api-pay.edutecka.com";
35
46
  }
36
47
  this.payments = new payments_js_1.PaymentsResource(this);
37
- this.checkout = new checkout_js_1.CheckoutResource(this);
38
- this.paymentLinks = new payment_links_js_1.PaymentLinksResource(this);
39
48
  this.customers = new customers_js_1.CustomersResource(this);
40
49
  this.invoices = new invoices_js_1.InvoicesResource(this);
41
50
  this.subscriptions = new subscriptions_js_1.SubscriptionsResource(this);
51
+ this.fx = new fx_js_1.FxResource(this);
52
+ this.wallets = new wallets_js_1.WalletsResource(this);
53
+ this.webhooks = new webhooks_js_1.WebhooksResource(this);
54
+ this.public = new public_js_1.PublicResource(this);
42
55
  }
43
- async request(method, path, body, customHeaders) {
56
+ async request(method, path, body, customHeaders, authenticated = true) {
44
57
  const url = `${this.baseUrl}${path}`;
45
58
  const headers = {
46
- "X-EDPay-Public-Key": this.publicKey,
47
- "X-EDPay-Private-Key": this.privateKey,
48
59
  "Content-Type": "application/json",
49
60
  Accept: "application/json",
50
- "User-Agent": "EDPay-Node-SDK/1.0.0",
61
+ "User-Agent": "EDPay-Node-SDK/1.6.0",
51
62
  ...customHeaders,
52
63
  };
64
+ if (authenticated) {
65
+ headers["X-EDPay-Public-Key"] = this.publicKey;
66
+ headers["X-EDPay-Private-Key"] = this.privateKey;
67
+ }
53
68
  const controller = new AbortController();
54
69
  const timer = setTimeout(() => controller.abort(), this.timeoutMs);
55
70
  try {
@@ -71,8 +86,13 @@ class EDPayClient {
71
86
  }
72
87
  }
73
88
  if (!response.ok) {
74
- const errorMsg = data?.message || data?.error || `HTTP ${response.status} ${response.statusText}`;
75
- throw new exceptions_js_1.EDPayError(errorMsg, response.status, data);
89
+ const apiError = data?.error;
90
+ const errorMsg = apiError?.message || data?.message || (typeof apiError === "string" ? apiError : undefined) || `HTTP ${response.status} ${response.statusText}`;
91
+ throw new exceptions_js_1.EDPayError(errorMsg, response.status, data, {
92
+ errorCode: apiError?.code,
93
+ requestId: response.headers.get("X-Request-Id") ?? undefined,
94
+ retryAfter: response.headers.get("Retry-After") ?? undefined,
95
+ });
76
96
  }
77
97
  return data;
78
98
  }
@@ -1 +1 @@
1
- {"version":3,"file":"client.js","sourceRoot":"","sources":["../src/client.ts"],"names":[],"mappings":";;;AACA,mDAA6C;AAC7C,yDAA2D;AAC3D,yDAA2D;AAC3D,mEAAoE;AACpE,2DAA6D;AAC7D,yDAA2D;AAC3D,mEAAqE;AAErE,MAAa,WAAW;IACL,SAAS,CAAS;IAClB,UAAU,CAAS;IACnB,OAAO,CAAS;IAChB,SAAS,CAAS;IAEnB,QAAQ,CAAmB;IAC3B,QAAQ,CAAmB;IAC3B,YAAY,CAAuB;IACnC,SAAS,CAAoB;IAC7B,QAAQ,CAAmB;IAC3B,aAAa,CAAwB;IAErD,YAAY,OAA2B;QACrC,IAAI,CAAC,OAAO,EAAE,SAAS,IAAI,CAAC,OAAO,EAAE,UAAU,EAAE,CAAC;YAChD,MAAM,IAAI,KAAK,CAAC,qDAAqD,CAAC,CAAC;QACzE,CAAC;QAED,IAAI,CAAC,SAAS,GAAG,OAAO,CAAC,SAAS,CAAC;QACnC,IAAI,CAAC,UAAU,GAAG,OAAO,CAAC,UAAU,CAAC;QACrC,IAAI,CAAC,SAAS,GAAG,OAAO,CAAC,SAAS,IAAI,KAAK,CAAC;QAE5C,IAAI,OAAO,CAAC,OAAO,EAAE,CAAC;YACpB,IAAI,CAAC,OAAO,GAAG,OAAO,CAAC,OAAO,CAAC,OAAO,CAAC,M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BAC7D,CAAC,CAAC;YACL,CAAC;YAED,OAAO,IAAS,CAAC;QACnB,CAAC;QAAC,OAAO,GAAQ,EAAE,CAAC;YAClB,YAAY,CAAC,KAAK,CAAC,CAAC;YACpB,IAAI,GAAG,YAAY,0BAAU;gBAAE,MAAM,GAAG,CAAC;YACzC,MAAM,IAAI,0BAAU,CAAC,GAAG,CAAC,OAAO,IAAI,wBAAwB,EAAE,CAAC,CAAC,CAAC;QACnE,CAAC;IACH,CAAC;CACF;AA3GD,kCA2GC"}
@@ -0,0 +1,32 @@
1
+ /** Phone number formats accepted by the SDK's contact helpers. */
2
+ export type PhoneNumberOutput = "international" | "country-code" | "national";
3
+ /** Rules for validating and formatting a phone number for a country or API method. */
4
+ export interface PhoneNumberOptions {
5
+ /** Country calling code without `+`. Defaults to Mozambique (`258`). */
6
+ countryCallingCode?: string;
7
+ /** Required number of national digits. Defaults to 9 for Mozambique. */
8
+ nationalLength?: number;
9
+ /** Optional national prefixes required by the selected payment method. */
10
+ nationalPrefixes?: readonly string[];
11
+ /** Request representation. Defaults to E.164-style `+<country><national>`. */
12
+ output?: PhoneNumberOutput;
13
+ /** Display grouping from left to right. Defaults to `[2, 3, 4]` for Mozambique. */
14
+ groupSizes?: readonly number[];
15
+ }
16
+ /**
17
+ * Normalize a phone number to the configured request format. The default is
18
+ * `+258` plus nine national digits. Method presets are available for phone
19
+ * methods; unknown methods return no preset and should use account metadata.
20
+ */
21
+ export declare function normalizePhoneNumber(value: string, options?: PhoneNumberOptions): string;
22
+ /** Return known phone rules for a method; null means the method is non-phone or unknown. */
23
+ export declare function phoneNumberOptionsForMethod(method: string): PhoneNumberOptions | null;
24
+ /** Format a validated phone number for display, using spaces between groups. */
25
+ export declare function formatPhoneNumber(value: string, options?: PhoneNumberOptions): string;
26
+ /** Add the configured country calling code and return an E.164-style value. */
27
+ export declare function addCountryPrefix(value: string, options?: PhoneNumberOptions): string;
28
+ /** Remove the configured country calling code and return national digits. */
29
+ export declare function removeCountryPrefix(value: string, options?: PhoneNumberOptions): string;
30
+ /** Return whether the number matches the configured country, length, and prefixes. */
31
+ export declare function validatePhoneNumber(value: string, options?: PhoneNumberOptions): boolean;
32
+ //# sourceMappingURL=contacts.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"contacts.d.ts","sourceRoot":"","sources":["../src/contacts.ts"],"names":[],"mappings":"AAAA,kEAAkE;AAClE,MAAM,MAAM,iBAAiB,GAAG,eAAe,GAAG,cAAc,GAAG,UAAU,CAAC;AAE9E,sFAAsF;AACtF,MAAM,WAAW,kBAAkB;IACjC,wEAAwE;IACxE,kBAAkB,CAAC,EAAE,MAAM,CAAC;IAC5B,wEAAwE;IACxE,cAAc,CAAC,EAAE,MAAM,CAAC;IACxB,0EAA0E;IAC1E,gBAAgB,CAAC,EAAE,SAAS,MAAM,EAAE,CAAC;IACrC,8EAA8E;IAC9E,MAAM,CAAC,EAAE,iBAAiB,CAAC;IAC3B,mFAAmF;IACnF,UAAU,CAAC,EAAE,SAAS,MAAM,EAAE,CAAC;CAChC;AAwED;;;;GAIG;AACH,wBAAgB,oBAAoB,CAAC,KAAK,EAAE,MAAM,EAAE,OAAO,GAAE,kBAAuB,GAAG,MAAM,CAM5F;AAED,4FAA4F;AAC5F,wBAAgB,2BAA2B,CAAC,MAAM,EAAE,MAAM,GAAG,kBAAkB,GAAG,IAAI,CAKrF;AAED,gFAAgF;AAChF,wBAAgB,iBAAiB,CAAC,KAAK,EAAE,MAAM,EAAE,OAAO,GAAE,kBAAuB,GAAG,MAAM,CAkBzF;AAED,+EAA+E;AAC/E,wBAAgB,gBAAgB,CAAC,KAAK,EAAE,MAAM,EAAE,OAAO,GAAE,kBAAuB,GAAG,MAAM,CAExF;AAED,6EAA6E;AAC7E,wBAAgB,mBAAmB,CAAC,KAAK,EAAE,MAAM,EAAE,OAAO,GAAE,kBAAuB,GAAG,MAAM,CAE3F;AAED,sFAAsF;AACtF,wBAAgB,mBAAmB,CAAC,KAAK,EAAE,MAAM,EAAE,OAAO,GAAE,kBAAuB,GAAG,OAAO,CAO5F"}
@@ -0,0 +1,129 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.normalizePhoneNumber = normalizePhoneNumber;
4
+ exports.phoneNumberOptionsForMethod = phoneNumberOptionsForMethod;
5
+ exports.formatPhoneNumber = formatPhoneNumber;
6
+ exports.addCountryPrefix = addCountryPrefix;
7
+ exports.removeCountryPrefix = removeCountryPrefix;
8
+ exports.validatePhoneNumber = validatePhoneNumber;
9
+ function normalizeOptions(options = {}) {
10
+ const countryCallingCode = (options.countryCallingCode ?? "258").replace(/^\+/, "");
11
+ const nationalLength = options.nationalLength ?? 9;
12
+ const output = options.output ?? "international";
13
+ if (!/^[1-9]\d{0,2}$/.test(countryCallingCode)) {
14
+ throw new TypeError("countryCallingCode must contain 1 to 3 digits and cannot start with 0.");
15
+ }
16
+ if (!Number.isInteger(nationalLength) || nationalLength < 1 || nationalLength + countryCallingCode.length > 15) {
17
+ throw new TypeError("nationalLength must fit within the E.164 limit of 15 digits.");
18
+ }
19
+ if (output !== "international" && output !== "country-code" && output !== "national") {
20
+ throw new TypeError("output must be 'international', 'country-code', or 'national'.");
21
+ }
22
+ if (options.nationalPrefixes?.some((prefix) => !/^\d+$/.test(prefix))) {
23
+ throw new TypeError("nationalPrefixes must contain digits only.");
24
+ }
25
+ if (options.groupSizes?.some((size) => !Number.isInteger(size) || size < 1)) {
26
+ throw new TypeError("groupSizes must contain positive integers.");
27
+ }
28
+ return { ...options, countryCallingCode, nationalLength, output };
29
+ }
30
+ function parsePhoneNumber(value, options = {}) {
31
+ const config = normalizeOptions(options);
32
+ if (typeof value !== "string") {
33
+ throw new TypeError("Phone number must be a string.");
34
+ }
35
+ const input = value.trim();
36
+ if (!input || !/^\+?[\d\s().-]+$/.test(input)) {
37
+ throw new TypeError("Phone number contains unsupported characters.");
38
+ }
39
+ if ((input.match(/\(/g)?.length ?? 0) !== (input.match(/\)/g)?.length ?? 0)) {
40
+ throw new TypeError("Phone number has unbalanced parentheses.");
41
+ }
42
+ const markedInternational = input.startsWith("+");
43
+ let digits = input.replace(/\D/g, "");
44
+ const hasInternational00Prefix = digits.startsWith("00");
45
+ if (hasInternational00Prefix)
46
+ digits = digits.slice(2);
47
+ const isInternational = markedInternational || hasInternational00Prefix ||
48
+ (digits.startsWith(config.countryCallingCode) && digits.length > config.nationalLength);
49
+ let nationalNumber;
50
+ if (isInternational) {
51
+ if (!digits.startsWith(config.countryCallingCode)) {
52
+ throw new TypeError("Phone number does not use the configured country calling code.");
53
+ }
54
+ nationalNumber = digits.slice(config.countryCallingCode.length);
55
+ }
56
+ else {
57
+ nationalNumber = digits;
58
+ }
59
+ if (nationalNumber.length !== config.nationalLength || !/^\d+$/.test(nationalNumber)) {
60
+ throw new TypeError("Phone number does not match the configured national length.");
61
+ }
62
+ if (config.nationalPrefixes?.length && !config.nationalPrefixes.some((prefix) => nationalNumber.startsWith(prefix))) {
63
+ throw new TypeError("Phone number does not match the configured national prefixes.");
64
+ }
65
+ return { countryCallingCode: config.countryCallingCode, nationalNumber };
66
+ }
67
+ /**
68
+ * Normalize a phone number to the configured request format. The default is
69
+ * `+258` plus nine national digits. Method presets are available for phone
70
+ * methods; unknown methods return no preset and should use account metadata.
71
+ */
72
+ function normalizePhoneNumber(value, options = {}) {
73
+ const config = normalizeOptions(options);
74
+ const parsed = parsePhoneNumber(value, config);
75
+ if (config.output === "national")
76
+ return parsed.nationalNumber;
77
+ if (config.output === "country-code")
78
+ return `${parsed.countryCallingCode}${parsed.nationalNumber}`;
79
+ return `+${parsed.countryCallingCode}${parsed.nationalNumber}`;
80
+ }
81
+ /** Return known phone rules for a method; null means the method is non-phone or unknown. */
82
+ function phoneNumberOptionsForMethod(method) {
83
+ const key = method.trim().toLowerCase().replace(/[ _-]/g, "");
84
+ if (key === "emola")
85
+ return { countryCallingCode: "258", nationalLength: 9, nationalPrefixes: ["86", "87"], output: "national" };
86
+ if (key === "mpesa")
87
+ return { countryCallingCode: "258", nationalLength: 9, nationalPrefixes: ["84", "85"], output: "country-code" };
88
+ return null;
89
+ }
90
+ /** Format a validated phone number for display, using spaces between groups. */
91
+ function formatPhoneNumber(value, options = {}) {
92
+ const parsed = parsePhoneNumber(value, options);
93
+ const config = normalizeOptions(options);
94
+ const defaultGroups = parsed.countryCallingCode === "258" && parsed.nationalNumber.length === 9
95
+ ? [2, 3, 4]
96
+ : [parsed.nationalNumber.length];
97
+ const groups = config.groupSizes ?? defaultGroups;
98
+ const formattedGroups = [];
99
+ let offset = 0;
100
+ for (const size of groups) {
101
+ if (offset >= parsed.nationalNumber.length)
102
+ break;
103
+ formattedGroups.push(parsed.nationalNumber.slice(offset, offset + size));
104
+ offset += size;
105
+ }
106
+ if (offset < parsed.nationalNumber.length) {
107
+ formattedGroups.push(parsed.nationalNumber.slice(offset));
108
+ }
109
+ return `+${parsed.countryCallingCode} ${formattedGroups.join(" ")}`;
110
+ }
111
+ /** Add the configured country calling code and return an E.164-style value. */
112
+ function addCountryPrefix(value, options = {}) {
113
+ return normalizePhoneNumber(value, { ...options, output: "international" });
114
+ }
115
+ /** Remove the configured country calling code and return national digits. */
116
+ function removeCountryPrefix(value, options = {}) {
117
+ return normalizePhoneNumber(value, { ...options, output: "national" });
118
+ }
119
+ /** Return whether the number matches the configured country, length, and prefixes. */
120
+ function validatePhoneNumber(value, options = {}) {
121
+ try {
122
+ parsePhoneNumber(value, options);
123
+ return true;
124
+ }
125
+ catch {
126
+ return false;
127
+ }
128
+ }
129
+ //# sourceMappingURL=contacts.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"contacts.js","sourceRoot":"","sources":["../src/contacts.ts"],"names":[],"mappings":";;AA4FA,oDAMC;AAGD,kEAKC;AAGD,8CAkBC;AAGD,4CAEC;AAGD,kDAEC;AAGD,kDAOC;AA7HD,SAAS,gBAAgB,CAAC,UAA8B,EAAE;IACxD,MAAM,kBAAkB,GAAG,CAAC,OAAO,CAAC,kBAAkB,IAAI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CAAC,KAAK,CAAC,MAAM,EAAE,MAAM,GAAG,IAAI,CAAC,CAAC,CAAC;QACzE,MAAM,IAAI,IAAI,CAAC;IACjB,CAAC;IACD,IAAI,MAAM,GAAG,MAAM,CAAC,cAAc,CAAC,MAAM,EAAE,CAAC;QAC1C,eAAe,CAAC,IAAI,CAAC,MAAM,CAAC,cAAc,CAAC,KAAK,CAAC,MAAM,CAAC,CAAC,CAAC;IAC5D,CAAC;IACD,OAAO,IAAI,MAAM,CAAC,kBAAkB,IAAI,eAAe,CAAC,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC;AACtE,CAAC;AAED,+EAA+E;AAC/E,SAAgB,gBAAgB,CAAC,KAAa,EAAE,UAA8B,EAAE;IAC9E,OAAO,oBAAoB,CAAC,KAAK,EAAE,EAAE,GAAG,OAAO,EAAE,MAAM,EAAE,eAAe,EAAE,CAAC,CAAC;AAC9E,CAAC;AAED,6EAA6E;AAC7E,SAAgB,mBAAmB,CAAC,KAAa,EAAE,UAA8B,EAAE;IACjF,OAAO,oBAAoB,CAAC,KAAK,EAAE,EAAE,GAAG,OAAO,EAAE,MAAM,EAAE,UAAU,EAAE,CAAC,CAAC;AACzE,CAAC;AAED,sFAAsF;AACtF,SAAgB,mBAAmB,CAAC,KAAa,EAAE,UAA8B,EAAE;IACjF,IAAI,CAAC;QACH,gBAAgB,CAAC,KAAK,EAAE,OAAO,CAAC,CAAC;QACjC,OAAO,IAAI,CAAC;IACd,CAAC;IAAC,MAAM,CAAC;QACP,OAAO,KAAK,CAAC;IACf,CAAC;AACH,CAAC"}
package/dist/edpay.js CHANGED
@@ -62,12 +62,13 @@
62
62
  var closeBtn = document.createElement('button');
63
63
  closeBtn.type = 'button';
64
64
  closeBtn.innerHTML = '&times;';
65
- closeBtn.setAttribute('aria-label', 'Fechar');
65
+ closeBtn.setAttribute('aria-label', 'Close');
66
66
  closeBtn.style.cssText = 'position:absolute;top:12px;right:12px;width:32px;height:32px;border:none;border-radius:50%;background:rgba(0,0,0,0.08);color:#333;font-size:22px;line-height:1;cursor:pointer;z-index:10;display:flex;align-items:center;justify-content:center;';
67
67
 
68
68
  // Iframe
69
69
  var iframe = document.createElement('iframe');
70
70
  iframe.src = checkoutUrl;
71
+ var checkoutOrigin = new URL(iframe.src).origin;
71
72
  iframe.style.cssText = 'width:100%;height:100%;border:none;';
72
73
  iframe.allow = 'payment';
73
74
 
@@ -105,6 +106,7 @@
105
106
  });
106
107
 
107
108
  function handleMessage(event) {
109
+ if (event.origin !== checkoutOrigin || event.source !== iframe.contentWindow) return;
108
110
  if (!event.data || typeof event.data !== 'object') return;
109
111
  var type = event.data.type;
110
112
  var payload = event.data.payload;
@@ -143,6 +145,7 @@
143
145
  var checkoutUrl = this.resolveUrl(options);
144
146
  var iframe = document.createElement('iframe');
145
147
  iframe.src = checkoutUrl;
148
+ var checkoutOrigin = new URL(iframe.src).origin;
146
149
  iframe.style.cssText = 'width:' + (options.width || '100%') + ';height:' + (options.height || '620px') + ';border:none;border-radius:16px;';
147
150
  iframe.allow = 'payment';
148
151
 
@@ -150,6 +153,7 @@
150
153
  target.appendChild(iframe);
151
154
 
152
155
  function handleMessage(event) {
156
+ if (event.origin !== checkoutOrigin || event.source !== iframe.contentWindow) return;
153
157
  if (!event.data || typeof event.data !== 'object') return;
154
158
  var type = event.data.type;
155
159
  var payload = event.data.payload;