@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.
@@ -0,0 +1,133 @@
1
+ /**
2
+ * The envelope every Alyte webhook arrives in. `data` differs per `type`;
3
+ * `eventId` is the dedupe key (stable across retries of the SAME event).
4
+ */
5
+ export interface AlyteEventEnvelope<T = unknown> {
6
+ /** Delivery id — CHANGES on every retry. Never dedupe on this. */
7
+ id: string;
8
+ type: string;
9
+ /** Stable per logical event. THIS is your dedupe key. */
10
+ eventId: string;
11
+ createdAt: string;
12
+ data: T;
13
+ }
14
+ /** A purchase that authorized and captured. Fulfil on `tierId` + `quantity`. */
15
+ export interface PaymentSettled {
16
+ intentId: string;
17
+ merchantId: string;
18
+ /** Integer minor units. NEVER a float — see formatMinor for display. */
19
+ amountMinor: number;
20
+ currency: string;
21
+ status: 'authorized';
22
+ pspId: string;
23
+ scheme?: string;
24
+ source: string;
25
+ createdBy: string;
26
+ createdAt: string;
27
+ /** Fulfil on THIS, never by matching the amount to a price. */
28
+ tierId: string;
29
+ quantity: number;
30
+ /** Stable opaque buyer reference — never an email. */
31
+ buyerRef: string;
32
+ }
33
+ /** A queued purchase that terminally refused. There is no retry after this. */
34
+ export interface WatchFailed {
35
+ watchId: string;
36
+ agentId: string;
37
+ buyerRef: string;
38
+ merchantId: string;
39
+ tierId: string;
40
+ quantity: number;
41
+ /** The typed refusal, verbatim — relay `message` to the buyer. */
42
+ reason: {
43
+ code: string;
44
+ message: string;
45
+ };
46
+ failedAt: string;
47
+ }
48
+ /** A signed delivery carrying no payment data. NEVER fulfil on this. */
49
+ export interface WebhookTest {
50
+ [key: string]: unknown;
51
+ }
52
+ export interface PurchaseHandlers {
53
+ /** A purchase completed. Issue the ticket here. */
54
+ onSettled?: (data: PaymentSettled, event: AlyteEventEnvelope<PaymentSettled>) => Promise<void> | void;
55
+ /** A queued purchase terminally refused. Tell the buyer why. */
56
+ onWatchFailed?: (data: WatchFailed, event: AlyteEventEnvelope<WatchFailed>) => Promise<void> | void;
57
+ /** A test delivery — use it to prove your signature check works. */
58
+ onTest?: (event: AlyteEventEnvelope<WebhookTest>) => Promise<void> | void;
59
+ /** Any event type this SDK version does not know. Default: ignored. */
60
+ onUnknown?: (event: AlyteEventEnvelope) => Promise<void> | void;
61
+ }
62
+ export interface OnPurchaseOptions {
63
+ /** The signing secret, shown exactly once when the endpoint was created. */
64
+ secret: string;
65
+ /** Replay window in seconds (default 300). */
66
+ toleranceSeconds?: number;
67
+ }
68
+ export type WebhookResult = {
69
+ ok: true;
70
+ status: 200;
71
+ eventId: string;
72
+ type: string;
73
+ } | {
74
+ ok: false;
75
+ status: 400 | 401;
76
+ error: string;
77
+ };
78
+ /**
79
+ * Verify and dispatch one Alyte webhook delivery.
80
+ *
81
+ * ## Deliveries are AT-LEAST-ONCE, and your handler owns idempotency.
82
+ *
83
+ * We retry until we see a 2xx, so a handler CAN run more than once for the
84
+ * same `eventId` — most commonly when your handler succeeded but the response
85
+ * never reached us. This SDK deliberately does NOT dedupe for you: doing it
86
+ * here would be a lie, because the dangerous window is not between deliveries,
87
+ * it is inside your own process. If you issue a ticket and crash before
88
+ * recording "handled", a retry double-issues; if you record first and crash,
89
+ * the fulfilment is lost.
90
+ *
91
+ * Only your database can close that window, by writing the dedupe row in the
92
+ * SAME transaction as the ticket:
93
+ *
94
+ * ```ts
95
+ * await db.transaction(async (tx) => {
96
+ * const claimed = await tx.query(
97
+ * `INSERT INTO handled_events (event_id) VALUES ($1)
98
+ * ON CONFLICT DO NOTHING RETURNING event_id`, [event.eventId]);
99
+ * if (!claimed.rowCount) return; // already done — a retry, not a new sale
100
+ * await tx.query(`INSERT INTO tickets (...) VALUES (...)`);
101
+ * });
102
+ * ```
103
+ *
104
+ * ## Failure behaviour
105
+ *
106
+ * - Bad/missing signature → `{ok: false, status: 401}`. Return that status; do
107
+ * NOT run your handler.
108
+ * - Malformed body → `{ok: false, status: 400}`. We will not usefully retry it.
109
+ * - Your handler THROWS → the error propagates. Return 5xx so we retry
110
+ * (30s → 1h backoff, 10 attempts). Swallowing it and returning 200 means the
111
+ * event is gone forever.
112
+ *
113
+ * Pass the RAW request body — verification is over exact bytes, so a parsed
114
+ * and re-serialized object will fail even when the signature is valid.
115
+ */
116
+ export declare function handleWebhook(rawBody: string, signatureHeader: string | undefined, handlers: PurchaseHandlers, options: OnPurchaseOptions): Promise<WebhookResult>;
117
+ /**
118
+ * The same dispatcher, curried for frameworks that want a reusable handler.
119
+ *
120
+ * ```ts
121
+ * const onPurchase = createWebhookHandler({ secret: process.env.ALYTE_WEBHOOK_SECRET! }, {
122
+ * onSettled: async (p) => { await issueTickets(p.tierId, p.quantity, p.buyerRef); },
123
+ * onWatchFailed: async (w) => { await emailBuyer(w.buyerRef, w.reason.message); },
124
+ * });
125
+ *
126
+ * // Express — note express.raw, NOT express.json
127
+ * app.post('/hooks/alyte', express.raw({ type: 'application/json' }), async (req, res) => {
128
+ * const r = await onPurchase(req.body.toString('utf8'), req.header('alyte-signature'));
129
+ * res.status(r.status).send(r.ok ? 'ok' : r.error);
130
+ * });
131
+ * ```
132
+ */
133
+ export declare function createWebhookHandler(options: OnPurchaseOptions, handlers: PurchaseHandlers): (rawBody: string, signatureHeader: string | undefined) => Promise<WebhookResult>;
@@ -0,0 +1,92 @@
1
+ import { verifyWebhookSignature } from './webhookVerify.js';
2
+ /**
3
+ * Verify and dispatch one Alyte webhook delivery.
4
+ *
5
+ * ## Deliveries are AT-LEAST-ONCE, and your handler owns idempotency.
6
+ *
7
+ * We retry until we see a 2xx, so a handler CAN run more than once for the
8
+ * same `eventId` — most commonly when your handler succeeded but the response
9
+ * never reached us. This SDK deliberately does NOT dedupe for you: doing it
10
+ * here would be a lie, because the dangerous window is not between deliveries,
11
+ * it is inside your own process. If you issue a ticket and crash before
12
+ * recording "handled", a retry double-issues; if you record first and crash,
13
+ * the fulfilment is lost.
14
+ *
15
+ * Only your database can close that window, by writing the dedupe row in the
16
+ * SAME transaction as the ticket:
17
+ *
18
+ * ```ts
19
+ * await db.transaction(async (tx) => {
20
+ * const claimed = await tx.query(
21
+ * `INSERT INTO handled_events (event_id) VALUES ($1)
22
+ * ON CONFLICT DO NOTHING RETURNING event_id`, [event.eventId]);
23
+ * if (!claimed.rowCount) return; // already done — a retry, not a new sale
24
+ * await tx.query(`INSERT INTO tickets (...) VALUES (...)`);
25
+ * });
26
+ * ```
27
+ *
28
+ * ## Failure behaviour
29
+ *
30
+ * - Bad/missing signature → `{ok: false, status: 401}`. Return that status; do
31
+ * NOT run your handler.
32
+ * - Malformed body → `{ok: false, status: 400}`. We will not usefully retry it.
33
+ * - Your handler THROWS → the error propagates. Return 5xx so we retry
34
+ * (30s → 1h backoff, 10 attempts). Swallowing it and returning 200 means the
35
+ * event is gone forever.
36
+ *
37
+ * Pass the RAW request body — verification is over exact bytes, so a parsed
38
+ * and re-serialized object will fail even when the signature is valid.
39
+ */
40
+ export async function handleWebhook(rawBody, signatureHeader, handlers, options) {
41
+ if (!signatureHeader)
42
+ return { ok: false, status: 401, error: 'missing alyte-signature header' };
43
+ if (!verifyWebhookSignature(rawBody, signatureHeader, options.secret, options.toleranceSeconds)) {
44
+ return { ok: false, status: 401, error: 'signature did not verify' };
45
+ }
46
+ let event;
47
+ try {
48
+ event = JSON.parse(rawBody);
49
+ }
50
+ catch {
51
+ return { ok: false, status: 400, error: 'body is not valid JSON' };
52
+ }
53
+ if (!event?.type || !event?.eventId) {
54
+ return { ok: false, status: 400, error: 'not an Alyte event envelope' };
55
+ }
56
+ // A handler that throws propagates on purpose: the caller must return 5xx so
57
+ // the delivery is retried rather than silently dropped.
58
+ switch (event.type) {
59
+ case 'payment.settled':
60
+ await handlers.onSettled?.(event.data, event);
61
+ break;
62
+ case 'watch.failed':
63
+ await handlers.onWatchFailed?.(event.data, event);
64
+ break;
65
+ case 'webhook.test':
66
+ await handlers.onTest?.(event);
67
+ break;
68
+ default:
69
+ await handlers.onUnknown?.(event);
70
+ break;
71
+ }
72
+ return { ok: true, status: 200, eventId: event.eventId, type: event.type };
73
+ }
74
+ /**
75
+ * The same dispatcher, curried for frameworks that want a reusable handler.
76
+ *
77
+ * ```ts
78
+ * const onPurchase = createWebhookHandler({ secret: process.env.ALYTE_WEBHOOK_SECRET! }, {
79
+ * onSettled: async (p) => { await issueTickets(p.tierId, p.quantity, p.buyerRef); },
80
+ * onWatchFailed: async (w) => { await emailBuyer(w.buyerRef, w.reason.message); },
81
+ * });
82
+ *
83
+ * // Express — note express.raw, NOT express.json
84
+ * app.post('/hooks/alyte', express.raw({ type: 'application/json' }), async (req, res) => {
85
+ * const r = await onPurchase(req.body.toString('utf8'), req.header('alyte-signature'));
86
+ * res.status(r.status).send(r.ok ? 'ok' : r.error);
87
+ * });
88
+ * ```
89
+ */
90
+ export function createWebhookHandler(options, handlers) {
91
+ return (rawBody, signatureHeader) => handleWebhook(rawBody, signatureHeader, handlers, options);
92
+ }
@@ -0,0 +1,188 @@
1
+ /**
2
+ * Hand-typed mirrors of the Alyte API's response shapes. Money is ALWAYS integer
3
+ * minor units (`…Minor`) — never floats. Format for display only.
4
+ */
5
+ export type Scheme = 'visa' | 'mastercard' | 'amex';
6
+ export type TierKind = 'general' | 'seated';
7
+ export type FeeBearer = 'buyer' | 'merchant';
8
+ export interface Merchant {
9
+ id: string;
10
+ name: string;
11
+ geo: string;
12
+ currency: string;
13
+ /** 'api' = in-flow reserve/confirm; 'hosted' = discovery-only, redirect to checkoutUrl. */
14
+ checkout?: 'api' | 'hosted';
15
+ checkoutUrl?: string;
16
+ allowedSchemes?: Scheme[];
17
+ feeBearer?: FeeBearer;
18
+ taxRateBps?: number;
19
+ /** Public discovery opt-in (default false) — see AlyteMerchant.updateShopDiscovery. */
20
+ discoverable?: boolean;
21
+ imageUrl?: string;
22
+ /** The ONE partner origin allowed to embed the authorize page (G14). */
23
+ embedOrigin?: string;
24
+ }
25
+ export interface EventItem {
26
+ id: string;
27
+ merchantId: string;
28
+ title: string;
29
+ /** ISO-8601 start time. */
30
+ startsAt: string;
31
+ }
32
+ export interface Tier {
33
+ id: string;
34
+ eventId: string;
35
+ title: string;
36
+ /** Integer minor units (cents). NEVER a float. */
37
+ priceMinor: number;
38
+ currency: string;
39
+ kind: TierKind;
40
+ availableCount?: number;
41
+ maxQtyPerPurchase?: number;
42
+ sellable?: boolean;
43
+ onSaleStart?: string;
44
+ onSaleEnd?: string;
45
+ allowedGeos?: string[];
46
+ allowedSchemes?: Scheme[];
47
+ }
48
+ /** Temporal availability, derived server-side at discovery time. */
49
+ export type AvailabilityState = 'on_sale' | 'not_yet_on_sale' | 'sale_ended' | 'sold_out' | 'not_sellable';
50
+ export interface DiscoveredTier extends Tier {
51
+ state: AvailabilityState;
52
+ /** Seconds until worth retrying, present when the sale hasn't opened. */
53
+ retryAfter?: number;
54
+ /** Present when a future purchase could still serve (drop CTA). */
55
+ authorizeUrl?: string;
56
+ }
57
+ export interface DiscoveredEvent extends EventItem {
58
+ tiers: DiscoveredTier[];
59
+ }
60
+ /** A price snapshot locked at quote time; the charge must match it. */
61
+ export interface Quote {
62
+ id: string;
63
+ tierId: string;
64
+ quantity: number;
65
+ unitPriceMinor: number;
66
+ subtotalMinor: number;
67
+ taxMinor: number;
68
+ processingFeeMinor: number;
69
+ /** Alyte's fee — INVOICED to the merchant, never part of the buyer's charge. */
70
+ agentFeeMinor: number;
71
+ /** What the buyer's card is authorised for (depends on feeBearer). */
72
+ chargeMinor: number;
73
+ pspId?: string;
74
+ feeBearer: FeeBearer;
75
+ currency: string;
76
+ /** ISO-8601; re-quote after this. */
77
+ expiresAt: string;
78
+ createdAt: string;
79
+ }
80
+ /** A perishable, oversell-proof reservation. */
81
+ export interface Hold {
82
+ id: string;
83
+ tierId: string;
84
+ seatId?: string;
85
+ quantity: number;
86
+ status: 'held' | 'confirmed' | 'released' | 'expired';
87
+ expiresAt: string;
88
+ createdAt: string;
89
+ /** Present on a partial fill (allowPartial: true). */
90
+ requestedQuantity?: number;
91
+ partialReason?: string;
92
+ }
93
+ export interface PaymentResult {
94
+ intentId: string;
95
+ status: string;
96
+ psp?: string;
97
+ amountMinor?: number;
98
+ currency?: string;
99
+ [k: string]: unknown;
100
+ }
101
+ export type ConfirmOutcome = {
102
+ status: 'settled';
103
+ result: PaymentResult;
104
+ holdStatus: string;
105
+ } | {
106
+ status: 'sca_required';
107
+ challenge: {
108
+ continueToken: string;
109
+ [k: string]: unknown;
110
+ };
111
+ holdStatus: 'held';
112
+ } | {
113
+ status: 'sca_failed';
114
+ holdStatus: 'released';
115
+ };
116
+ export interface MerchantPspLink {
117
+ pspId: string;
118
+ name: string;
119
+ isDefault: boolean;
120
+ rateBps: number;
121
+ /** Opaque reference to the merchant's vaulted PSP secret — never the secret. */
122
+ credentialRef?: string;
123
+ publishableKey?: string;
124
+ }
125
+ export interface CatalogMerchant extends Merchant {
126
+ events: Array<EventItem & {
127
+ tiers: Tier[];
128
+ }>;
129
+ }
130
+ export interface BuyerSessionMint {
131
+ ok: boolean;
132
+ /** Deterministic buyer identity (byr_…) — stable across mint & magic-link logins. */
133
+ buyerId: string;
134
+ expiresAt: string;
135
+ /** RELATIVE single-use redeem path — compose with your Alyte base URL and
136
+ * redirect your user there to drop them into the shop's authorize page. */
137
+ redeemPath: string;
138
+ }
139
+ /** A row on the merchant payments feed (`GET /v1/integration/payments`). */
140
+ export interface PaymentRow {
141
+ intentId: string;
142
+ tenantId: string;
143
+ merchantId: string;
144
+ amountMinor: number;
145
+ currency: string;
146
+ /** 'pending' | 'authorized' | 'declined' | 'error' — FULFIL on 'authorized'
147
+ * (terminal for ticketing: the seat is sold and the charge is captured). */
148
+ status: string;
149
+ pspId?: string;
150
+ scheme?: string;
151
+ source?: string;
152
+ createdBy: string;
153
+ createdAt: string;
154
+ /** The paid ticket tier — fulfil on THIS, never by price-matching. Absent only
155
+ * on legacy rows. */
156
+ tierId?: string;
157
+ quantity?: number;
158
+ /** Stable opaque buyer reference (byr_…) — never an email. Map it to your own
159
+ * customer record at buyer-session mint time if you need contact details. */
160
+ buyerRef?: string;
161
+ }
162
+ /** A registered webhook endpoint (secret is returned ONCE, at create). */
163
+ export interface WebhookEndpoint {
164
+ id: string;
165
+ url: string;
166
+ status: 'active' | 'disabled';
167
+ description?: string;
168
+ createdAt: string;
169
+ }
170
+ /** Agent adoption + per-tier watch demand for one shop (counts only). */
171
+ export interface MerchantInsights {
172
+ agents: {
173
+ total: number;
174
+ alyte: number;
175
+ byoa: number;
176
+ readyToBuy: number;
177
+ };
178
+ watches: Array<{
179
+ tierId: string;
180
+ tierTitle: string;
181
+ eventTitle: string;
182
+ queued: number;
183
+ fired: number;
184
+ failed: number;
185
+ cancelled: number;
186
+ expired: number;
187
+ }>;
188
+ }
package/dist/types.js ADDED
@@ -0,0 +1,5 @@
1
+ /**
2
+ * Hand-typed mirrors of the Alyte API's response shapes. Money is ALWAYS integer
3
+ * minor units (`…Minor`) — never floats. Format for display only.
4
+ */
5
+ export {};
@@ -0,0 +1,11 @@
1
+ /**
2
+ * Verify an Alyte webhook delivery. The signature is an HMAC-SHA256 over the RAW
3
+ * request body, timestamp-prefixed (Stripe-shaped):
4
+ *
5
+ * alyte-signature: t=<unix-seconds>,v1=hex( hmac_sha256(secret, `${t}.${rawBody}`) )
6
+ *
7
+ * Verify against the RAW bytes, before any JSON parse/re-serialize — most
8
+ * frameworks need a raw-body handler on the webhook route. Deliveries are
9
+ * at-least-once: dedupe by the event's `eventId` (the payment's intentId).
10
+ */
11
+ export declare function verifyWebhookSignature(rawBody: string, signatureHeader: string, secret: string, toleranceSeconds?: number): boolean;
@@ -0,0 +1,23 @@
1
+ import { createHmac, timingSafeEqual } from 'node:crypto';
2
+ /**
3
+ * Verify an Alyte webhook delivery. The signature is an HMAC-SHA256 over the RAW
4
+ * request body, timestamp-prefixed (Stripe-shaped):
5
+ *
6
+ * alyte-signature: t=<unix-seconds>,v1=hex( hmac_sha256(secret, `${t}.${rawBody}`) )
7
+ *
8
+ * Verify against the RAW bytes, before any JSON parse/re-serialize — most
9
+ * frameworks need a raw-body handler on the webhook route. Deliveries are
10
+ * at-least-once: dedupe by the event's `eventId` (the payment's intentId).
11
+ */
12
+ export function verifyWebhookSignature(rawBody, signatureHeader, secret, toleranceSeconds = 300) {
13
+ const t = /(?:^|,)t=(\d+)/.exec(signatureHeader)?.[1];
14
+ const v1 = /(?:^|,)v1=([0-9a-f]+)/.exec(signatureHeader)?.[1];
15
+ if (!t || !v1)
16
+ return false;
17
+ if (Math.abs(Date.now() / 1000 - Number(t)) > toleranceSeconds)
18
+ return false; // replay window
19
+ const expected = createHmac('sha256', secret).update(`${t}.${rawBody}`).digest('hex');
20
+ if (expected.length !== v1.length)
21
+ return false;
22
+ return timingSafeEqual(Buffer.from(expected), Buffer.from(v1));
23
+ }
@@ -0,0 +1,47 @@
1
+ /**
2
+ * The agent buy path: discover → quote → hold → confirm. Requires an agent JWT
3
+ * (catalog:read + payments:write) whose mandate covers the purchase.
4
+ *
5
+ * ALYTE_BASE_URL=… ALYTE_AGENT_TOKEN=… npx tsx agent-buy.ts
6
+ */
7
+ import { randomUUID } from 'node:crypto';
8
+ import { AlyteAgent, AlyteApiError } from '@alytegen/sdk';
9
+
10
+ const agent = new AlyteAgent({
11
+ baseUrl: process.env.ALYTE_BASE_URL!,
12
+ token: process.env.ALYTE_AGENT_TOKEN!,
13
+ });
14
+
15
+ // 1 · Discover. `state` is live truth: a drop that hasn't opened says so, with a retryAfter.
16
+ const { merchants } = await agent.listMerchants();
17
+ const { events } = await agent.discoverInventory(merchants[0]!.id);
18
+ const tier = events.flatMap((e) => e.tiers).find((t) => t.state === 'on_sale');
19
+ if (!tier) throw new Error('nothing on sale right now');
20
+
21
+ // 2 · Quote — the price is LOCKED until expiresAt. No amount is ever passed again.
22
+ const quote = await agent.quote({ tierId: tier.id, quantity: 2 });
23
+
24
+ // 3 · Hold — oversell-proof; auto-releases if you don't confirm in time.
25
+ const hold = await agent.reserve({ tierId: tier.id, quantity: 2, scheme: 'visa', geo: 'DE' });
26
+
27
+ // 4 · Confirm — pays the locked quote. The idempotencyKey makes retries safe:
28
+ // the same key can NEVER double-charge, even across crashes.
29
+ const [instrument] = (await agent.listInstruments()).instruments;
30
+ try {
31
+ const outcome = await agent.confirm(
32
+ hold.id,
33
+ { quoteId: quote.id, instrumentToken: instrument!.token, scheme: 'visa', geo: 'DE' },
34
+ { idempotencyKey: randomUUID() },
35
+ );
36
+ if (outcome.status === 'settled') console.log('paid:', outcome.result.intentId);
37
+ else if (outcome.status === 'sca_required') {
38
+ // The buyer approves out-of-band; then:
39
+ console.log('resume with:', outcome.challenge.continueToken);
40
+ }
41
+ } catch (e) {
42
+ if (e instanceof AlyteApiError) {
43
+ // Stable taxonomy codes — e.g. a spend-cap refusal means the MANDATE said no;
44
+ // don't retry, tell the buyer.
45
+ console.error(`refused [${e.code}]: ${e.message}`);
46
+ } else throw e;
47
+ }
@@ -0,0 +1,48 @@
1
+ /**
2
+ * Merchant onboarding, end to end: shop → PSP → event → tier → your user shopping.
3
+ *
4
+ * ALYTE_BASE_URL=https://alyte-sandbox-….run.app \
5
+ * ALYTE_API_TOKEN=<console-minted, merchant:read+merchant:write> \
6
+ * npx tsx merchant-onboard.ts
7
+ */
8
+ import { AlyteMerchant } from '@alytegen/sdk';
9
+
10
+ const alyte = new AlyteMerchant({
11
+ baseUrl: process.env.ALYTE_BASE_URL!,
12
+ token: process.env.ALYTE_API_TOKEN!, // secret — server-side only
13
+ });
14
+
15
+ // 1 · The shop (your settlement identity — money lands on YOUR PSP, never Alyte's).
16
+ const { merchant } = await alyte.createShop({ name: 'Nova Live', geo: 'DE', currency: 'EUR' });
17
+
18
+ // 2 · Your OWN Stripe. The secret goes straight to Alyte's vault — you get back an
19
+ // opaque ref; the pk_ powers the buyer card-capture iframe.
20
+ await alyte.linkPsp(merchant.id, {
21
+ psp: { id: 'stripe', name: 'Stripe' },
22
+ isDefault: true,
23
+ secret: process.env.MY_STRIPE_SECRET_KEY!,
24
+ publishableKey: process.env.MY_STRIPE_PUBLISHABLE_KEY,
25
+ });
26
+
27
+ // 3 · Inventory. priceMinor is integer cents — 4900 = €49.00.
28
+ const { event } = await alyte.createEvent({
29
+ merchantId: merchant.id,
30
+ title: 'Nova Live — Warsaw',
31
+ startsAt: '2026-11-04T19:00:00Z',
32
+ });
33
+ const { tier } = await alyte.createTier({
34
+ eventId: event.id,
35
+ title: 'General admission',
36
+ priceMinor: 4900,
37
+ currency: 'EUR',
38
+ kind: 'general',
39
+ availableCount: 500,
40
+ });
41
+ await alyte.updateTier(tier.id, { maxQtyPerPurchase: 4 });
42
+
43
+ // 4 · Your signed-in user wants their AI agent to buy for them. You already know
44
+ // who they are — attest them; no email round-trip:
45
+ const session = await alyte.buyerSessions.mint({ merchantId: merchant.id, email: 'fan@example.com' });
46
+ console.log('Redirect your user to:', process.env.ALYTE_BASE_URL + session.redeemPath);
47
+ // They land authenticated on the shop's authorize page: pick/bring an agent,
48
+ // set a spending cap, done. Alyte enforces the cap server-side on every purchase.