@cosmosapp/pay_sdk 1.1.0 → 1.2.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.
package/dist/web/index.js CHANGED
@@ -1,5 +1,5 @@
1
- import { version, CosmosPayAPIError, CosmosPayRequestError, DEFAULT_BASE_URL, resolveIntentBody } from '../chunk-RCLT7E4Y.js';
2
- export { AddressBook, Assets, CosmosPayAPIError, CosmosPayRequestError, TestnetAssets, Wallets, addresses, assertAddress, defineAsset, isAddress, isContractAddress, isMuxedAddress, isNativeAsset, isStellarAddress, resolveAddress, resolveAsset, resolveIntentBody } from '../chunk-RCLT7E4Y.js';
1
+ import { version, CosmosPayAPIError, CosmosPayRequestError, DEFAULT_BASE_URL, resolveIntentBody } from '../chunk-TZDZBVFS.js';
2
+ export { AddressBook, Assets, CosmosPayAPIError, CosmosPayRequestError, TestnetAssets, Wallets, addresses, assertAddress, defineAsset, isAddress, isContractAddress, isMuxedAddress, isNativeAsset, isStellarAddress, resolveAddress, resolveAsset, resolveIntentBody } from '../chunk-TZDZBVFS.js';
3
3
 
4
4
  // src/web/errors.ts
