@alytegen/sdk 0.0.0-stage → 0.3.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/LICENSE +21 -0
- package/QUICKSTART.md +70 -0
- package/README.md +92 -2
- package/dist/agent.d.ts +68 -0
- package/dist/agent.js +59 -0
- package/dist/http.d.ts +23 -0
- package/dist/http.js +53 -0
- package/dist/index.d.ts +6 -0
- package/dist/index.js +5 -0
- package/dist/merchant.d.ts +154 -0
- package/dist/merchant.js +106 -0
- package/dist/onPurchase.d.ts +133 -0
- package/dist/onPurchase.js +92 -0
- package/dist/types.d.ts +188 -0
- package/dist/types.js +5 -0
- package/dist/webhookVerify.d.ts +11 -0
- package/dist/webhookVerify.js +23 -0
- package/examples/agent-buy.ts +47 -0
- package/examples/merchant-onboard.ts +48 -0
- package/examples/reference-merchant/server.ts +190 -0
- package/package.json +51 -4
|
@@ -0,0 +1,190 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* THE REFERENCE INTEGRATION — a complete, runnable merchant server.
|
|
3
|
+
*
|
|
4
|
+
* It is deliberately one file and has no dependencies beyond the SDK and Node,
|
|
5
|
+
* so you can read the whole integration in one sitting and then delete the
|
|
6
|
+
* parts you don't need.
|
|
7
|
+
*
|
|
8
|
+
* It covers exactly the three things a working integration must do:
|
|
9
|
+
*
|
|
10
|
+
* 1. HAND OFF to the buyer → GET /buy/:tierId
|
|
11
|
+
* 2. RECEIVE the purchase → POST /hooks/alyte (signed, at-least-once)
|
|
12
|
+
* 3. FULFIL exactly once → issueTickets(), inside ONE transaction
|
|
13
|
+
*
|
|
14
|
+
* ...and the fourth thing you will need the first time something goes wrong:
|
|
15
|
+
*
|
|
16
|
+
* 4. DIAGNOSE without asking us → GET /admin/why/:watchId
|
|
17
|
+
*
|
|
18
|
+
* Run it:
|
|
19
|
+
*
|
|
20
|
+
* ALYTE_BASE_URL=https://alyte-sandbox-f365cfb3ma-ey.a.run.app \
|
|
21
|
+
* ALYTE_API_TOKEN=alyte_sk_… \
|
|
22
|
+
* ALYTE_WEBHOOK_SECRET=whsec_… \
|
|
23
|
+
* npx tsx server.ts
|
|
24
|
+
*
|
|
25
|
+
* The store here is an in-memory Map standing in for your database. It is the
|
|
26
|
+
* ONLY part you must replace — and §3 explains exactly why the shape matters.
|
|
27
|
+
*/
|
|
28
|
+
import { createServer, type IncomingMessage, type ServerResponse } from 'node:http';
|
|
29
|
+
import { createWebhookHandler, type PaymentSettled, type WatchFailed } from '@alytegen/sdk';
|
|
30
|
+
|
|
31
|
+
const BASE_URL = required('ALYTE_BASE_URL');
|
|
32
|
+
const API_TOKEN = required('ALYTE_API_TOKEN');
|
|
33
|
+
const WEBHOOK_SECRET = required('ALYTE_WEBHOOK_SECRET');
|
|
34
|
+
const PORT = Number(process.env.PORT ?? 8099);
|
|
35
|
+
|
|
36
|
+
function required(name: string): string {
|
|
37
|
+
const v = process.env[name];
|
|
38
|
+
if (!v) { console.error(`Missing ${name}`); process.exit(1); }
|
|
39
|
+
return v;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
// ─────────────────────────────────────────────────────────────────────────────
|
|
43
|
+
// Your database, stubbed. Replace with the real thing — keep the SHAPE.
|
|
44
|
+
// ─────────────────────────────────────────────────────────────────────────────
|
|
45
|
+
const tickets = new Map<string, { tierId: string; quantity: number; buyerRef: string }>();
|
|
46
|
+
const handledEvents = new Set<string>();
|
|
47
|
+
const notifications: Array<{ buyerRef: string; message: string }> = [];
|
|
48
|
+
|
|
49
|
+
/**
|
|
50
|
+
* §3 · FULFILMENT, EXACTLY ONCE.
|
|
51
|
+
*
|
|
52
|
+
* Deliveries are at-least-once: we retry until we see a 2xx, so this function
|
|
53
|
+
* CAN be called twice for one sale — most often when your handler succeeded but
|
|
54
|
+
* the response never got back to us.
|
|
55
|
+
*
|
|
56
|
+
* The dangerous window is not between deliveries, it is inside this function.
|
|
57
|
+
* Issue the ticket and crash before recording "handled" → a retry double-issues.
|
|
58
|
+
* Record first and crash → the buyer paid and got nothing.
|
|
59
|
+
*
|
|
60
|
+
* The only fix is to make both facts commit together. In real code that is one
|
|
61
|
+
* database transaction:
|
|
62
|
+
*
|
|
63
|
+
* await db.transaction(async (tx) => {
|
|
64
|
+
* const claimed = await tx.query(
|
|
65
|
+
* `INSERT INTO handled_events (event_id) VALUES ($1)
|
|
66
|
+
* ON CONFLICT DO NOTHING RETURNING event_id`, [eventId]);
|
|
67
|
+
* if (!claimed.rowCount) return; // a retry — already fulfilled
|
|
68
|
+
* await tx.query(`INSERT INTO tickets (...) VALUES (...)`);
|
|
69
|
+
* });
|
|
70
|
+
*
|
|
71
|
+
* Claim FIRST inside the transaction, then do the work. If anything throws, the
|
|
72
|
+
* whole thing rolls back and the retry finds the claim gone and tries again.
|
|
73
|
+
*/
|
|
74
|
+
function issueTickets(eventId: string, p: PaymentSettled): 'issued' | 'already-issued' {
|
|
75
|
+
if (handledEvents.has(eventId)) return 'already-issued'; // stands in for ON CONFLICT DO NOTHING
|
|
76
|
+
handledEvents.add(eventId);
|
|
77
|
+
|
|
78
|
+
// Fulfil on tierId + quantity — NEVER by matching the amount back to a price.
|
|
79
|
+
// Prices change, tiers don't, and two tiers can cost the same.
|
|
80
|
+
tickets.set(eventId, { tierId: p.tierId, quantity: p.quantity, buyerRef: p.buyerRef });
|
|
81
|
+
return 'issued';
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
// ─────────────────────────────────────────────────────────────────────────────
|
|
85
|
+
// §2 · RECEIVE. Verify, then dispatch. The SDK does not dedupe for you.
|
|
86
|
+
// ─────────────────────────────────────────────────────────────────────────────
|
|
87
|
+
const onAlyteWebhook = createWebhookHandler({ secret: WEBHOOK_SECRET }, {
|
|
88
|
+
onSettled: async (payment: PaymentSettled, event) => {
|
|
89
|
+
const outcome = issueTickets(event.eventId, payment);
|
|
90
|
+
console.log(`[settled] ${event.eventId} · ${payment.quantity}× ${payment.tierId} · ${outcome}`);
|
|
91
|
+
// If this throws, we return 5xx below and Alyte retries (30s → 1h, 10 times).
|
|
92
|
+
},
|
|
93
|
+
|
|
94
|
+
onWatchFailed: async (watch: WatchFailed) => {
|
|
95
|
+
// A queued purchase refused. THIS IS TERMINAL — the watch does not retry,
|
|
96
|
+
// so this is your only chance to tell the buyer. Relay reason.message
|
|
97
|
+
// as-authored; it is written to be read by a person.
|
|
98
|
+
notifications.push({ buyerRef: watch.buyerRef, message: watch.reason.message });
|
|
99
|
+
console.log(`[refused] ${watch.watchId} · ${watch.reason.code} · "${watch.reason.message}"`);
|
|
100
|
+
},
|
|
101
|
+
|
|
102
|
+
onTest: async (event) => {
|
|
103
|
+
// Carries no payment data. Use it to prove your signature check works
|
|
104
|
+
// BEFORE a real sale depends on it. Never fulfil on it.
|
|
105
|
+
console.log(`[test] signature verified · ${event.eventId}`);
|
|
106
|
+
},
|
|
107
|
+
});
|
|
108
|
+
|
|
109
|
+
// ─────────────────────────────────────────────────────────────────────────────
|
|
110
|
+
// §4 · DIAGNOSE. Answer "what happened to that purchase?" yourself.
|
|
111
|
+
// ─────────────────────────────────────────────────────────────────────────────
|
|
112
|
+
async function whyDidThisNotBuy(watchId: string): Promise<unknown> {
|
|
113
|
+
// Most refusals happen BEFORE a payment exists (the spend cap is checked
|
|
114
|
+
// first), so there is often no intentId to look up — this is the entry point
|
|
115
|
+
// that always works. `deliveries` tells you whether WE sent the webhook and
|
|
116
|
+
// what your endpoint said back.
|
|
117
|
+
const res = await fetch(`${BASE_URL}/v1/integration/watches/${watchId}`, {
|
|
118
|
+
headers: { authorization: `Bearer ${API_TOKEN}` },
|
|
119
|
+
});
|
|
120
|
+
if (!res.ok) throw new Error(`lookup failed: ${res.status} ${await res.text()}`);
|
|
121
|
+
return res.json();
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
// ─────────────────────────────────────────────────────────────────────────────
|
|
125
|
+
// Wiring
|
|
126
|
+
// ─────────────────────────────────────────────────────────────────────────────
|
|
127
|
+
function readRawBody(req: IncomingMessage): Promise<string> {
|
|
128
|
+
// RAW bytes. Do not use a JSON body parser on this route — verification is
|
|
129
|
+
// over the exact bytes we signed, and parse-then-restringify breaks it.
|
|
130
|
+
return new Promise((resolve, reject) => {
|
|
131
|
+
const chunks: Buffer[] = [];
|
|
132
|
+
req.on('data', (c: Buffer) => chunks.push(c));
|
|
133
|
+
req.on('end', () => resolve(Buffer.concat(chunks).toString('utf8')));
|
|
134
|
+
req.on('error', reject);
|
|
135
|
+
});
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
const server = createServer(async (req: IncomingMessage, res: ServerResponse) => {
|
|
139
|
+
const url = new URL(req.url ?? '/', `http://localhost:${PORT}`);
|
|
140
|
+
const send = (status: number, body: unknown) => {
|
|
141
|
+
res.writeHead(status, { 'content-type': 'application/json' });
|
|
142
|
+
res.end(typeof body === 'string' ? JSON.stringify({ message: body }) : JSON.stringify(body, null, 2));
|
|
143
|
+
};
|
|
144
|
+
|
|
145
|
+
try {
|
|
146
|
+
// §1 · HAND OFF. There is no merchant-side "buy" call, by design: your
|
|
147
|
+
// token cannot spend. You send the buyer to their own authorize page, and
|
|
148
|
+
// they approve in their own session. One URL, no API call.
|
|
149
|
+
if (req.method === 'GET' && url.pathname.startsWith('/buy/')) {
|
|
150
|
+
const tierId = url.pathname.slice('/buy/'.length);
|
|
151
|
+
const merchantId = process.env.ALYTE_MERCHANT_ID ?? 'mrc_your_id';
|
|
152
|
+
const handoff = `${BASE_URL}/shop/${merchantId}/authorize?tier=${encodeURIComponent(tierId)}`;
|
|
153
|
+
res.writeHead(302, { location: handoff });
|
|
154
|
+
return res.end();
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
if (req.method === 'POST' && url.pathname === '/hooks/alyte') {
|
|
158
|
+
const raw = await readRawBody(req);
|
|
159
|
+
const result = await onAlyteWebhook(raw, req.headers['alyte-signature'] as string | undefined);
|
|
160
|
+
// 200 = we stop retrying. Only say it when the work is durably done.
|
|
161
|
+
return send(result.status, result.ok ? { ok: true } : { error: result.error });
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
if (req.method === 'GET' && url.pathname.startsWith('/admin/why/')) {
|
|
165
|
+
return send(200, await whyDidThisNotBuy(url.pathname.slice('/admin/why/'.length)));
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
if (req.method === 'GET' && url.pathname === '/admin/state') {
|
|
169
|
+
return send(200, { tickets: [...tickets.entries()], notifications });
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
return send(404, 'not found');
|
|
173
|
+
} catch (err) {
|
|
174
|
+
// A throw from a handler lands here. Returning 5xx is CORRECT: it tells
|
|
175
|
+
// Alyte to retry. Returning 200 on failure loses the event permanently.
|
|
176
|
+
console.error('[error]', err);
|
|
177
|
+
return send(500, { error: (err as Error).message });
|
|
178
|
+
}
|
|
179
|
+
});
|
|
180
|
+
|
|
181
|
+
server.listen(PORT, () => {
|
|
182
|
+
console.log(`reference merchant on http://localhost:${PORT}`);
|
|
183
|
+
console.log(` hand-off GET /buy/:tierId`);
|
|
184
|
+
console.log(` webhook POST /hooks/alyte`);
|
|
185
|
+
console.log(` diagnose GET /admin/why/:watchId`);
|
|
186
|
+
console.log(` state GET /admin/state`);
|
|
187
|
+
console.log(`\nVerify your signature check before a real sale:`);
|
|
188
|
+
console.log(` 1. expose this server (e.g. a tunnel) and register the URL as a webhook endpoint`);
|
|
189
|
+
console.log(` 2. POST /v1/integration/webhooks/:id/test → you should see "[test] signature verified"`);
|
|
190
|
+
});
|
package/package.json
CHANGED
|
@@ -1,6 +1,53 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@alytegen/sdk",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.3.0",
|
|
4
|
+
"description": "Alyte client SDK — merchant integration (catalog, PSP links, buyer sessions, payments visibility) and the agent buy path (discover → quote → hold → confirm).",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"main": "dist/index.js",
|
|
7
|
+
"types": "dist/index.d.ts",
|
|
8
|
+
"exports": {
|
|
9
|
+
".": {
|
|
10
|
+
"types": "./dist/index.d.ts",
|
|
11
|
+
"import": "./dist/index.js"
|
|
12
|
+
}
|
|
13
|
+
},
|
|
14
|
+
"files": [
|
|
15
|
+
"dist",
|
|
16
|
+
"QUICKSTART.md",
|
|
17
|
+
"examples"
|
|
18
|
+
],
|
|
19
|
+
"scripts": {
|
|
20
|
+
"build": "tsc -p tsconfig.json",
|
|
21
|
+
"prepublishOnly": "npm run build"
|
|
22
|
+
},
|
|
23
|
+
"engines": {
|
|
24
|
+
"node": ">=18"
|
|
25
|
+
},
|
|
26
|
+
"license": "MIT",
|
|
27
|
+
"repository": {
|
|
28
|
+
"type": "git",
|
|
29
|
+
"url": "git+https://github.com/Alytegen/alyte-sdk.git"
|
|
30
|
+
},
|
|
31
|
+
"homepage": "https://github.com/Alytegen/alyte-sdk#readme",
|
|
32
|
+
"bugs": {
|
|
33
|
+
"url": "https://github.com/Alytegen/alyte-sdk/issues"
|
|
34
|
+
},
|
|
35
|
+
"keywords": [
|
|
36
|
+
"alyte",
|
|
37
|
+
"agentic-commerce",
|
|
38
|
+
"ai-agents",
|
|
39
|
+
"payments",
|
|
40
|
+
"mandate",
|
|
41
|
+
"ticketing",
|
|
42
|
+
"sdk"
|
|
43
|
+
],
|
|
44
|
+
"sideEffects": false,
|
|
45
|
+
"publishConfig": {
|
|
46
|
+
"access": "public"
|
|
47
|
+
},
|
|
48
|
+
"devDependencies": {
|
|
49
|
+
"@types/node": "^22.10.5",
|
|
50
|
+
"typescript": "^5.7.3"
|
|
51
|
+
},
|
|
52
|
+
"author": "Alyte Agentic Pay"
|
|
53
|
+
}
|