@cosmosapp/pay_sdk 1.1.0 → 1.2.1

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.
@@ -0,0 +1,987 @@
1
+ # @cosmosapp/pay_sdk — full documentation
2
+
3
+ Object-oriented JavaScript/TypeScript SDK for the Cosmos Pay Payments API
4
+ (Stellar SEP-7 payment intents, webhooks, products, customers, analytics).
5
+
6
+ This single file concatenates every topic in llms/ for one-shot AI ingestion.
7
+ Generated by scripts/build-llms.mjs — do not edit by hand; edit the NN-*.md files.
8
+
9
+ # Overview
10
+
11
+ `@cosmosapp/pay_sdk` is the object-oriented JavaScript/TypeScript SDK for the
12
+ **Cosmos Pay** Payments API — Stellar **SEP-7 payment intents**, **webhooks**,
13
+ **products**, **customers** and **analytics**.
14
+
15
+ ## Two entry points
16
+
17
+ | Import | Runs in | Purpose |
18
+ | ------ | ------- | ------- |
19
+ | `@cosmosapp/pay_sdk` | server (Node ≥ 18) | Create & manage intents, webhooks, products, customers, analytics — anything that needs your secret API key. |
20
+ | `@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. |
21
+
22
+ ## Mental model
23
+
24
+ A payment has two halves:
25
+
26
+ 1. **Server** creates an intent with your secret key (`client.paymentIntents.createPay`/`createTx`)
27
+ and returns the payload (`uri`, `qr`, and for `tx` intents an unsigned `xdr`) to your frontend.
28
+ 2. **Browser** completes it with the user's wallet (`new WebClient().pay(intent)`),
29
+ producing an on-chain `txHash`.
30
+ 3. **Server** finalizes by validating that hash (`intent.validate(txHash)`), which
31
+ updates the status and fires a webhook.
32
+
33
+ ## Design
34
+
35
+ - **Atomic** — one `Client`; one manager per resource (`client.paymentIntents`,
36
+ `client.webhooks`, `client.products`, `client.customers`, `client.analytics`,
37
+ `client.health`).
38
+ - **Self-acting structures** — returned objects act on themselves:
39
+ `intent.validate()`, `endpoint.rotateSecret()`, `product.deactivate()`.
40
+ - **Zero runtime dependencies** — native `fetch` + `node:crypto`. The Stellar SDK
41
+ is an *optional* peer dep, only needed by the browser web client.
42
+ - **Fully typed** — works in both CJS and ESM.
43
+
44
+ ## Key facts for correct integration
45
+
46
+ - The **network is chosen by the API key type**: `dv_` → testnet, `prod_` → mainnet.
47
+ You never pass a network on the server.
48
+ - **Amounts are decimal strings** (e.g. `'10'`, `'120.1234567'`), max 7 decimals.
49
+ - The **webhook secret (`whsec_…`) is shown only once** on `create`/`rotateSecret`.
50
+ - The **gateway URL is pre-configured**; a normal integration only sets `apiKey`.
51
+ - Default gateway: `https://api.cosmospay.lat/cosmos-api`. Requires Node ≥ 18.
52
+
53
+ ---
54
+
55
+ # Installation
56
+
57
+ ```bash
58
+ npm install @cosmosapp/pay_sdk
59
+ # or: pnpm add @cosmosapp/pay_sdk
60
+ # or: yarn add @cosmosapp/pay_sdk
61
+ ```
62
+
63
+ Requires **Node.js ≥ 18** (for global `fetch`). On older runtimes pass a `fetch`
64
+ polyfill via the `fetch` client option.
65
+
66
+ ## Browser web client (optional peer dependency)
67
+
68
+ The browser web client builds & submits Stellar transactions, so it needs the
69
+ Stellar SDK (an optional peer dependency, lazy-imported when present):
70
+
71
+ ```bash
72
+ npm install @cosmosapp/pay_sdk @stellar/stellar-sdk
73
+ ```
74
+
75
+ ## Importing
76
+
77
+ ```ts
78
+ // ESM
79
+ import { Client } from '@cosmosapp/pay_sdk';
80
+ import { WebClient } from '@cosmosapp/pay_sdk/web';
81
+ ```
82
+
83
+ ```js
84
+ // CommonJS
85
+ const { Client } = require('@cosmosapp/pay_sdk');
86
+ ```
87
+
88
+ The package ships both ESM (`./dist/index.js`) and CJS (`./dist/index.cjs`) with
89
+ full type declarations.
90
+
91
+ ---
92
+
93
+ # Authentication
94
+
95
+ **You only need your API key.** Everything else (gateway URL, API version) is
96
+ part of the SDK's shared configuration, maintained by Cosmos Pay.
97
+
98
+ ```ts
99
+ import { Client } from '@cosmosapp/pay_sdk';
100
+
101
+ const client = new Client({ apiKey: process.env.COSMOS_PAY_API_KEY });
102
+ ```
103
+
104
+ The API key is sent as `Authorization: Bearer <apiKey>`.
105
+
106
+ ## Network selection (important)
107
+
108
+ The **network is determined by the key type** — you do NOT configure it:
109
+
110
+ | Key prefix | Network |
111
+ | ---------- | ------- |
112
+ | `dv_…` | testnet |
113
+ | `prod_…` | mainnet |
114
+
115
+ Because of this, asset issuers are network-specific: use `Assets.*` for mainnet
116
+ and `TestnetAssets.*` for testnet (see assets docs).
117
+
118
+ ## Keep the key on the server
119
+
120
+ The API key is a secret. Create and validate intents on your **server**. The
121
+ browser web client only signs/submits; it does not need the key. (It *can* take
122
+ an `apiKey` for trusted prototypes, but never ship a production key to the browser.)
123
+
124
+ ## Shared / self-hosting overrides (advanced)
125
+
126
+ ```ts
127
+ // Change the gateway for every client created afterward (once, at startup):
128
+ Client.shared.baseURL = 'https://gateway.your-domain.com';
129
+
130
+ // Or per-client (rarely needed) — e.g. local dev bypassing the gateway:
131
+ const client = new Client({
132
+ apiKey: '...',
133
+ baseURL: 'http://localhost:3000',
134
+ gatewaySecret: process.env.APISIX_GATEWAY_SECRET,
135
+ consumerUsername: 'cosmos_demo',
136
+ });
137
+ ```
138
+
139
+ `baseURL`, `version`, `gatewaySecret`, `consumerUsername` are all optional — a
140
+ normal integration never sets them.
141
+
142
+ ---
143
+
144
+ # Quickstart
145
+
146
+ ```ts
147
+ import { Client } from '@cosmosapp/pay_sdk';
148
+
149
+ const client = new Client({ apiKey: process.env.COSMOS_PAY_API_KEY });
150
+
151
+ // 1. Create a SEP-7 `pay` intent (no source → pay URI + QR).
152
+ const intent = await client.paymentIntents.createPay({
153
+ destination: 'GCALNQQBXAPZ2WIRSDDBMSTAKCUH5SG6U76YBFLQLIXJTF7FE5AX7AOO',
154
+ amount: '120.1234567',
155
+ // Omitting asset fields uses native XLM on both testnet and mainnet.
156
+ msg: 'Order #24',
157
+ });
158
+
159
+ console.log(intent.uri); // web+stellar:pay?destination=...
160
+ console.log(intent.qr); // data:image/png;base64,... (render this)
161
+
162
+ // 2. After the payer submits a transaction, validate it.
163
+ const outcome = await intent.validate('<txHash>');
164
+ if (outcome.valid) console.log('Settled!', outcome.status);
165
+ ```
166
+
167
+ ## Full split (server creates, browser completes)
168
+
169
+ ```ts
170
+ // ── server.ts ──────────────────────────────────────────────────────
171
+ import { Client } from '@cosmosapp/pay_sdk';
172
+ const client = new Client({ apiKey: process.env.COSMOS_PAY_API_KEY });
173
+
174
+ export async function createIntent() {
175
+ const intent = await client.paymentIntents.createPay({
176
+ destination: 'G...MERCHANT',
177
+ amount: '10',
178
+ // Native XLM keeps this first example network-independent.
179
+ });
180
+ return intent.toJSON(); // send this payload to the browser
181
+ }
182
+
183
+ export function confirm(intentId: string, txHash: string) {
184
+ return client.paymentIntents.validate(intentId, { txHash });
185
+ }
186
+ ```
187
+
188
+ ```ts
189
+ // ── browser.ts ─────────────────────────────────────────────────────
190
+ import { WebClient } from '@cosmosapp/pay_sdk/web';
191
+
192
+ const intent = await fetch('/api/create-intent', { method: 'POST' }).then((r) => r.json());
193
+ const { txHash, account, wallet } = await new WebClient().pay(intent);
194
+
195
+ await fetch('/api/confirm', {
196
+ method: 'POST',
197
+ headers: { 'Content-Type': 'application/json' },
198
+ body: JSON.stringify({ intentId: intent.id, txHash }),
199
+ });
200
+ ```
201
+
202
+ ---
203
+
204
+ # The Client
205
+
206
+ ```ts
207
+ import { Client } from '@cosmosapp/pay_sdk';
208
+ const client = new Client({ apiKey: process.env.COSMOS_PAY_API_KEY });
209
+ ```
210
+
211
+ One client exposes every resource through its own manager.
212
+
213
+ | Manager | Resource | Key methods |
214
+ | ------- | -------- | ----------- |
215
+ | `client.paymentIntents` | Stellar SEP-7 intents | `createTx` · `createPay` · `fetch` · `list` · `update` · `delete` · `validate` |
216
+ | `client.webhooks` | Endpoints + deliveries + event listener | `create` · `list` · `fetch` · `update` · `delete` · `rotateSecret` · `ping` · `fetchDeliveries` · `redeliver` · `on(...)` · `process` · `createHandler` · `middleware` |
217
+ | `client.products` | Products / prices | `create` · `list` · `fetch` · `update` · `delete` |
218
+ | `client.customers` | Customers | `create` · `list` · `fetch` · `update` · `delete` |
219
+ | `client.analytics` | Read-only metrics | `summary` · `balances` · `apiLogs` · `webhookLogs` |
220
+ | `client.health` | Liveness / readiness | `liveness` · `readiness` |
221
+
222
+ ## Constructor options
223
+
224
+ ```ts
225
+ new Client({
226
+ apiKey: 'prod_xxx', // required — the only thing you normally set
227
+ webhookSecret: 'whsec_...', // default secret for the webhook listener
228
+ timeout: 30_000, // ms (default 30000)
229
+ retries: 2, // network errors / 429 / 5xx (default 2)
230
+ headers: { 'X-Trace': 'abc' },
231
+ fetch: customFetch, // custom fetch implementation
232
+
233
+ // Advanced / internal (pre-filled from Client.shared, rarely set):
234
+ baseURL: 'https://api.cosmospay.lat/cosmos-api',
235
+ version: 'v1',
236
+ gatewaySecret: '...',
237
+ consumerUsername: '...',
238
+ });
239
+ ```
240
+
241
+ ## Statics & mutators
242
+
243
+ ```ts
244
+ Client.version; // library version string
245
+ Client.shared.baseURL = 'https://...'; // process-wide default for all clients
246
+
247
+ client.setApiKey('prod_rotated');
248
+ client.setWebhookSecret('whsec_new');
249
+ client.setGatewayCredentials(secret, consumerUsername); // local-dev direct access
250
+ ```
251
+
252
+ ## Returned objects are "structures"
253
+
254
+ Manager methods return rich instances (`PaymentIntent`, `WebhookEndpoint`,
255
+ `Product`, `Customer`) that can act on themselves and expose typed accessors —
256
+ e.g. `intent.isPay`, `intent.assetLabel`, `await intent.validate(txHash)`,
257
+ `await endpoint.disable()`. Call `.toJSON()` for the raw payload.
258
+
259
+ ---
260
+
261
+ # Payment intents
262
+
263
+ `client.paymentIntents` — Stellar SEP-7 intents. Two kinds:
264
+
265
+ - **`pay` intent** — no source. The payer's wallet picks the source account.
266
+ Produces a `web+stellar:pay?...` URI + QR (no XDR).
267
+ - **`tx` intent** — source known. Produces an unsigned XDR + `web+stellar:tx?...`
268
+ URI + QR.
269
+
270
+ ## Create
271
+
272
+ ```ts
273
+ import { Assets, TestnetAssets } from '@cosmosapp/pay_sdk';
274
+
275
+ const usdc = process.env.COSMOS_PAY_API_KEY?.startsWith('prod_')
276
+ ? Assets.USDC
277
+ : TestnetAssets.USDC;
278
+
279
+ // pay (no source)
280
+ const pay = await client.paymentIntents.createPay({
281
+ destination: 'G...', // required — payee (or an address-book name)
282
+ amount: '10', // optional — omit for an open amount (donations)
283
+ asset: usdc, // issuer matches the API key network
284
+ // assetCode: 'USDC', assetIssuer: 'G...', // …or set them explicitly
285
+ // omit asset entirely for native lumens (XLM)
286
+ memo: '123456789', // optional MEMO_ID (uint64) — auto-generated if omitted
287
+ msg: 'Order #24', // optional, ≤ 300 chars, shown in the wallet
288
+ callback: 'url:https://...', // optional SEP-7 callback for the signed XDR
289
+ });
290
+
291
+ // tx (source known)
292
+ const tx = await client.paymentIntents.createTx({
293
+ source: 'G...PAYER', // required (extra vs pay)
294
+ destination: 'G...MERCHANT',
295
+ amount: '25.5',
296
+ });
297
+ console.log(tx.xdr, tx.uri, tx.qr);
298
+ ```
299
+
300
+ > Amounts are **decimal strings**, max 7 decimals. Asset issuers are
301
+ > network-specific (mainnet vs testnet).
302
+
303
+ ## Fetch / list
304
+
305
+ ```ts
306
+ const intent = await client.paymentIntents.fetch('pi_123');
307
+
308
+ const page = await client.paymentIntents.list({
309
+ status: 'SUCCEEDED', // optional filter (PaymentIntentStatus)
310
+ take: 50, // page size, max 100, default 20
311
+ skip: 0, // offset
312
+ });
313
+ // page → { items: PaymentIntent[], total, take, skip }
314
+ ```
315
+
316
+ ## Update / cancel / delete
317
+
318
+ ```ts
319
+ await intent.edit({ reference: 'order_1234' }); // status / txHash / reference
320
+ await intent.cancel(); // → status CANCELLED
321
+ await intent.delete();
322
+ // manager forms: client.paymentIntents.update(id, {...}) / .delete(id)
323
+ ```
324
+
325
+ ## Validate (finalize)
326
+
327
+ ```ts
328
+ const outcome = await intent.validate('<txHash>');
329
+ // → { valid, status, reason, paymentIntent }
330
+ if (outcome.valid) console.log('settled', outcome.status);
331
+ // manager form: client.paymentIntents.validate(id, { txHash })
332
+ ```
333
+
334
+ Validation checks tx success + destination + amount + memo, finalizes the status
335
+ server-side, and fires the webhook.
336
+
337
+ ## Structure accessors (on a `PaymentIntent`)
338
+
339
+ `id`, `kind`, `status`, `network`, `source`, `destination`, `amount`, `asset`,
340
+ `assetIssuer`, `memo`, `msg`, `callback`, `xdr`, `uri`, `qr`, `txHash`,
341
+ `reference`, `createdAt`, `updatedAt`. Helpers: `isTx`, `isPay`, `isSucceeded`,
342
+ `isPending`, `assetLabel` (`'XLM'` for native). Methods: `fetch()`, `edit()`,
343
+ `validate(txHash)`, `cancel()`, `delete()`, `toJSON()`.
344
+
345
+ ---
346
+
347
+ # Web client (browser wallets)
348
+
349
+ `@cosmosapp/pay_sdk/web` *completes* an intent in the user's browser. Stellar
350
+ wallets don't ingest SEP-7 `web+stellar:` URIs from a dapp, so the web client
351
+ auto-detects the wallet, adapts the intent into a transaction, signs and submits.
352
+
353
+ ```bash
354
+ npm install @cosmosapp/pay_sdk @stellar/stellar-sdk
355
+ ```
356
+
357
+ ## One-call happy path
358
+
359
+ ```ts
360
+ import { WebClient } from '@cosmosapp/pay_sdk/web';
361
+
362
+ const webClient = new WebClient(); // auto-detects the wallet
363
+ const result = await webClient.pay(intent); // intent = payload/instance/URI string
364
+
365
+ result.wallet; // 'freighter' | 'xbull' | 'rabet' | 'lobstr' | 'albedo' | …
366
+ result.account; // the G... account that signed
367
+ result.txHash; // on-chain transaction hash
368
+ result.submitted; // true
369
+ ```
370
+
371
+ Report `result.txHash` to your server and finalize with `intent.validate(txHash)`.
372
+
373
+ ## Supported wallets
374
+
375
+ Auto-detected (inject a browser global, zero config):
376
+
377
+ | Wallet | id | Detection |
378
+ | ------ | -- | --------- |
379
+ | Freighter | `freighter` | `window.freighterApi` |
380
+ | xBull | `xbull` | `window.xBullSDK` |
381
+ | Rabet | `rabet` | `window.rabet` |
382
+
383
+ Enabled by passing their library (no reliable global):
384
+
385
+ | Wallet | id | Enable |
386
+ | ------ | -- | ------ |
387
+ | Albedo | `albedo` | `new WebClient({ albedo })` — `import albedo from '@albedo-link/intent'` |
388
+ | LOBSTR | `lobstr` | `new WebClient({ lobstr })` — `import * as lobstr from '@lobstrco/signer-extension-api'` |
389
+
390
+ ## Inspect & choose
391
+
392
+ ```ts
393
+ import { Wallets } from '@cosmosapp/pay_sdk/web';
394
+
395
+ const wallets = await webClient.getAvailableWallets(); // [{ id, name, available }]
396
+ const { wallet, address, network } = await webClient.connect(); // just connect
397
+ await webClient.pay(intent, { wallet: Wallets.XBULL }); // pin for one call
398
+ const pinned = new WebClient({ preferredWallets: [Wallets.XBULL, Wallets.FREIGHTER] });
399
+ ```
400
+
401
+ ## `pay()` options & variations
402
+
403
+ ```ts
404
+ await webClient.pay(intent, { amount: '5' }); // open-amount intent
405
+ await webClient.pay(intent, { sign: true }); // sign WITHOUT submitting → { signedXdr }
406
+ await webClient.pay(intent, { submit: false }); // also skips submission
407
+ await webClient.pay(intent, { wallet: 'xbull' });
408
+
409
+ // Inspect the tx before prompting the wallet:
410
+ const { xdr, source, network } = await webClient.buildTransaction(intent);
411
+ ```
412
+
413
+ `pay` vs `tx`: for **pay** intents the client builds a payment from the connected
414
+ account (loads sequence from Horizon, adds op + memo, fee, timebounds). For **tx**
415
+ intents it signs the returned XDR as-is (throws if the connected wallet isn't the
416
+ intent's `source`).
417
+
418
+ ## Network
419
+
420
+ Inferred from the intent (`network` / SEP-7 `network_passphrase`). Override if you
421
+ self-host Horizon: `new WebClient({ network: 'testnet', horizonUrl: '...' })`.
422
+
423
+ ## Custom wallet adapter
424
+
425
+ ```ts
426
+ import { WebClient } from '@cosmosapp/pay_sdk/web';
427
+
428
+ const myWallet = {
429
+ id: 'my-wallet',
430
+ name: 'My Wallet',
431
+ async isAvailable() { return Boolean(globalThis.myWallet); },
432
+ async getPublicKey() { return globalThis.myWallet.getAddress(); },
433
+ async signTransaction(xdr, { networkPassphrase }) {
434
+ return globalThis.myWallet.sign(xdr, networkPassphrase);
435
+ },
436
+ };
437
+ const wc = new WebClient();
438
+ wc.registerWallet(myWallet, /* prepend */ true);
439
+ ```
440
+
441
+ ## Dependency injection (SSR / bundle control)
442
+
443
+ ```ts
444
+ import * as StellarSdk from '@stellar/stellar-sdk';
445
+ import freighter from '@stellar/freighter-api';
446
+ const wc = new WebClient({ stellarSdk: StellarSdk, freighter });
447
+ ```
448
+
449
+ ## Direct API (trusted environments only)
450
+
451
+ > ⚠️ Ships your API key to the browser. Only for prototypes/internal tools with a
452
+ > scoped testnet `dv_` key. For production, create/validate on your server.
453
+
454
+ ```ts
455
+ const wc = new WebClient({ apiKey: 'dv_test_only' });
456
+ const intent = await wc.createPay({ destination: 'G...', amount: '10' });
457
+ const result = await wc.pay(intent);
458
+ const outcome = await wc.validate(intent.id, result.txHash);
459
+ ```
460
+
461
+ ---
462
+
463
+ # Webhooks
464
+
465
+ Two halves: **registering** endpoints (server CRUD) and **receiving** events
466
+ (the listener + handlers). `client.webhooks` does both.
467
+
468
+ ## Register & manage endpoints
469
+
470
+ ```ts
471
+ import { WebhookEventType } from '@cosmosapp/pay_sdk';
472
+
473
+ const endpoint = await client.webhooks.create({
474
+ url: 'https://me.example.com/hooks/cosmos',
475
+ description: 'Production events',
476
+ eventTypes: [
477
+ WebhookEventType.PaymentIntentSucceeded,
478
+ WebhookEventType.PaymentIntentFailed,
479
+ ], // omit/empty → receive ALL events
480
+ });
481
+ console.log(endpoint.secret); // whsec_… — returned ONCE, store it now!
482
+
483
+ await endpoint.disable(); // pause
484
+ await endpoint.enable(); // resume
485
+ await endpoint.edit({ url: 'https://new...' });
486
+ await endpoint.ping(); // send a test event
487
+ const rotated = await endpoint.rotateSecret(); // new instance carries new secret
488
+ await endpoint.delete();
489
+
490
+ // audit trail + manual redelivery
491
+ const deliveries = await endpoint.fetchDeliveries({ status: 'FAILED', take: 50 });
492
+ for (const d of deliveries.items) await d.redeliver();
493
+ ```
494
+
495
+ Manager forms exist too: `client.webhooks.list()`, `.fetch(id)`,
496
+ `.update(id, {...})`, `.delete(id)`, `.rotateSecret(id)`, `.ping(id)`,
497
+ `.fetchDeliveries(id, {...})`, `.redeliver(id, deliveryId)`.
498
+
499
+ ## Receive events — `client.webhooks.on(...)`
500
+
501
+ Subscribe with the raw type, the camelCase alias, or `event` for all:
502
+
503
+ ```ts
504
+ client.webhooks.on('paymentIntentSucceeded', (event) => {
505
+ console.log('Paid!', event.data.id, event.data.amount);
506
+ });
507
+ client.webhooks.on('PAYMENT_INTENT_FAILED', (event) => { /* ... */ });
508
+ client.webhooks.on('event', (event) => console.log(event.type));
509
+ ```
510
+
511
+ Set the signing secret on the client (or pass `{ secret }` to the handler):
512
+
513
+ ```ts
514
+ const client = new Client({
515
+ apiKey: process.env.COSMOS_PAY_API_KEY,
516
+ webhookSecret: process.env.COSMOS_WEBHOOK_SECRET, // whsec_…
517
+ });
518
+ ```
519
+
520
+ ### Node.js `http` (zero deps)
521
+
522
+ ```ts
523
+ import { createServer } from 'node:http';
524
+ createServer(client.webhooks.createHandler()).listen(4242);
525
+ // verifies signature → emits event → replies 200 (or 400 on bad signature)
526
+ ```
527
+
528
+ ### Express
529
+
530
+ ```ts
531
+ import express from 'express';
532
+ const app = express();
533
+ app.post(
534
+ '/hooks/cosmos',
535
+ express.raw({ type: '*/*' }), // MUST be the RAW body
536
+ client.webhooks.middleware(),
537
+ (req, res) => res.sendStatus(200), // req.cosmosEvent is the verified event
538
+ );
539
+ ```
540
+
541
+ ## Verify signatures manually
542
+
543
+ The dispatcher signs each POST with `X-Cosmos-Signature: t=<unixSeconds>,v1=<hmacSha256>`.
544
+
545
+ ```ts
546
+ import { Webhooks } from '@cosmosapp/pay_sdk';
547
+
548
+ Webhooks.verify(rawBody, header, secret); // → true or throws
549
+ const event = Webhooks.constructEvent(rawBody, header, secret); // verify + parse
550
+ // both accept { toleranceSeconds } (default 300s replay window; 0 disables)
551
+
552
+ // or on a client (also emits to your on(...) listeners):
553
+ client.webhooks.process(rawBody, header, { secret });
554
+ ```
555
+
556
+ Bad signatures throw `WebhookSignatureError`.
557
+
558
+ ## Event payload shape
559
+
560
+ ```ts
561
+ interface WebhookEvent {
562
+ id: string; // stable — use for idempotency
563
+ type: WebhookEventType;
564
+ createdAt: string;
565
+ data: PaymentIntentData;
566
+ }
567
+ ```
568
+
569
+ Event types: `PAYMENT_INTENT_CREATED`, `PAYMENT_INTENT_UPDATED`,
570
+ `PAYMENT_INTENT_SUCCEEDED`, `PAYMENT_INTENT_FAILED`, `PAYMENT_INTENT_CANCELLED`,
571
+ `PAYMENT_INTENT_DELETED`.
572
+
573
+ ---
574
+
575
+ # Products & customers
576
+
577
+ ## Products / prices — `client.products`
578
+
579
+ ```ts
580
+ import { ProductKind } from '@cosmosapp/pay_sdk';
581
+
582
+ const product = await client.products.create({
583
+ name: 'Pro plan — monthly',
584
+ description: 'Priority support included.', // optional
585
+ amount: '49.00', // optional — omit for customer-set amount
586
+ assetCode: 'USDC', // optional — omit for native XLM
587
+ kind: ProductKind.Recurring, // 'recurring' | 'one_time' | 'link'
588
+ reference: 'sku_pro_monthly', // optional
589
+ });
590
+
591
+ await client.products.list();
592
+ await client.products.fetch(product.id);
593
+ await product.edit({ amount: '59.00' });
594
+ await product.deactivate(); // active = false
595
+ await product.activate(); // active = true
596
+ await product.delete();
597
+ ```
598
+
599
+ `Product` accessors: `id`, `name`, `description`, `amount`, `asset`, `assetLabel`,
600
+ `kind`, `active`, `reference`, `createdAt`, `updatedAt`.
601
+
602
+ ## Customers — `client.customers`
603
+
604
+ ```ts
605
+ const customer = await client.customers.create({
606
+ name: 'Acme Inc.',
607
+ email: 'billing@acme.com', // optional
608
+ alias: 'acme', // optional
609
+ account: 'G...', // optional Stellar account to associate
610
+ reference: 'crm_4821', // optional
611
+ });
612
+
613
+ await customer.edit({ note: 'VIP, net-30' });
614
+ await client.customers.fetch(customer.id);
615
+ await customer.delete();
616
+
617
+ // list() includes payment stats per customer:
618
+ const customers = await client.customers.list();
619
+ for (const c of customers) {
620
+ console.log(c.name, c.payments, c.succeeded, c.total);
621
+ }
622
+ ```
623
+
624
+ `Customer` accessors: `id`, `consumerId`, `name`, `alias`, `note`, `email`,
625
+ `account`, `reference`, `createdAt`, `updatedAt`, plus list-only stats
626
+ `payments`, `succeeded`, `total` (null outside `list()`).
627
+
628
+ ---
629
+
630
+ # Analytics & health
631
+
632
+ ## Analytics (read-only) — `client.analytics`
633
+
634
+ ```ts
635
+ const summary = await client.analytics.summary(); // totals, volume, webhook health, 30-day series
636
+ const balances = await client.analytics.balances(); // settled + pending per asset
637
+ const apiLogs = await client.analytics.apiLogs(); // recent API requests
638
+ const hookLogs = await client.analytics.webhookLogs(); // recent webhook deliveries
639
+ ```
640
+
641
+ `summary()` → `{ totals: { all, succeeded, pending, submitted, failed, cancelled,
642
+ expired, successRate }, volume: [...], webhooks: { endpoints, deliveries, ... } }`.
643
+
644
+ `balances()` → `{ data: [{ asset, amount, pending, count }], total }`
645
+ where `amount`/`pending` are decimal strings and `count` is the number of payments.
646
+
647
+ ## Health (public probes) — `client.health`
648
+
649
+ ```ts
650
+ await client.health.liveness(); // → true when the service is up
651
+ const ready = await client.health.readiness(); // → { status, info, details } (checks the DB)
652
+ ```
653
+
654
+ These routes don't require an authenticated consumer.
655
+
656
+ ---
657
+
658
+ # Typed assets, wallets & addresses
659
+
660
+ Small typed catalogs so you never paste the wrong issuer or a magic string. Plain
661
+ strings still work everywhere. Exported from **both** entry points
662
+ (`@cosmosapp/pay_sdk` and `@cosmosapp/pay_sdk/web`).
663
+
664
+ ## Assets
665
+
666
+ ```ts
667
+ import { Assets, TestnetAssets, defineAsset, resolveAsset, isNativeAsset } from '@cosmosapp/pay_sdk';
668
+
669
+ Assets.XLM; // native lumens
670
+ Assets.USDC; // { code: 'USDC', issuer: 'GA5Z…' } (Circle, mainnet — verified)
671
+ Assets.EURC; // { code: 'EURC', issuer: 'GDHU…' }
672
+
673
+ // Custom asset (issuer/contract validated):
674
+ const AQUA = defineAsset({ code: 'AQUA', issuer: 'GBNZ…', name: 'Aquarius' });
675
+
676
+ await client.paymentIntents.createPay({ destination: 'G...', amount: '5', asset: AQUA });
677
+
678
+ // Plain code + issuer also works:
679
+ await client.paymentIntents.createPay({ destination: 'G...', amount: '5', assetCode: 'USDC', assetIssuer: 'G...' });
680
+ ```
681
+
682
+ > ⚠️ Issuers are **network-specific**. `Assets.*` = mainnet; use `TestnetAssets.*`
683
+ > (e.g. `TestnetAssets.USDC`) for testnet, matched to your `dv_` key.
684
+
685
+ Helpers: `resolveAsset(ref)` → `{ code, issuer? }`; `isNativeAsset(ref)` → boolean.
686
+
687
+ ## Wallets
688
+
689
+ ```ts
690
+ import { Wallets } from '@cosmosapp/pay_sdk/web';
691
+ Wallets.FREIGHTER; Wallets.XBULL; Wallets.RABET; Wallets.LOBSTR; Wallets.ALBEDO;
692
+
693
+ const wc = new WebClient({ preferredWallets: [Wallets.XBULL, Wallets.FREIGHTER] });
694
+ await wc.pay(intent, { wallet: Wallets.FREIGHTER });
695
+ ```
696
+
697
+ ## Address book
698
+
699
+ ```ts
700
+ import { addresses, resolveAddress, isStellarAddress, isMuxedAddress, isContractAddress, isAddress, assertAddress } from '@cosmosapp/pay_sdk';
701
+
702
+ addresses.define('merchant', 'GC...PAYOUT');
703
+ await client.paymentIntents.createPay({ destination: 'merchant', amount: '10' });
704
+
705
+ resolveAddress('merchant'); // → 'GC...PAYOUT' (unknown values pass through unchanged)
706
+ isStellarAddress('GC...'); // true
707
+ isMuxedAddress('MA...'); // true
708
+ isContractAddress('CA...'); // true
709
+ isAddress('merchant'); // true
710
+ assertAddress(value); // throws on an invalid value
711
+ ```
712
+
713
+ Raw `G…`, muxed `M…`, contract `C…` and federation addresses keep working as
714
+ plain strings.
715
+
716
+ ---
717
+
718
+ # Error handling & observability
719
+
720
+ ## Errors
721
+
722
+ ```ts
723
+ import { CosmosPayAPIError, CosmosPayRequestError } from '@cosmosapp/pay_sdk';
724
+
725
+ try {
726
+ await client.paymentIntents.fetch('missing');
727
+ } catch (err) {
728
+ if (err instanceof CosmosPayAPIError) {
729
+ // server responded with an error status
730
+ console.error(err.status, err.code, err.body); // e.g. 404
731
+ } else if (err instanceof CosmosPayRequestError) {
732
+ // no usable response — network / TLS / timeout / offline
733
+ console.error('Network/timeout:', err.cause);
734
+ } else {
735
+ throw err;
736
+ }
737
+ }
738
+ ```
739
+
740
+ - `CosmosPayAPIError` — the API replied with 4xx/5xx. Fields: `status`, `code`, `body`.
741
+ - `CosmosPayRequestError` — the request never completed. Field: `cause`.
742
+ - Web client adds: `CosmosPayWebError`, `WalletNotFoundError`, `WalletError`
743
+ (user rejected / locked), `StellarSdkRequiredError`, `IntentError`. The API
744
+ error classes are re-exported from `/web` too, so `catch` works across entries.
745
+ - Webhook signature failures throw `WebhookSignatureError`.
746
+
747
+ ### Retries
748
+
749
+ Transient failures (network errors, `408`, `429`, `5xx`) are retried
750
+ automatically — default **2** retries, honoring `Retry-After`. Tune via
751
+ `new Client({ retries, timeout })`.
752
+
753
+ ## Observability
754
+
755
+ The client re-emits REST telemetry:
756
+
757
+ ```ts
758
+ client.on('request', ({ method, url, attempt }) => {});
759
+ client.on('response', ({ method, url, status, attempt }) => {});
760
+ client.on('rateLimited', ({ method, url, attempt }) => {});
761
+ client.on('debug', (message) => {});
762
+ ```
763
+
764
+ Wire these into your logger/APM to trace or meter every request.
765
+
766
+ ---
767
+
768
+ # Configuration reference
769
+
770
+ ```ts
771
+ new Client({
772
+ apiKey: 'prod_xxx', // required — the only thing you normally set
773
+ webhookSecret: 'whsec_...', // default secret for the webhook listener
774
+ timeout: 30_000, // ms (default 30000)
775
+ retries: 2, // network errors / 429 / 5xx (default 2)
776
+ headers: { 'X-Trace': 'abc' }, // extra headers on every request
777
+ fetch: customFetch, // custom fetch implementation
778
+
779
+ // Advanced / internal — pre-filled from Client.shared, rarely overridden:
780
+ baseURL: 'https://api.cosmospay.lat/cosmos-api', // gateway URL (default)
781
+ version: 'v1', // route prefix
782
+ gatewaySecret: '...', // direct access (X-Gateway-Secret), local dev
783
+ consumerUsername: '...', // direct access (X-Consumer-Username), local dev
784
+ });
785
+ ```
786
+
787
+ ## Environment variables (convention)
788
+
789
+ The SDK reads nothing from the environment itself — you pass values in. Common
790
+ convention used across the docs/examples:
791
+
792
+ | Var | Used for |
793
+ | --- | -------- |
794
+ | `COSMOS_PAY_API_KEY` | `new Client({ apiKey })` |
795
+ | `COSMOS_WEBHOOK_SECRET` | `new Client({ webhookSecret })` / handler `{ secret }` |
796
+
797
+ ## Self-hosting / staging
798
+
799
+ ```ts
800
+ // Once at startup, for every client:
801
+ Client.shared.baseURL = 'https://gateway.your-domain.com';
802
+
803
+ // Or per-client, bypassing the gateway in local dev:
804
+ new Client({
805
+ apiKey: 'x',
806
+ baseURL: 'http://localhost:3000',
807
+ gatewaySecret: process.env.APISIX_GATEWAY_SECRET,
808
+ consumerUsername: 'cosmos_demo',
809
+ });
810
+ ```
811
+
812
+ ---
813
+
814
+ # Types & enums reference
815
+
816
+ Everything is fully typed. Import option/entity types and the const-enums directly
817
+ from `@cosmosapp/pay_sdk` (or `/web`).
818
+
819
+ ```ts
820
+ import {
821
+ Client,
822
+ PaymentIntentStatus,
823
+ PaymentIntentKind,
824
+ WebhookEventType,
825
+ WebhookDeliveryStatus,
826
+ ProductKind,
827
+ type CreatePayPaymentIntentOptions,
828
+ type CreateTxPaymentIntentOptions,
829
+ type PaymentIntentData,
830
+ } from '@cosmosapp/pay_sdk';
831
+ ```
832
+
833
+ ## Enums (const objects — usable as values and types)
834
+
835
+ ```ts
836
+ PaymentIntentStatus = { Pending:'PENDING', Submitted:'SUBMITTED', Succeeded:'SUCCEEDED',
837
+ Failed:'FAILED', Cancelled:'CANCELLED', Expired:'EXPIRED' }
838
+ PaymentIntentKind = { Tx:'TX', Pay:'PAY' }
839
+ WebhookEventType = { PaymentIntentCreated:'PAYMENT_INTENT_CREATED',
840
+ PaymentIntentUpdated:'PAYMENT_INTENT_UPDATED',
841
+ PaymentIntentSucceeded:'PAYMENT_INTENT_SUCCEEDED',
842
+ PaymentIntentFailed:'PAYMENT_INTENT_FAILED',
843
+ PaymentIntentCancelled:'PAYMENT_INTENT_CANCELLED',
844
+ PaymentIntentDeleted:'PAYMENT_INTENT_DELETED' }
845
+ WebhookDeliveryStatus = { Pending:'PENDING', Succeeded:'SUCCEEDED', Failed:'FAILED' }
846
+ ProductKind = { Recurring:'recurring', OneTime:'one_time', Link:'link' }
847
+ ```
848
+
849
+ ## Option types (inputs)
850
+
851
+ ```ts
852
+ interface CreatePayPaymentIntentOptions {
853
+ destination: string; amount?: string; asset?: AssetRef;
854
+ assetCode?: string; assetIssuer?: string; memo?: string; msg?: string; callback?: string;
855
+ }
856
+ interface CreateTxPaymentIntentOptions {
857
+ source: string; destination: string; amount: string; asset?: AssetRef;
858
+ assetCode?: string; assetIssuer?: string; memo?: string; msg?: string; callback?: string;
859
+ }
860
+ interface UpdatePaymentIntentOptions { status?: PaymentIntentStatus; txHash?: string; reference?: string; }
861
+ interface ListPaymentIntentsOptions { status?: PaymentIntentStatus; take?: number; skip?: number; }
862
+ interface ValidatePaymentIntentOptions { txHash: string; }
863
+
864
+ interface CreateWebhookEndpointOptions { url: string; description?: string; eventTypes?: WebhookEventType[]; }
865
+ interface UpdateWebhookEndpointOptions { url?: string; description?: string; enabled?: boolean; eventTypes?: WebhookEventType[]; }
866
+ interface ListWebhookDeliveriesOptions { status?: WebhookDeliveryStatus; take?: number; skip?: number; }
867
+
868
+ interface CreateProductOptions { name: string; description?: string; amount?: string; assetCode?: string; kind?: ProductKind; active?: boolean; reference?: string; }
869
+ type UpdateProductOptions = Partial<CreateProductOptions>;
870
+
871
+ interface CreateCustomerOptions { name: string; alias?: string; note?: string; email?: string; account?: string; reference?: string; }
872
+ type UpdateCustomerOptions = Partial<CreateCustomerOptions>;
873
+ ```
874
+
875
+ ## Entity payloads (outputs)
876
+
877
+ - `PaymentIntentData` — `id, kind, status, network, source, destination, amount,
878
+ asset, assetIssuer, memo, msg, callback, xdr, uri, qr, txHash, reference,
879
+ createdAt, updatedAt`.
880
+ - `WebhookEndpointData` — `id, url, description, enabled, eventTypes, createdAt,
881
+ updatedAt` (+ `secret` on create/rotate only).
882
+ - `WebhookEvent<T = PaymentIntentData>` — `{ id, type, createdAt, data }`.
883
+ - `ProductData` — `id, name, description, amount, asset, kind, active, reference,
884
+ createdAt, updatedAt`.
885
+ - `CustomerData` — `id, consumerId, name, alias, note, email, account, reference,
886
+ createdAt, updatedAt` (+ list-only `payments, succeeded, total`).
887
+ - `AnalyticsBalancesData` — `{ data: { asset, amount, pending, count }[], total }`.
888
+ - `ValidationOutcomeData` — `{ valid, status, reason?, paymentIntent? }`.
889
+
890
+ Pagination wrappers (`list` / `fetchDeliveries`) return
891
+ `{ items, total, take, skip }`.
892
+
893
+ ---
894
+
895
+ # Recipes
896
+
897
+ Copy-paste end-to-end patterns. All server snippets assume:
898
+
899
+ ```ts
900
+ import { Assets, Client, TestnetAssets } from '@cosmosapp/pay_sdk';
901
+
902
+ const apiKey = process.env.COSMOS_PAY_API_KEY;
903
+ const merchantAccount = process.env.MERCHANT_ACCOUNT;
904
+ if (!apiKey || !merchantAccount) throw new Error('Missing Cosmos Pay configuration');
905
+
906
+ const client = new Client({ apiKey });
907
+ const usdc = apiKey.startsWith('prod_') ? Assets.USDC : TestnetAssets.USDC;
908
+ ```
909
+
910
+ ## 1. Checkout (server creates, browser pays, webhook confirms)
911
+
912
+ ```ts
913
+ // server: create the intent for an order
914
+ export async function startCheckout(orderId: string, total: string) {
915
+ const intent = await client.paymentIntents.createPay({
916
+ destination: merchantAccount,
917
+ amount: total,
918
+ asset: usdc,
919
+ msg: `Order ${orderId}`,
920
+ });
921
+ await intent.edit({ reference: orderId }); // reference is set through PATCH
922
+ return intent.toJSON(); // → send to the browser
923
+ }
924
+ ```
925
+
926
+ ```ts
927
+ // browser: complete it with the user's wallet
928
+ import { WebClient } from '@cosmosapp/pay_sdk/web';
929
+ const { txHash } = await new WebClient().pay(intentPayload);
930
+ await fetch('/api/confirm', { method: 'POST', body: JSON.stringify({ id: intentPayload.id, txHash }) });
931
+ ```
932
+
933
+ ```ts
934
+ // server: fulfill on the webhook (don't trust the browser alone)
935
+ client.webhooks.on('paymentIntentSucceeded', async (event) => {
936
+ await markOrderPaid(event.data.reference, event.data.id);
937
+ });
938
+ ```
939
+
940
+ ## 2. Donation / tip jar (open amount)
941
+
942
+ ```ts
943
+ const intent = await client.paymentIntents.createPay({
944
+ destination: merchantAccount,
945
+ asset: usdc, // no amount → the wallet asks the user
946
+ msg: 'Support us 💜',
947
+ });
948
+ // browser: await new WebClient().pay(intent, { amount: enteredAmount });
949
+ ```
950
+
951
+ ## 3. Idempotent webhook handling
952
+
953
+ ```ts
954
+ const processed = new Set<string>(); // use your DB in production
955
+ client.webhooks.on('event', (event) => {
956
+ if (processed.has(event.id)) return; // event.id is stable — dedupe on it
957
+ processed.add(event.id);
958
+ handle(event);
959
+ });
960
+ ```
961
+
962
+ ## 4. Reconcile a payment server-side
963
+
964
+ ```ts
965
+ // You received a txHash out-of-band (e.g. polled the browser). Finalize it:
966
+ const outcome = await client.paymentIntents.validate(intentId, { txHash });
967
+ if (!outcome.valid) {
968
+ console.warn('payment not valid:', outcome.reason); // amount/destination/memo mismatch
969
+ }
970
+ ```
971
+
972
+ ## 5. Testnet vs mainnet
973
+
974
+ ```ts
975
+ import { Assets, TestnetAssets } from '@cosmosapp/pay_sdk';
976
+ // dv_ key → testnet → use TestnetAssets.USDC
977
+ // prod_ key → mainnet → use Assets.USDC
978
+ const asset = apiKey.startsWith('prod_') ? Assets.USDC : TestnetAssets.USDC;
979
+ ```
980
+
981
+ ## 6. Catalog: products + customers
982
+
983
+ ```ts
984
+ const product = await client.products.create({ name: 'Pro', amount: '49.00', assetCode: 'USDC', kind: 'recurring' });
985
+ const customer = await client.customers.create({ name: 'Acme', email: 'billing@acme.com', account: 'G...' });
986
+ // then create intents referencing the customer's account as destination/source.
987
+ ```