@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.
@@ -0,0 +1,977 @@
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, Assets } 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
+ asset: Assets.USDC, // fills the verified mainnet issuer for you
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, Assets } 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
+ asset: Assets.USDC,
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 } from '@cosmosapp/pay_sdk';
274
+
275
+ // pay (no source)
276
+ const pay = await client.paymentIntents.createPay({
277
+ destination: 'G...', // required — payee (or an address-book name)
278
+ amount: '10', // optional — omit for an open amount (donations)
279
+ asset: Assets.USDC, // typed asset → fills assetCode + verified issuer
280
+ // assetCode: 'USDC', assetIssuer: 'G...', // …or set them explicitly
281
+ // omit asset entirely for native lumens (XLM)
282
+ memo: '123456789', // optional MEMO_ID (uint64) — auto-generated if omitted
283
+ msg: 'Order #24', // optional, ≤ 300 chars, shown in the wallet
284
+ callback: 'url:https://...', // optional SEP-7 callback for the signed XDR
285
+ });
286
+
287
+ // tx (source known)
288
+ const tx = await client.paymentIntents.createTx({
289
+ source: 'G...PAYER', // required (extra vs pay)
290
+ destination: 'G...MERCHANT',
291
+ amount: '25.5',
292
+ });
293
+ console.log(tx.xdr, tx.uri, tx.qr);
294
+ ```
295
+
296
+ > Amounts are **decimal strings**, max 7 decimals. Asset issuers are
297
+ > network-specific (mainnet vs testnet).
298
+
299
+ ## Fetch / list
300
+
301
+ ```ts
302
+ const intent = await client.paymentIntents.fetch('pi_123');
303
+
304
+ const page = await client.paymentIntents.list({
305
+ status: 'SUCCEEDED', // optional filter (PaymentIntentStatus)
306
+ take: 50, // page size, max 100, default 20
307
+ skip: 0, // offset
308
+ });
309
+ // page → { items: PaymentIntent[], total, take, skip }
310
+ ```
311
+
312
+ ## Update / cancel / delete
313
+
314
+ ```ts
315
+ await intent.edit({ reference: 'order_1234' }); // status / txHash / reference
316
+ await intent.cancel(); // → status CANCELLED
317
+ await intent.delete();
318
+ // manager forms: client.paymentIntents.update(id, {...}) / .delete(id)
319
+ ```
320
+
321
+ ## Validate (finalize)
322
+
323
+ ```ts
324
+ const outcome = await intent.validate('<txHash>');
325
+ // → { valid, status, reason, paymentIntent }
326
+ if (outcome.valid) console.log('settled', outcome.status);
327
+ // manager form: client.paymentIntents.validate(id, { txHash })
328
+ ```
329
+
330
+ Validation checks tx success + destination + amount + memo, finalizes the status
331
+ server-side, and fires the webhook.
332
+
333
+ ## Structure accessors (on a `PaymentIntent`)
334
+
335
+ `id`, `kind`, `status`, `network`, `source`, `destination`, `amount`, `asset`,
336
+ `assetIssuer`, `memo`, `msg`, `callback`, `xdr`, `uri`, `qr`, `txHash`,
337
+ `reference`, `createdAt`, `updatedAt`. Helpers: `isTx`, `isPay`, `isSucceeded`,
338
+ `isPending`, `assetLabel` (`'XLM'` for native). Methods: `fetch()`, `edit()`,
339
+ `validate(txHash)`, `cancel()`, `delete()`, `toJSON()`.
340
+
341
+ ---
342
+
343
+ # Web client (browser wallets)
344
+
345
+ `@cosmosapp/pay_sdk/web` *completes* an intent in the user's browser. Stellar
346
+ wallets don't ingest SEP-7 `web+stellar:` URIs from a dapp, so the web client
347
+ auto-detects the wallet, adapts the intent into a transaction, signs and submits.
348
+
349
+ ```bash
350
+ npm install @cosmosapp/pay_sdk @stellar/stellar-sdk
351
+ ```
352
+
353
+ ## One-call happy path
354
+
355
+ ```ts
356
+ import { WebClient } from '@cosmosapp/pay_sdk/web';
357
+
358
+ const webClient = new WebClient(); // auto-detects the wallet
359
+ const result = await webClient.pay(intent); // intent = payload/instance/URI string
360
+
361
+ result.wallet; // 'freighter' | 'xbull' | 'rabet' | 'lobstr' | 'albedo' | …
362
+ result.account; // the G... account that signed
363
+ result.txHash; // on-chain transaction hash
364
+ result.submitted; // true
365
+ ```
366
+
367
+ Report `result.txHash` to your server and finalize with `intent.validate(txHash)`.
368
+
369
+ ## Supported wallets
370
+
371
+ Auto-detected (inject a browser global, zero config):
372
+
373
+ | Wallet | id | Detection |
374
+ | ------ | -- | --------- |
375
+ | Freighter | `freighter` | `window.freighterApi` |
376
+ | xBull | `xbull` | `window.xBullSDK` |
377
+ | Rabet | `rabet` | `window.rabet` |
378
+
379
+ Enabled by passing their library (no reliable global):
380
+
381
+ | Wallet | id | Enable |
382
+ | ------ | -- | ------ |
383
+ | Albedo | `albedo` | `new WebClient({ albedo })` — `import albedo from '@albedo-link/intent'` |
384
+ | LOBSTR | `lobstr` | `new WebClient({ lobstr })` — `import * as lobstr from '@lobstrco/signer-extension-api'` |
385
+
386
+ ## Inspect & choose
387
+
388
+ ```ts
389
+ import { Wallets } from '@cosmosapp/pay_sdk/web';
390
+
391
+ const wallets = await webClient.getAvailableWallets(); // [{ id, name, available }]
392
+ const { wallet, address, network } = await webClient.connect(); // just connect
393
+ await webClient.pay(intent, { wallet: Wallets.XBULL }); // pin for one call
394
+ const pinned = new WebClient({ preferredWallets: [Wallets.XBULL, Wallets.FREIGHTER] });
395
+ ```
396
+
397
+ ## `pay()` options & variations
398
+
399
+ ```ts
400
+ await webClient.pay(intent, { amount: '5' }); // open-amount intent
401
+ await webClient.pay(intent, { sign: true }); // sign WITHOUT submitting → { signedXdr }
402
+ await webClient.pay(intent, { submit: false }); // also skips submission
403
+ await webClient.pay(intent, { wallet: 'xbull' });
404
+
405
+ // Inspect the tx before prompting the wallet:
406
+ const { xdr, source, network } = await webClient.buildTransaction(intent);
407
+ ```
408
+
409
+ `pay` vs `tx`: for **pay** intents the client builds a payment from the connected
410
+ account (loads sequence from Horizon, adds op + memo, fee, timebounds). For **tx**
411
+ intents it signs the returned XDR as-is (throws if the connected wallet isn't the
412
+ intent's `source`).
413
+
414
+ ## Network
415
+
416
+ Inferred from the intent (`network` / SEP-7 `network_passphrase`). Override if you
417
+ self-host Horizon: `new WebClient({ network: 'testnet', horizonUrl: '...' })`.
418
+
419
+ ## Custom wallet adapter
420
+
421
+ ```ts
422
+ import { WebClient } from '@cosmosapp/pay_sdk/web';
423
+
424
+ const myWallet = {
425
+ id: 'my-wallet',
426
+ name: 'My Wallet',
427
+ async isAvailable() { return Boolean(globalThis.myWallet); },
428
+ async getPublicKey() { return globalThis.myWallet.getAddress(); },
429
+ async signTransaction(xdr, { networkPassphrase }) {
430
+ return globalThis.myWallet.sign(xdr, networkPassphrase);
431
+ },
432
+ };
433
+ const wc = new WebClient();
434
+ wc.registerWallet(myWallet, /* prepend */ true);
435
+ ```
436
+
437
+ ## Dependency injection (SSR / bundle control)
438
+
439
+ ```ts
440
+ import * as StellarSdk from '@stellar/stellar-sdk';
441
+ import freighter from '@stellar/freighter-api';
442
+ const wc = new WebClient({ stellarSdk: StellarSdk, freighter });
443
+ ```
444
+
445
+ ## Direct API (trusted environments only)
446
+
447
+ > ⚠️ Ships your API key to the browser. Only for prototypes/internal tools with a
448
+ > scoped testnet `dv_` key. For production, create/validate on your server.
449
+
450
+ ```ts
451
+ const wc = new WebClient({ apiKey: 'dv_test_only' });
452
+ const intent = await wc.createPay({ destination: 'G...', amount: '10' });
453
+ const result = await wc.pay(intent);
454
+ const outcome = await wc.validate(intent.id, result.txHash);
455
+ ```
456
+
457
+ ---
458
+
459
+ # Webhooks
460
+
461
+ Two halves: **registering** endpoints (server CRUD) and **receiving** events
462
+ (the listener + handlers). `client.webhooks` does both.
463
+
464
+ ## Register & manage endpoints
465
+
466
+ ```ts
467
+ import { WebhookEventType } from '@cosmosapp/pay_sdk';
468
+
469
+ const endpoint = await client.webhooks.create({
470
+ url: 'https://me.example.com/hooks/cosmos',
471
+ description: 'Production events',
472
+ eventTypes: [
473
+ WebhookEventType.PaymentIntentSucceeded,
474
+ WebhookEventType.PaymentIntentFailed,
475
+ ], // omit/empty → receive ALL events
476
+ });
477
+ console.log(endpoint.secret); // whsec_… — returned ONCE, store it now!
478
+
479
+ await endpoint.disable(); // pause
480
+ await endpoint.enable(); // resume
481
+ await endpoint.edit({ url: 'https://new...' });
482
+ await endpoint.ping(); // send a test event
483
+ const rotated = await endpoint.rotateSecret(); // new instance carries new secret
484
+ await endpoint.delete();
485
+
486
+ // audit trail + manual redelivery
487
+ const deliveries = await endpoint.fetchDeliveries({ status: 'FAILED', take: 50 });
488
+ for (const d of deliveries.items) await d.redeliver();
489
+ ```
490
+
491
+ Manager forms exist too: `client.webhooks.list()`, `.fetch(id)`,
492
+ `.update(id, {...})`, `.delete(id)`, `.rotateSecret(id)`, `.ping(id)`,
493
+ `.fetchDeliveries(id, {...})`, `.redeliver(id, deliveryId)`.
494
+
495
+ ## Receive events — `client.webhooks.on(...)`
496
+
497
+ Subscribe with the raw type, the camelCase alias, or `event` for all:
498
+
499
+ ```ts
500
+ client.webhooks.on('paymentIntentSucceeded', (event) => {
501
+ console.log('Paid!', event.data.id, event.data.amount);
502
+ });
503
+ client.webhooks.on('PAYMENT_INTENT_FAILED', (event) => { /* ... */ });
504
+ client.webhooks.on('event', (event) => console.log(event.type));
505
+ ```
506
+
507
+ Set the signing secret on the client (or pass `{ secret }` to the handler):
508
+
509
+ ```ts
510
+ const client = new Client({
511
+ apiKey: process.env.COSMOS_PAY_API_KEY,
512
+ webhookSecret: process.env.COSMOS_WEBHOOK_SECRET, // whsec_…
513
+ });
514
+ ```
515
+
516
+ ### Node.js `http` (zero deps)
517
+
518
+ ```ts
519
+ import { createServer } from 'node:http';
520
+ createServer(client.webhooks.createHandler()).listen(4242);
521
+ // verifies signature → emits event → replies 200 (or 400 on bad signature)
522
+ ```
523
+
524
+ ### Express
525
+
526
+ ```ts
527
+ import express from 'express';
528
+ const app = express();
529
+ app.post(
530
+ '/hooks/cosmos',
531
+ express.raw({ type: '*/*' }), // MUST be the RAW body
532
+ client.webhooks.middleware(),
533
+ (req, res) => res.sendStatus(200), // req.cosmosEvent is the verified event
534
+ );
535
+ ```
536
+
537
+ ## Verify signatures manually
538
+
539
+ The dispatcher signs each POST with `X-Cosmos-Signature: t=<unixSeconds>,v1=<hmacSha256>`.
540
+
541
+ ```ts
542
+ import { Webhooks } from '@cosmosapp/pay_sdk';
543
+
544
+ Webhooks.verify(rawBody, header, secret); // → true or throws
545
+ const event = Webhooks.constructEvent(rawBody, header, secret); // verify + parse
546
+ // both accept { toleranceSeconds } (default 300s replay window; 0 disables)
547
+
548
+ // or on a client (also emits to your on(...) listeners):
549
+ client.webhooks.process(rawBody, header, { secret });
550
+ ```
551
+
552
+ Bad signatures throw `WebhookSignatureError`.
553
+
554
+ ## Event payload shape
555
+
556
+ ```ts
557
+ interface WebhookEvent {
558
+ id: string; // stable — use for idempotency
559
+ type: WebhookEventType;
560
+ createdAt: string;
561
+ data: PaymentIntentData;
562
+ }
563
+ ```
564
+
565
+ Event types: `PAYMENT_INTENT_CREATED`, `PAYMENT_INTENT_UPDATED`,
566
+ `PAYMENT_INTENT_SUCCEEDED`, `PAYMENT_INTENT_FAILED`, `PAYMENT_INTENT_CANCELLED`,
567
+ `PAYMENT_INTENT_DELETED`.
568
+
569
+ ---
570
+
571
+ # Products & customers
572
+
573
+ ## Products / prices — `client.products`
574
+
575
+ ```ts
576
+ import { ProductKind } from '@cosmosapp/pay_sdk';
577
+
578
+ const product = await client.products.create({
579
+ name: 'Pro plan — monthly',
580
+ description: 'Priority support included.', // optional
581
+ amount: '49.00', // optional — omit for customer-set amount
582
+ assetCode: 'USDC', // optional — omit for native XLM
583
+ kind: ProductKind.Recurring, // 'recurring' | 'one_time' | 'link'
584
+ reference: 'sku_pro_monthly', // optional
585
+ });
586
+
587
+ await client.products.list();
588
+ await client.products.fetch(product.id);
589
+ await product.edit({ amount: '59.00' });
590
+ await product.deactivate(); // active = false
591
+ await product.activate(); // active = true
592
+ await product.delete();
593
+ ```
594
+
595
+ `Product` accessors: `id`, `name`, `description`, `amount`, `asset`, `assetLabel`,
596
+ `kind`, `active`, `reference`, `createdAt`, `updatedAt`.
597
+
598
+ ## Customers — `client.customers`
599
+
600
+ ```ts
601
+ const customer = await client.customers.create({
602
+ name: 'Acme Inc.',
603
+ email: 'billing@acme.com', // optional
604
+ alias: 'acme', // optional
605
+ account: 'G...', // optional Stellar account to associate
606
+ reference: 'crm_4821', // optional
607
+ });
608
+
609
+ await customer.edit({ note: 'VIP, net-30' });
610
+ await client.customers.fetch(customer.id);
611
+ await customer.delete();
612
+
613
+ // list() includes payment stats per customer:
614
+ const customers = await client.customers.list();
615
+ for (const c of customers) {
616
+ console.log(c.name, c.payments, c.succeeded, c.total);
617
+ }
618
+ ```
619
+
620
+ `Customer` accessors: `id`, `consumerId`, `name`, `alias`, `note`, `email`,
621
+ `account`, `reference`, `createdAt`, `updatedAt`, plus list-only stats
622
+ `payments`, `succeeded`, `total` (null outside `list()`).
623
+
624
+ ---
625
+
626
+ # Analytics & health
627
+
628
+ ## Analytics (read-only) — `client.analytics`
629
+
630
+ ```ts
631
+ const summary = await client.analytics.summary(); // totals, volume, webhook health, 30-day series
632
+ const balances = await client.analytics.balances(); // settled + pending per asset
633
+ const apiLogs = await client.analytics.apiLogs(); // recent API requests
634
+ const hookLogs = await client.analytics.webhookLogs(); // recent webhook deliveries
635
+ ```
636
+
637
+ `summary()` → `{ totals: { all, succeeded, pending, submitted, failed, cancelled,
638
+ expired, successRate }, volume: [...], webhooks: { endpoints, deliveries, ... } }`.
639
+
640
+ `balances()` → `{ data: [{ asset, amount, pending, count }], total }`
641
+ where `amount`/`pending` are decimal strings and `count` is the number of payments.
642
+
643
+ ## Health (public probes) — `client.health`
644
+
645
+ ```ts
646
+ await client.health.liveness(); // → true when the service is up
647
+ const ready = await client.health.readiness(); // → { status, info, details } (checks the DB)
648
+ ```
649
+
650
+ These routes don't require an authenticated consumer.
651
+
652
+ ---
653
+
654
+ # Typed assets, wallets & addresses
655
+
656
+ Small typed catalogs so you never paste the wrong issuer or a magic string. Plain
657
+ strings still work everywhere. Exported from **both** entry points
658
+ (`@cosmosapp/pay_sdk` and `@cosmosapp/pay_sdk/web`).
659
+
660
+ ## Assets
661
+
662
+ ```ts
663
+ import { Assets, TestnetAssets, defineAsset, resolveAsset, isNativeAsset } from '@cosmosapp/pay_sdk';
664
+
665
+ Assets.XLM; // native lumens
666
+ Assets.USDC; // { code: 'USDC', issuer: 'GA5Z…' } (Circle, mainnet — verified)
667
+ Assets.EURC; // { code: 'EURC', issuer: 'GDHU…' }
668
+
669
+ // Custom asset (issuer/contract validated):
670
+ const AQUA = defineAsset({ code: 'AQUA', issuer: 'GBNZ…', name: 'Aquarius' });
671
+
672
+ await client.paymentIntents.createPay({ destination: 'G...', amount: '5', asset: AQUA });
673
+
674
+ // Plain code + issuer also works:
675
+ await client.paymentIntents.createPay({ destination: 'G...', amount: '5', assetCode: 'USDC', assetIssuer: 'G...' });
676
+ ```
677
+
678
+ > ⚠️ Issuers are **network-specific**. `Assets.*` = mainnet; use `TestnetAssets.*`
679
+ > (e.g. `TestnetAssets.USDC`) for testnet, matched to your `dv_` key.
680
+
681
+ Helpers: `resolveAsset(ref)` → `{ code, issuer? }`; `isNativeAsset(ref)` → boolean.
682
+
683
+ ## Wallets
684
+
685
+ ```ts
686
+ import { Wallets } from '@cosmosapp/pay_sdk/web';
687
+ Wallets.FREIGHTER; Wallets.XBULL; Wallets.RABET; Wallets.LOBSTR; Wallets.ALBEDO;
688
+
689
+ const wc = new WebClient({ preferredWallets: [Wallets.XBULL, Wallets.FREIGHTER] });
690
+ await wc.pay(intent, { wallet: Wallets.FREIGHTER });
691
+ ```
692
+
693
+ ## Address book
694
+
695
+ ```ts
696
+ import { addresses, resolveAddress, isStellarAddress, isMuxedAddress, isContractAddress, isAddress, assertAddress } from '@cosmosapp/pay_sdk';
697
+
698
+ addresses.define('merchant', 'GC...PAYOUT');
699
+ await client.paymentIntents.createPay({ destination: 'merchant', amount: '10' });
700
+
701
+ resolveAddress('merchant'); // → 'GC...PAYOUT' (unknown values pass through unchanged)
702
+ isStellarAddress('GC...'); // true
703
+ isMuxedAddress('MA...'); // true
704
+ isContractAddress('CA...'); // true
705
+ isAddress('merchant'); // true
706
+ assertAddress(value); // throws on an invalid value
707
+ ```
708
+
709
+ Raw `G…`, muxed `M…`, contract `C…` and federation addresses keep working as
710
+ plain strings.
711
+
712
+ ---
713
+
714
+ # Error handling & observability
715
+
716
+ ## Errors
717
+
718
+ ```ts
719
+ import { CosmosPayAPIError, CosmosPayRequestError } from '@cosmosapp/pay_sdk';
720
+
721
+ try {
722
+ await client.paymentIntents.fetch('missing');
723
+ } catch (err) {
724
+ if (err instanceof CosmosPayAPIError) {
725
+ // server responded with an error status
726
+ console.error(err.status, err.code, err.body); // e.g. 404
727
+ } else if (err instanceof CosmosPayRequestError) {
728
+ // no usable response — network / TLS / timeout / offline
729
+ console.error('Network/timeout:', err.cause);
730
+ } else {
731
+ throw err;
732
+ }
733
+ }
734
+ ```
735
+
736
+ - `CosmosPayAPIError` — the API replied with 4xx/5xx. Fields: `status`, `code`, `body`.
737
+ - `CosmosPayRequestError` — the request never completed. Field: `cause`.
738
+ - Web client adds: `CosmosPayWebError`, `WalletNotFoundError`, `WalletError`
739
+ (user rejected / locked), `StellarSdkRequiredError`, `IntentError`. The API
740
+ error classes are re-exported from `/web` too, so `catch` works across entries.
741
+ - Webhook signature failures throw `WebhookSignatureError`.
742
+
743
+ ### Retries
744
+
745
+ Transient failures (network errors, `408`, `429`, `5xx`) are retried
746
+ automatically — default **2** retries, honoring `Retry-After`. Tune via
747
+ `new Client({ retries, timeout })`.
748
+
749
+ ## Observability
750
+
751
+ The client re-emits REST telemetry:
752
+
753
+ ```ts
754
+ client.on('request', ({ method, url, attempt }) => {});
755
+ client.on('response', ({ method, url, status, attempt }) => {});
756
+ client.on('rateLimited', ({ method, url, attempt }) => {});
757
+ client.on('debug', (message) => {});
758
+ ```
759
+
760
+ Wire these into your logger/APM to trace or meter every request.
761
+
762
+ ---
763
+
764
+ # Configuration reference
765
+
766
+ ```ts
767
+ new Client({
768
+ apiKey: 'prod_xxx', // required — the only thing you normally set
769
+ webhookSecret: 'whsec_...', // default secret for the webhook listener
770
+ timeout: 30_000, // ms (default 30000)
771
+ retries: 2, // network errors / 429 / 5xx (default 2)
772
+ headers: { 'X-Trace': 'abc' }, // extra headers on every request
773
+ fetch: customFetch, // custom fetch implementation
774
+
775
+ // Advanced / internal — pre-filled from Client.shared, rarely overridden:
776
+ baseURL: 'https://api.cosmospay.lat/cosmos-api', // gateway URL (default)
777
+ version: 'v1', // route prefix
778
+ gatewaySecret: '...', // direct access (X-Gateway-Secret), local dev
779
+ consumerUsername: '...', // direct access (X-Consumer-Username), local dev
780
+ });
781
+ ```
782
+
783
+ ## Environment variables (convention)
784
+
785
+ The SDK reads nothing from the environment itself — you pass values in. Common
786
+ convention used across the docs/examples:
787
+
788
+ | Var | Used for |
789
+ | --- | -------- |
790
+ | `COSMOS_PAY_API_KEY` | `new Client({ apiKey })` |
791
+ | `COSMOS_WEBHOOK_SECRET` | `new Client({ webhookSecret })` / handler `{ secret }` |
792
+
793
+ ## Self-hosting / staging
794
+
795
+ ```ts
796
+ // Once at startup, for every client:
797
+ Client.shared.baseURL = 'https://gateway.your-domain.com';
798
+
799
+ // Or per-client, bypassing the gateway in local dev:
800
+ new Client({
801
+ apiKey: 'x',
802
+ baseURL: 'http://localhost:3000',
803
+ gatewaySecret: process.env.APISIX_GATEWAY_SECRET,
804
+ consumerUsername: 'cosmos_demo',
805
+ });
806
+ ```
807
+
808
+ ---
809
+
810
+ # Types & enums reference
811
+
812
+ Everything is fully typed. Import option/entity types and the const-enums directly
813
+ from `@cosmosapp/pay_sdk` (or `/web`).
814
+
815
+ ```ts
816
+ import {
817
+ Client,
818
+ PaymentIntentStatus,
819
+ PaymentIntentKind,
820
+ WebhookEventType,
821
+ WebhookDeliveryStatus,
822
+ ProductKind,
823
+ type CreatePayPaymentIntentOptions,
824
+ type CreateTxPaymentIntentOptions,
825
+ type PaymentIntentData,
826
+ } from '@cosmosapp/pay_sdk';
827
+ ```
828
+
829
+ ## Enums (const objects — usable as values and types)
830
+
831
+ ```ts
832
+ PaymentIntentStatus = { Pending:'PENDING', Submitted:'SUBMITTED', Succeeded:'SUCCEEDED',
833
+ Failed:'FAILED', Cancelled:'CANCELLED', Expired:'EXPIRED' }
834
+ PaymentIntentKind = { Tx:'TX', Pay:'PAY' }
835
+ WebhookEventType = { PaymentIntentCreated:'PAYMENT_INTENT_CREATED',
836
+ PaymentIntentUpdated:'PAYMENT_INTENT_UPDATED',
837
+ PaymentIntentSucceeded:'PAYMENT_INTENT_SUCCEEDED',
838
+ PaymentIntentFailed:'PAYMENT_INTENT_FAILED',
839
+ PaymentIntentCancelled:'PAYMENT_INTENT_CANCELLED',
840
+ PaymentIntentDeleted:'PAYMENT_INTENT_DELETED' }
841
+ WebhookDeliveryStatus = { Pending:'PENDING', Succeeded:'SUCCEEDED', Failed:'FAILED' }
842
+ ProductKind = { Recurring:'recurring', OneTime:'one_time', Link:'link' }
843
+ ```
844
+
845
+ ## Option types (inputs)
846
+
847
+ ```ts
848
+ interface CreatePayPaymentIntentOptions {
849
+ destination: string; amount?: string; asset?: AssetRef;
850
+ assetCode?: string; assetIssuer?: string; memo?: string; msg?: string; callback?: string;
851
+ }
852
+ interface CreateTxPaymentIntentOptions {
853
+ source: string; destination: string; amount: string; asset?: AssetRef;
854
+ assetCode?: string; assetIssuer?: string; memo?: string; msg?: string; callback?: string;
855
+ }
856
+ interface UpdatePaymentIntentOptions { status?: PaymentIntentStatus; txHash?: string; reference?: string; }
857
+ interface ListPaymentIntentsOptions { status?: PaymentIntentStatus; take?: number; skip?: number; }
858
+ interface ValidatePaymentIntentOptions { txHash: string; }
859
+
860
+ interface CreateWebhookEndpointOptions { url: string; description?: string; eventTypes?: WebhookEventType[]; }
861
+ interface UpdateWebhookEndpointOptions { url?: string; description?: string; enabled?: boolean; eventTypes?: WebhookEventType[]; }
862
+ interface ListWebhookDeliveriesOptions { status?: WebhookDeliveryStatus; take?: number; skip?: number; }
863
+
864
+ interface CreateProductOptions { name: string; description?: string; amount?: string; assetCode?: string; kind?: ProductKind; active?: boolean; reference?: string; }
865
+ type UpdateProductOptions = Partial<CreateProductOptions>;
866
+
867
+ interface CreateCustomerOptions { name: string; alias?: string; note?: string; email?: string; account?: string; reference?: string; }
868
+ type UpdateCustomerOptions = Partial<CreateCustomerOptions>;
869
+ ```
870
+
871
+ ## Entity payloads (outputs)
872
+
873
+ - `PaymentIntentData` — `id, kind, status, network, source, destination, amount,
874
+ asset, assetIssuer, memo, msg, callback, xdr, uri, qr, txHash, reference,
875
+ createdAt, updatedAt`.
876
+ - `WebhookEndpointData` — `id, url, description, enabled, eventTypes, createdAt,
877
+ updatedAt` (+ `secret` on create/rotate only).
878
+ - `WebhookEvent<T = PaymentIntentData>` — `{ id, type, createdAt, data }`.
879
+ - `ProductData` — `id, name, description, amount, asset, kind, active, reference,
880
+ createdAt, updatedAt`.
881
+ - `CustomerData` — `id, consumerId, name, alias, note, email, account, reference,
882
+ createdAt, updatedAt` (+ list-only `payments, succeeded, total`).
883
+ - `AnalyticsBalancesData` — `{ data: { asset, amount, pending, count }[], total }`.
884
+ - `ValidationOutcomeData` — `{ valid, status, reason?, paymentIntent? }`.
885
+
886
+ Pagination wrappers (`list` / `fetchDeliveries`) return
887
+ `{ items, total, take, skip }`.
888
+
889
+ ---
890
+
891
+ # Recipes
892
+
893
+ Copy-paste end-to-end patterns. All server snippets assume:
894
+
895
+ ```ts
896
+ import { Client, Assets } from '@cosmosapp/pay_sdk';
897
+ const client = new Client({ apiKey: process.env.COSMOS_PAY_API_KEY });
898
+ ```
899
+
900
+ ## 1. Checkout (server creates, browser pays, webhook confirms)
901
+
902
+ ```ts
903
+ // server: create the intent for an order
904
+ export async function startCheckout(orderId: string, total: string) {
905
+ const intent = await client.paymentIntents.createPay({
906
+ destination: process.env.MERCHANT_ACCOUNT,
907
+ amount: total,
908
+ asset: Assets.USDC,
909
+ reference: orderId, // ties the intent to your order
910
+ msg: `Order ${orderId}`,
911
+ });
912
+ return intent.toJSON(); // → send to the browser
913
+ }
914
+ ```
915
+
916
+ ```ts
917
+ // browser: complete it with the user's wallet
918
+ import { WebClient } from '@cosmosapp/pay_sdk/web';
919
+ const { txHash } = await new WebClient().pay(intentPayload);
920
+ await fetch('/api/confirm', { method: 'POST', body: JSON.stringify({ id: intentPayload.id, txHash }) });
921
+ ```
922
+
923
+ ```ts
924
+ // server: fulfill on the webhook (don't trust the browser alone)
925
+ client.webhooks.on('paymentIntentSucceeded', async (event) => {
926
+ await markOrderPaid(event.data.reference, event.data.id);
927
+ });
928
+ ```
929
+
930
+ ## 2. Donation / tip jar (open amount)
931
+
932
+ ```ts
933
+ const intent = await client.paymentIntents.createPay({
934
+ destination: process.env.MERCHANT_ACCOUNT,
935
+ asset: Assets.USDC, // no amount → the wallet asks the user
936
+ msg: 'Support us 💜',
937
+ });
938
+ // browser: await new WebClient().pay(intent, { amount: enteredAmount });
939
+ ```
940
+
941
+ ## 3. Idempotent webhook handling
942
+
943
+ ```ts
944
+ const processed = new Set<string>(); // use your DB in production
945
+ client.webhooks.on('event', (event) => {
946
+ if (processed.has(event.id)) return; // event.id is stable — dedupe on it
947
+ processed.add(event.id);
948
+ handle(event);
949
+ });
950
+ ```
951
+
952
+ ## 4. Reconcile a payment server-side
953
+
954
+ ```ts
955
+ // You received a txHash out-of-band (e.g. polled the browser). Finalize it:
956
+ const outcome = await client.paymentIntents.validate(intentId, { txHash });
957
+ if (!outcome.valid) {
958
+ console.warn('payment not valid:', outcome.reason); // amount/destination/memo mismatch
959
+ }
960
+ ```
961
+
962
+ ## 5. Testnet vs mainnet
963
+
964
+ ```ts
965
+ import { Assets, TestnetAssets } from '@cosmosapp/pay_sdk';
966
+ // dv_ key → testnet → use TestnetAssets.USDC
967
+ // prod_ key → mainnet → use Assets.USDC
968
+ const asset = process.env.COSMOS_PAY_API_KEY.startsWith('prod_') ? Assets.USDC : TestnetAssets.USDC;
969
+ ```
970
+
971
+ ## 6. Catalog: products + customers
972
+
973
+ ```ts
974
+ const product = await client.products.create({ name: 'Pro', amount: '49.00', assetCode: 'USDC', kind: 'recurring' });
975
+ const customer = await client.customers.create({ name: 'Acme', email: 'billing@acme.com', account: 'G...' });
976
+ // then create intents referencing the customer's account as destination/source.
977
+ ```