5
5
  var CosmosPayWebError = class _CosmosPayWebError extends Error {
@@ -0,0 +1,43 @@
1
+ # Overview
2
+
3
+ `@cosmosapp/pay_sdk` is the object-oriented JavaScript/TypeScript SDK for the
4
+ **Cosmos Pay** Payments API — Stellar **SEP-7 payment intents**, **webhooks**,
5
+ **products**, **customers** and **analytics**.
6
+
7
+ ## Two entry points
8
+
9
+ | Import | Runs in | Purpose |
10
+ | ------ | ------- | ------- |
11
+ | `@cosmosapp/pay_sdk` | server (Node ≥ 18) | Create & manage intents, webhooks, products, customers, analytics — anything that needs your secret API key. |
12
+ | `@cosmosapp/pay_sdk/web` | browser | *Complete* an intent: auto-detect the user's Stellar wallet (Freighter, xBull, Rabet, LOBSTR, Albedo), build the transaction, sign and submit. Provider-agnostic. |
13
+
14
+ ## Mental model
15
+
16
+ A payment has two halves:
17
+
18
+ 1. **Server** creates an intent with your secret key (`client.paymentIntents.createPay`/`createTx`)
19
+ and returns the payload (`uri`, `qr`, and for `tx` intents an unsigned `xdr`) to your frontend.
20
+ 2. **Browser** completes it with the user's wallet (`new WebClient().pay(intent)`),
21
+ producing an on-chain `txHash`.
22
+ 3. **Server** finalizes by validating that hash (`intent.validate(txHash)`), which
23
+ updates the status and fires a webhook.
24
+
25
+ ## Design
26
+
27
+ - **Atomic** — one `Client`; one manager per resource (`client.paymentIntents`,
28
+ `client.webhooks`, `client.products`, `client.customers`, `client.analytics`,
29
+ `client.health`).
30
+ - **Self-acting structures** — returned objects act on themselves:
31
+ `intent.validate()`, `endpoint.rotateSecret()`, `product.deactivate()`.
32
+ - **Zero runtime dependencies** — native `fetch` + `node:crypto`. The Stellar SDK
33
+ is an *optional* peer dep, only needed by the browser web client.
34
+ - **Fully typed** — works in both CJS and ESM.
35
+
36
+ ## Key facts for correct integration
37
+
38
+ - The **network is chosen by the API key type**: `dv_` → testnet, `prod_` → mainnet.
39
+ You never pass a network on the server.
40
+ - **Amounts are decimal strings** (e.g. `'10'`, `'120.1234567'`), max 7 decimals.
41
+ - The **webhook secret (`whsec_…`) is shown only once** on `create`/`rotateSecret`.
42
+ - The **gateway URL is pre-configured**; a normal integration only sets `apiKey`.
43
+ - Default gateway: `https://api.cosmospay.lat/cosmos-api`. Requires Node ≥ 18.
@@ -0,0 +1,35 @@
1
+ # Installation
2
+
3
+ ```bash
4
+ npm install @cosmosapp/pay_sdk
5
+ # or: pnpm add @cosmosapp/pay_sdk
6
+ # or: yarn add @cosmosapp/pay_sdk
7
+ ```
8
+
9
+ Requires **Node.js ≥ 18** (for global `fetch`). On older runtimes pass a `fetch`
10
+ polyfill via the `fetch` client option.
11
+
12
+ ## Browser web client (optional peer dependency)
13
+
14
+ The browser web client builds & submits Stellar transactions, so it needs the
15
+ Stellar SDK (an optional peer dependency, lazy-imported when present):
16
+
17
+ ```bash
18
+ npm install @cosmosapp/pay_sdk @stellar/stellar-sdk
19
+ ```
20
+
21
+ ## Importing
22
+
23
+ ```ts
24
+ // ESM
25
+ import { Client } from '@cosmosapp/pay_sdk';
26
+ import { WebClient } from '@cosmosapp/pay_sdk/web';
27
+ ```
28
+
29
+ ```js
30
+ // CommonJS
31
+ const { Client } = require('@cosmosapp/pay_sdk');
32
+ ```
33
+
34
+ The package ships both ESM (`./dist/index.js`) and CJS (`./dist/index.cjs`) with
35
+ full type declarations.
@@ -0,0 +1,48 @@
1
+ # Authentication
2
+
3
+ **You only need your API key.** Everything else (gateway URL, API version) is
4
+ part of the SDK's shared configuration, maintained by Cosmos Pay.
5
+
6
+ ```ts
7
+ import { Client } from '@cosmosapp/pay_sdk';
8
+
9
+ const client = new Client({ apiKey: process.env.COSMOS_PAY_API_KEY });
10
+ ```
11
+
12
+ The API key is sent as `Authorization: Bearer <apiKey>`.
13
+
14
+ ## Network selection (important)
15
+
16
+ The **network is determined by the key type** — you do NOT configure it:
17
+
18
+ | Key prefix | Network |
19
+ | ---------- | ------- |
20
+ | `dv_…` | testnet |
21
+ | `prod_…` | mainnet |
22
+
23
+ Because of this, asset issuers are network-specific: use `Assets.*` for mainnet
24
+ and `TestnetAssets.*` for testnet (see assets docs).
25
+
26
+ ## Keep the key on the server
27
+
28
+ The API key is a secret. Create and validate intents on your **server**. The
29
+ browser web client only signs/submits; it does not need the key. (It *can* take
30
+ an `apiKey` for trusted prototypes, but never ship a production key to the browser.)
31
+
32
+ ## Shared / self-hosting overrides (advanced)
33
+
34
+ ```ts
35
+ // Change the gateway for every client created afterward (once, at startup):
36
+ Client.shared.baseURL = 'https://gateway.your-domain.com';
37
+
38
+ // Or per-client (rarely needed) — e.g. local dev bypassing the gateway:
39
+ const client = new Client({
40
+ apiKey: '...',
41
+ baseURL: 'http://localhost:3000',
42
+ gatewaySecret: process.env.APISIX_GATEWAY_SECRET,
43
+ consumerUsername: 'cosmos_demo',
44
+ });
45
+ ```
46
+
47
+ `baseURL`, `version`, `gatewaySecret`, `consumerUsername` are all optional — a
48
+ normal integration never sets them.
@@ -0,0 +1,57 @@
1
+ # Quickstart
2
+
3
+ ```ts
4
+ import { Client, Assets } from '@cosmosapp/pay_sdk';
5
+
6
+ const client = new Client({ apiKey: process.env.COSMOS_PAY_API_KEY });
7
+
8
+ // 1. Create a SEP-7 `pay` intent (no source → pay URI + QR).
9
+ const intent = await client.paymentIntents.createPay({
10
+ destination: 'GCALNQQBXAPZ2WIRSDDBMSTAKCUH5SG6U76YBFLQLIXJTF7FE5AX7AOO',
11
+ amount: '120.1234567',
12
+ asset: Assets.USDC, // fills the verified mainnet issuer for you
13
+ msg: 'Order #24',
14
+ });
15
+
16
+ console.log(intent.uri); // web+stellar:pay?destination=...
17
+ console.log(intent.qr); // data:image/png;base64,... (render this)
18
+
19
+ // 2. After the payer submits a transaction, validate it.
20
+ const outcome = await intent.validate('<txHash>');
21
+ if (outcome.valid) console.log('Settled!', outcome.status);
22
+ ```
23
+
24
+ ## Full split (server creates, browser completes)
25
+
26
+ ```ts
27
+ // ── server.ts ──────────────────────────────────────────────────────
28
+ import { Client, Assets } from '@cosmosapp/pay_sdk';
29
+ const client = new Client({ apiKey: process.env.COSMOS_PAY_API_KEY });
30
+
31
+ export async function createIntent() {
32
+ const intent = await client.paymentIntents.createPay({
33
+ destination: 'G...MERCHANT',
34
+ amount: '10',
35
+ asset: Assets.USDC,
36
+ });
37
+ return intent.toJSON(); // send this payload to the browser
38
+ }
39
+
40
+ export function confirm(intentId: string, txHash: string) {
41
+ return client.paymentIntents.validate(intentId, { txHash });
42
+ }
43
+ ```
44
+
45
+ ```ts
46
+ // ── browser.ts ─────────────────────────────────────────────────────
47
+ import { WebClient } from '@cosmosapp/pay_sdk/web';
48
+
49
+ const intent = await fetch('/api/create-intent', { method: 'POST' }).then((r) => r.json());
50
+ const { txHash, account, wallet } = await new WebClient().pay(intent);
51
+
52
+ await fetch('/api/confirm', {
53
+ method: 'POST',
54
+ headers: { 'Content-Type': 'application/json' },
55
+ body: JSON.stringify({ intentId: intent.id, txHash }),
56
+ });
57
+ ```
@@ -0,0 +1,54 @@
1
+ # The Client
2
+
3
+ ```ts
4
+ import { Client } from '@cosmosapp/pay_sdk';
5
+ const client = new Client({ apiKey: process.env.COSMOS_PAY_API_KEY });
6
+ ```
7
+
8
+ One client exposes every resource through its own manager.
9
+
10
+ | Manager | Resource | Key methods |
11
+ | ------- | -------- | ----------- |
12
+ | `client.paymentIntents` | Stellar SEP-7 intents | `createTx` · `createPay` · `fetch` · `list` · `update` · `delete` · `validate` |
13
+ | `client.webhooks` | Endpoints + deliveries + event listener | `create` · `list` · `fetch` · `update` · `delete` · `rotateSecret` · `ping` · `fetchDeliveries` · `redeliver` · `on(...)` · `process` · `createHandler` · `middleware` |
14
+ | `client.products` | Products / prices | `create` · `list` · `fetch` · `update` · `delete` |
15
+ | `client.customers` | Customers | `create` · `list` · `fetch` · `update` · `delete` |
16
+ | `client.analytics` | Read-only metrics | `summary` · `balances` · `apiLogs` · `webhookLogs` |
17
+ | `client.health` | Liveness / readiness | `liveness` · `readiness` |
18
+
19
+ ## Constructor options
20
+
21
+ ```ts
22
+ new Client({
23
+ apiKey: 'prod_xxx', // required — the only thing you normally set
24
+ webhookSecret: 'whsec_...', // default secret for the webhook listener
25
+ timeout: 30_000, // ms (default 30000)
26
+ retries: 2, // network errors / 429 / 5xx (default 2)
27
+ headers: { 'X-Trace': 'abc' },
28
+ fetch: customFetch, // custom fetch implementation
29
+
30
+ // Advanced / internal (pre-filled from Client.shared, rarely set):
31
+ baseURL: 'https://api.cosmospay.lat/cosmos-api',
32
+ version: 'v1',
33
+ gatewaySecret: '...',
34
+ consumerUsername: '...',
35
+ });
36
+ ```
37
+
38
+ ## Statics & mutators
39
+
40
+ ```ts
41
+ Client.version; // library version string
42
+ Client.shared.baseURL = 'https://...'; // process-wide default for all clients
43
+
44
+ client.setApiKey('prod_rotated');
45
+ client.setWebhookSecret('whsec_new');
46
+ client.setGatewayCredentials(secret, consumerUsername); // local-dev direct access
47
+ ```
48
+
49
+ ## Returned objects are "structures"
50
+
51
+ Manager methods return rich instances (`PaymentIntent`, `WebhookEndpoint`,
52
+ `Product`, `Customer`) that can act on themselves and expose typed accessors —
53
+ e.g. `intent.isPay`, `intent.assetLabel`, `await intent.validate(txHash)`,
54
+ `await endpoint.disable()`. Call `.toJSON()` for the raw payload.
@@ -0,0 +1,79 @@
1
+ # Payment intents
2
+
3
+ `client.paymentIntents` — Stellar SEP-7 intents. Two kinds:
4
+
5
+ - **`pay` intent** — no source. The payer's wallet picks the source account.
6
+ Produces a `web+stellar:pay?...` URI + QR (no XDR).
7
+ - **`tx` intent** — source known. Produces an unsigned XDR + `web+stellar:tx?...`
8
+ URI + QR.
9
+
10
+ ## Create
11
+
12
+ ```ts
13
+ import { Assets } from '@cosmosapp/pay_sdk';
14
+
15
+ // pay (no source)
16
+ const pay = await client.paymentIntents.createPay({
17
+ destination: 'G...', // required — payee (or an address-book name)
18
+ amount: '10', // optional — omit for an open amount (donations)
19
+ asset: Assets.USDC, // typed asset → fills assetCode + verified issuer
20
+ // assetCode: 'USDC', assetIssuer: 'G...', // …or set them explicitly
21
+ // omit asset entirely for native lumens (XLM)
22
+ memo: '123456789', // optional MEMO_ID (uint64) — auto-generated if omitted
23
+ msg: 'Order #24', // optional, ≤ 300 chars, shown in the wallet
24
+ callback: 'url:https://...', // optional SEP-7 callback for the signed XDR
25
+ });
26
+
27
+ // tx (source known)
28
+ const tx = await client.paymentIntents.createTx({
29
+ source: 'G...PAYER', // required (extra vs pay)
30
+ destination: 'G...MERCHANT',
31
+ amount: '25.5',
32
+ });
33
+ console.log(tx.xdr, tx.uri, tx.qr);
34
+ ```
35
+
36
+ > Amounts are **decimal strings**, max 7 decimals. Asset issuers are
37
+ > network-specific (mainnet vs testnet).
38
+
39
+ ## Fetch / list
40
+
41
+ ```ts
42
+ const intent = await client.paymentIntents.fetch('pi_123');
43
+
44
+ const page = await client.paymentIntents.list({
45
+ status: 'SUCCEEDED', // optional filter (PaymentIntentStatus)
46
+ take: 50, // page size, max 100, default 20
47
+ skip: 0, // offset
48
+ });
49
+ // page → { items: PaymentIntent[], total, take, skip }
50
+ ```
51
+
52
+ ## Update / cancel / delete
53
+
54
+ ```ts
55
+ await intent.edit({ reference: 'order_1234' }); // status / txHash / reference
56
+ await intent.cancel(); // → status CANCELLED
57
+ await intent.delete();
58
+ // manager forms: client.paymentIntents.update(id, {...}) / .delete(id)
59
+ ```
60
+
61
+ ## Validate (finalize)
62
+
63
+ ```ts
64
+ const outcome = await intent.validate('<txHash>');
65
+ // → { valid, status, reason, paymentIntent }
66
+ if (outcome.valid) console.log('settled', outcome.status);
67
+ // manager form: client.paymentIntents.validate(id, { txHash })
68
+ ```
69
+
70
+ Validation checks tx success + destination + amount + memo, finalizes the status
71
+ server-side, and fires the webhook.
72
+
73
+ ## Structure accessors (on a `PaymentIntent`)
74
+
75
+ `id`, `kind`, `status`, `network`, `source`, `destination`, `amount`, `asset`,
76
+ `assetIssuer`, `memo`, `msg`, `callback`, `xdr`, `uri`, `qr`, `txHash`,
77
+ `reference`, `createdAt`, `updatedAt`. Helpers: `isTx`, `isPay`, `isSucceeded`,
78
+ `isPending`, `assetLabel` (`'XLM'` for native). Methods: `fetch()`, `edit()`,
79
+ `validate(txHash)`, `cancel()`, `delete()`, `toJSON()`.
@@ -0,0 +1,113 @@
1
+ # Web client (browser wallets)
2
+
3
+ `@cosmosapp/pay_sdk/web` *completes* an intent in the user's browser. Stellar
4
+ wallets don't ingest SEP-7 `web+stellar:` URIs from a dapp, so the web client
5
+ auto-detects the wallet, adapts the intent into a transaction, signs and submits.
6
+
7
+ ```bash
8
+ npm install @cosmosapp/pay_sdk @stellar/stellar-sdk
9
+ ```
10
+
11
+ ## One-call happy path
12
+
13
+ ```ts
14
+ import { WebClient } from '@cosmosapp/pay_sdk/web';
15
+
16
+ const webClient = new WebClient(); // auto-detects the wallet
17
+ const result = await webClient.pay(intent); // intent = payload/instance/URI string
18
+
19
+ result.wallet; // 'freighter' | 'xbull' | 'rabet' | 'lobstr' | 'albedo' | …
20
+ result.account; // the G... account that signed
21
+ result.txHash; // on-chain transaction hash
22
+ result.submitted; // true
23
+ ```
24
+
25
+ Report `result.txHash` to your server and finalize with `intent.validate(txHash)`.
26
+
27
+ ## Supported wallets
28
+
29
+ Auto-detected (inject a browser global, zero config):
30
+
31
+ | Wallet | id | Detection |
32
+ | ------ | -- | --------- |
33
+ | Freighter | `freighter` | `window.freighterApi` |
34
+ | xBull | `xbull` | `window.xBullSDK` |
35
+ | Rabet | `rabet` | `window.rabet` |
36
+
37
+ Enabled by passing their library (no reliable global):
38
+
39
+ | Wallet | id | Enable |
40
+ | ------ | -- | ------ |
41
+ | Albedo | `albedo` | `new WebClient({ albedo })` — `import albedo from '@albedo-link/intent'` |
42
+ | LOBSTR | `lobstr` | `new WebClient({ lobstr })` — `import * as lobstr from '@lobstrco/signer-extension-api'` |
43
+
44
+ ## Inspect & choose
45
+
46
+ ```ts
47
+ import { Wallets } from '@cosmosapp/pay_sdk/web';
48
+
49
+ const wallets = await webClient.getAvailableWallets(); // [{ id, name, available }]
50
+ const { wallet, address, network } = await webClient.connect(); // just connect
51
+ await webClient.pay(intent, { wallet: Wallets.XBULL }); // pin for one call
52
+ const pinned = new WebClient({ preferredWallets: [Wallets.XBULL, Wallets.FREIGHTER] });
53
+ ```
54
+
55
+ ## `pay()` options & variations
56
+
57
+ ```ts
58
+ await webClient.pay(intent, { amount: '5' }); // open-amount intent
59
+ await webClient.pay(intent, { sign: true }); // sign WITHOUT submitting → { signedXdr }
60
+ await webClient.pay(intent, { submit: false }); // also skips submission
61
+ await webClient.pay(intent, { wallet: 'xbull' });
62
+
63
+ // Inspect the tx before prompting the wallet:
64
+ const { xdr, source, network } = await webClient.buildTransaction(intent);
65
+ ```
66
+
67
+ `pay` vs `tx`: for **pay** intents the client builds a payment from the connected
68
+ account (loads sequence from Horizon, adds op + memo, fee, timebounds). For **tx**
69
+ intents it signs the returned XDR as-is (throws if the connected wallet isn't the
70
+ intent's `source`).
71
+
72
+ ## Network
73
+
74
+ Inferred from the intent (`network` / SEP-7 `network_passphrase`). Override if you
75
+ self-host Horizon: `new WebClient({ network: 'testnet', horizonUrl: '...' })`.
76
+
77
+ ## Custom wallet adapter
78
+
79
+ ```ts
80
+ import { WebClient } from '@cosmosapp/pay_sdk/web';
81
+
82
+ const myWallet = {
83
+ id: 'my-wallet',
84
+ name: 'My Wallet',
85
+ async isAvailable() { return Boolean(globalThis.myWallet); },
86
+ async getPublicKey() { return globalThis.myWallet.getAddress(); },
87
+ async signTransaction(xdr, { networkPassphrase }) {
88
+ return globalThis.myWallet.sign(xdr, networkPassphrase);
89
+ },
90
+ };
91
+ const wc = new WebClient();
92
+ wc.registerWallet(myWallet, /* prepend */ true);
93
+ ```
94
+
95
+ ## Dependency injection (SSR / bundle control)
96
+
97
+ ```ts
98
+ import * as StellarSdk from '@stellar/stellar-sdk';
99
+ import freighter from '@stellar/freighter-api';
100
+ const wc = new WebClient({ stellarSdk: StellarSdk, freighter });
101
+ ```
102
+
103
+ ## Direct API (trusted environments only)
104
+
105
+ > ⚠️ Ships your API key to the browser. Only for prototypes/internal tools with a
106
+ > scoped testnet `dv_` key. For production, create/validate on your server.
107
+
108
+ ```ts
109
+ const wc = new WebClient({ apiKey: 'dv_test_only' });
110
+ const intent = await wc.createPay({ destination: 'G...', amount: '10' });
111
+ const result = await wc.pay(intent);
112
+ const outcome = await wc.validate(intent.id, result.txHash);
113
+ ```
@@ -0,0 +1,109 @@
1
+ # Webhooks
2
+
3
+ Two halves: **registering** endpoints (server CRUD) and **receiving** events
4
+ (the listener + handlers). `client.webhooks` does both.
5
+
6
+ ## Register & manage endpoints
7
+
8
+ ```ts
9
+ import { WebhookEventType } from '@cosmosapp/pay_sdk';
10
+
11
+ const endpoint = await client.webhooks.create({
12
+ url: 'https://me.example.com/hooks/cosmos',
13
+ description: 'Production events',
14
+ eventTypes: [
15
+ WebhookEventType.PaymentIntentSucceeded,
16
+ WebhookEventType.PaymentIntentFailed,
17
+ ], // omit/empty → receive ALL events
18
+ });
19
+ console.log(endpoint.secret); // whsec_… — returned ONCE, store it now!
20
+
21
+ await endpoint.disable(); // pause
22
+ await endpoint.enable(); // resume
23
+ await endpoint.edit({ url: 'https://new...' });
24
+ await endpoint.ping(); // send a test event
25
+ const rotated = await endpoint.rotateSecret(); // new instance carries new secret
26
+ await endpoint.delete();
27
+
28
+ // audit trail + manual redelivery
29
+ const deliveries = await endpoint.fetchDeliveries({ status: 'FAILED', take: 50 });
30
+ for (const d of deliveries.items) await d.redeliver();
31
+ ```
32
+
33
+ Manager forms exist too: `client.webhooks.list()`, `.fetch(id)`,
34
+ `.update(id, {...})`, `.delete(id)`, `.rotateSecret(id)`, `.ping(id)`,
35
+ `.fetchDeliveries(id, {...})`, `.redeliver(id, deliveryId)`.
36
+
37
+ ## Receive events — `client.webhooks.on(...)`
38
+
39
+ Subscribe with the raw type, the camelCase alias, or `event` for all:
40
+
41
+ ```ts
42
+ client.webhooks.on('paymentIntentSucceeded', (event) => {
43
+ console.log('Paid!', event.data.id, event.data.amount);
44
+ });
45
+ client.webhooks.on('PAYMENT_INTENT_FAILED', (event) => { /* ... */ });
46
+ client.webhooks.on('event', (event) => console.log(event.type));
47
+ ```
48
+
49
+ Set the signing secret on the client (or pass `{ secret }` to the handler):
50
+
51
+ ```ts
52
+ const client = new Client({
53
+ apiKey: process.env.COSMOS_PAY_API_KEY,
54
+ webhookSecret: process.env.COSMOS_WEBHOOK_SECRET, // whsec_…
55
+ });
56
+ ```
57
+
58
+ ### Node.js `http` (zero deps)
59
+
60
+ ```ts
61
+ import { createServer } from 'node:http';
62
+ createServer(client.webhooks.createHandler()).listen(4242);
63
+ // verifies signature → emits event → replies 200 (or 400 on bad signature)
64
+ ```
65
+
66
+ ### Express
67
+
68
+ ```ts
69
+ import express from 'express';
70
+ const app = express();
71
+ app.post(
72
+ '/hooks/cosmos',
73
+ express.raw({ type: '*/*' }), // MUST be the RAW body
74
+ client.webhooks.middleware(),
75
+ (req, res) => res.sendStatus(200), // req.cosmosEvent is the verified event
76
+ );
77
+ ```
78
+
79
+ ## Verify signatures manually
80
+
81
+ The dispatcher signs each POST with `X-Cosmos-Signature: t=<unixSeconds>,v1=<hmacSha256>`.
82
+
83
+ ```ts
84
+ import { Webhooks } from '@cosmosapp/pay_sdk';
85
+
86
+ Webhooks.verify(rawBody, header, secret); // → true or throws
87
+ const event = Webhooks.constructEvent(rawBody, header, secret); // verify + parse
88
+ // both accept { toleranceSeconds } (default 300s replay window; 0 disables)
89
+
90
+ // or on a client (also emits to your on(...) listeners):
91
+ client.webhooks.process(rawBody, header, { secret });
92
+ ```
93
+
94
+ Bad signatures throw `WebhookSignatureError`.
95
+
96
+ ## Event payload shape
97
+
98
+ ```ts
99
+ interface WebhookEvent {
100
+ id: string; // stable — use for idempotency
101
+ type: WebhookEventType;
102
+ createdAt: string;
103
+ data: PaymentIntentData;
104
+ }
105
+ ```
106
+
107
+ Event types: `PAYMENT_INTENT_CREATED`, `PAYMENT_INTENT_UPDATED`,
108
+ `PAYMENT_INTENT_SUCCEEDED`, `PAYMENT_INTENT_FAILED`, `PAYMENT_INTENT_CANCELLED`,
109
+ `PAYMENT_INTENT_DELETED`.
@@ -0,0 +1,52 @@
1
+ # Products & customers
2
+
3
+ ## Products / prices — `client.products`
4
+
5
+ ```ts
6
+ import { ProductKind } from '@cosmosapp/pay_sdk';
7
+
8
+ const product = await client.products.create({
9
+ name: 'Pro plan — monthly',
10
+ description: 'Priority support included.', // optional
11
+ amount: '49.00', // optional — omit for customer-set amount
12
+ assetCode: 'USDC', // optional — omit for native XLM
13
+ kind: ProductKind.Recurring, // 'recurring' | 'one_time' | 'link'
14
+ reference: 'sku_pro_monthly', // optional
15
+ });
16
+
17
+ await client.products.list();
18
+ await client.products.fetch(product.id);
19
+ await product.edit({ amount: '59.00' });
20
+ await product.deactivate(); // active = false
21
+ await product.activate(); // active = true
22
+ await product.delete();
23
+ ```
24
+
25
+ `Product` accessors: `id`, `name`, `description`, `amount`, `asset`, `assetLabel`,
26
+ `kind`, `active`, `reference`, `createdAt`, `updatedAt`.
27
+
28
+ ## Customers — `client.customers`
29
+
30
+ ```ts
31
+ const customer = await client.customers.create({
32
+ name: 'Acme Inc.',
33
+ email: 'billing@acme.com', // optional
34
+ alias: 'acme', // optional
35
+ account: 'G...', // optional Stellar account to associate
36
+ reference: 'crm_4821', // optional
37
+ });
38
+
39
+ await customer.edit({ note: 'VIP, net-30' });
40
+ await client.customers.fetch(customer.id);
41
+ await customer.delete();
42
+
43
+ // list() includes payment stats per customer:
44
+ const customers = await client.customers.list();
45
+ for (const c of customers) {
46
+ console.log(c.name, c.payments, c.succeeded, c.total);
47
+ }
48
+ ```
49
+
50
+ `Customer` accessors: `id`, `consumerId`, `name`, `alias`, `note`, `email`,
51
+ `account`, `reference`, `createdAt`, `updatedAt`, plus list-only stats
52
+ `payments`, `succeeded`, `total` (null outside `list()`).
@@ -0,0 +1,25 @@
1
+ # Analytics & health
2
+
3
+ ## Analytics (read-only) — `client.analytics`
4
+
5
+ ```ts
6
+ const summary = await client.analytics.summary(); // totals, volume, webhook health, 30-day series
7
+ const balances = await client.analytics.balances(); // settled + pending per asset
8
+ const apiLogs = await client.analytics.apiLogs(); // recent API requests
9
+ const hookLogs = await client.analytics.webhookLogs(); // recent webhook deliveries
10
+ ```
11
+
12
+ `summary()` → `{ totals: { all, succeeded, pending, submitted, failed, cancelled,
13
+ expired, successRate }, volume: [...], webhooks: { endpoints, deliveries, ... } }`.
14
+
15
+ `balances()` → `{ data: [{ asset, amount, pending, count }], total }`
16
+ where `amount`/`pending` are decimal strings and `count` is the number of payments.
17
+
18
+ ## Health (public probes) — `client.health`
19
+
20
+ ```ts
21
+ await client.health.liveness(); // → true when the service is up
22
+ const ready = await client.health.readiness(); // → { status, info, details } (checks the DB)
23
+ ```
24
+
25
+ These routes don't require an authenticated consumer.