@alytegen/sdk 0.0.0-stage → 0.4.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/BROWSER.md +83 -0
- package/LICENSE +21 -0
- package/QUICKSTART.md +78 -0
- package/README.md +96 -2
- package/dist/agent.d.ts +68 -0
- package/dist/agent.js +59 -0
- package/dist/browser.d.ts +183 -0
- package/dist/browser.js +159 -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 +171 -0
- package/dist/merchant.js +107 -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 +56 -4
package/dist/browser.js
ADDED
|
@@ -0,0 +1,159 @@
|
|
|
1
|
+
/** Browser-only buyer connection. No merchant key or raw agent credential belongs here. */
|
|
2
|
+
import { AlyteApiError } from './http.js';
|
|
3
|
+
export { AlyteApiError } from './http.js';
|
|
4
|
+
function baseOrigin(value) {
|
|
5
|
+
const url = new URL(value);
|
|
6
|
+
if (!['http:', 'https:'].includes(url.protocol) || url.username || url.password || url.pathname !== '/' || url.search || url.hash)
|
|
7
|
+
throw new TypeError('baseUrl must be an HTTP(S) origin');
|
|
8
|
+
if (url.protocol !== 'https:' && !['localhost', '127.0.0.1', '[::1]'].includes(url.hostname))
|
|
9
|
+
throw new TypeError('baseUrl must use HTTPS outside local development');
|
|
10
|
+
return url.origin;
|
|
11
|
+
}
|
|
12
|
+
/** HTTP errors retain the server taxonomy; no request is automatically retried. */
|
|
13
|
+
async function request(fetcher, base, path, method, bearer, body) {
|
|
14
|
+
const res = await fetcher(base + path, { method, credentials: 'omit', redirect: 'error', cache: 'no-store',
|
|
15
|
+
headers: { ...(bearer ? { authorization: `Bearer ${bearer}` } : {}), ...(body !== undefined ? { 'content-type': 'application/json' } : {}) },
|
|
16
|
+
body: body === undefined ? undefined : JSON.stringify(body),
|
|
17
|
+
});
|
|
18
|
+
const json = await res.json().catch(() => undefined);
|
|
19
|
+
if (!res.ok) {
|
|
20
|
+
const error = json?.error;
|
|
21
|
+
throw new AlyteApiError(res.status, error?.code ?? `http_${res.status}`, error?.message ?? `Alyte API error (HTTP ${res.status})`, error?.details ?? json);
|
|
22
|
+
}
|
|
23
|
+
return json;
|
|
24
|
+
}
|
|
25
|
+
/** Pass only the token from the merchant-minted redeemPath. Keep the result in memory. */
|
|
26
|
+
export function exchangeBuyerSession(opts) {
|
|
27
|
+
if (typeof opts.token !== 'string' || !opts.token)
|
|
28
|
+
throw new TypeError('token is required');
|
|
29
|
+
return request(opts.fetch ?? globalThis.fetch, baseOrigin(opts.baseUrl), '/v1/buyer/session-token', 'POST', undefined, { token: opts.token });
|
|
30
|
+
}
|
|
31
|
+
/** Existing-authority actions only. Setup and permission changes belong in openConsent. */
|
|
32
|
+
export function createBuyerClient(opts) {
|
|
33
|
+
const base = baseOrigin(opts.baseUrl), fetcher = opts.fetch ?? globalThis.fetch;
|
|
34
|
+
if (typeof opts.bearer !== 'string' || !opts.bearer)
|
|
35
|
+
throw new TypeError('bearer is required');
|
|
36
|
+
const call = (method, path, body) => request(fetcher, base, '/v1/buyer' + path, method, opts.bearer, body);
|
|
37
|
+
return {
|
|
38
|
+
me: () => call('GET', '/me'),
|
|
39
|
+
catalog: () => call('GET', '/catalog'),
|
|
40
|
+
agents: () => call('GET', '/agents'),
|
|
41
|
+
instruments: () => call('GET', '/instruments'),
|
|
42
|
+
instrumentCaps: () => call('GET', '/instruments/caps'),
|
|
43
|
+
watches: () => call('GET', '/watches'),
|
|
44
|
+
/** Save attemptId BEFORE dispatch and reuse it after an uncertain response. Never retry with a new ID. */
|
|
45
|
+
buy: (input) => {
|
|
46
|
+
if (typeof input.attemptId !== 'string' || !/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(input.attemptId))
|
|
47
|
+
throw new TypeError('A saved UUID attemptId is required');
|
|
48
|
+
return call('POST', `/agents/${encodeURIComponent(input.agentId)}/buy`, { tierId: input.tierId, quantity: input.quantity, attemptId: input.attemptId });
|
|
49
|
+
},
|
|
50
|
+
payment: (intentId) => call('GET', `/payments/${encodeURIComponent(intentId)}`),
|
|
51
|
+
watch: (input) => call('POST', '/watches', input),
|
|
52
|
+
cancelWatch: (watchId) => call('DELETE', `/watches/${encodeURIComponent(watchId)}`),
|
|
53
|
+
revokeMandate: (mandateId) => call('DELETE', `/mandates/${encodeURIComponent(mandateId)}`),
|
|
54
|
+
};
|
|
55
|
+
}
|
|
56
|
+
export class AlyteConsentError extends Error {
|
|
57
|
+
code;
|
|
58
|
+
constructor(code) {
|
|
59
|
+
super(`Alyte consent: ${code}`);
|
|
60
|
+
this.code = code;
|
|
61
|
+
this.name = 'AlyteConsentError';
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
/** Mount Alyte's isolated consent surface; the full verification credential never leaves it. */
|
|
65
|
+
export function openConsent(opts) {
|
|
66
|
+
const base = baseOrigin(opts.baseUrl);
|
|
67
|
+
if (!opts.merchantId || !opts.bearer)
|
|
68
|
+
throw new TypeError('merchantId and bearer are required');
|
|
69
|
+
const doc = opts.container.ownerDocument, host = doc.defaultView;
|
|
70
|
+
if (!host)
|
|
71
|
+
throw new TypeError('container must belong to a browser document');
|
|
72
|
+
if (opts.readyTimeoutMs !== undefined && (!Number.isFinite(opts.readyTimeoutMs) || opts.readyTimeoutMs <= 0))
|
|
73
|
+
throw new TypeError('readyTimeoutMs must be positive');
|
|
74
|
+
const url = new URL(`/shop/${encodeURIComponent(opts.merchantId)}/authorize`, base);
|
|
75
|
+
url.searchParams.set('view', 'consent');
|
|
76
|
+
url.searchParams.set('embed', '1');
|
|
77
|
+
if (opts.tierId)
|
|
78
|
+
url.searchParams.set('tier', opts.tierId);
|
|
79
|
+
if (opts.quantity !== undefined) {
|
|
80
|
+
if (!Number.isInteger(opts.quantity) || opts.quantity < 1 || opts.quantity > 10)
|
|
81
|
+
throw new TypeError('quantity must be 1–10');
|
|
82
|
+
url.searchParams.set('qty', String(opts.quantity));
|
|
83
|
+
}
|
|
84
|
+
if (opts.lang)
|
|
85
|
+
url.searchParams.set('lang', opts.lang);
|
|
86
|
+
if (opts.returnUrl) {
|
|
87
|
+
const back = new URL(opts.returnUrl);
|
|
88
|
+
if (back.origin !== host.location.origin)
|
|
89
|
+
throw new TypeError('returnUrl must belong to the host origin');
|
|
90
|
+
url.searchParams.set('return', back.href);
|
|
91
|
+
}
|
|
92
|
+
for (const key of ['accent', 'background', 'surface', 'text', 'font', 'radius', 'scheme']) {
|
|
93
|
+
const value = opts.theme?.[key];
|
|
94
|
+
if ((typeof value === 'string' || typeof value === 'number') && String(value).length <= 64)
|
|
95
|
+
url.searchParams.set(key, String(value));
|
|
96
|
+
}
|
|
97
|
+
return new Promise((resolve, reject) => {
|
|
98
|
+
const iframe = doc.createElement('iframe');
|
|
99
|
+
iframe.title = 'Alyte consent';
|
|
100
|
+
iframe.src = url.href;
|
|
101
|
+
iframe.referrerPolicy = 'no-referrer';
|
|
102
|
+
iframe.style.width = '100%';
|
|
103
|
+
iframe.style.height = '640px';
|
|
104
|
+
iframe.style.border = '0';
|
|
105
|
+
let done = false, ready = false;
|
|
106
|
+
let timer;
|
|
107
|
+
const cleanup = () => { clearTimeout(timer); host.removeEventListener('message', receive); opts.signal?.removeEventListener('abort', abort); iframe.remove(); };
|
|
108
|
+
const fail = (code) => { if (!done) {
|
|
109
|
+
done = true;
|
|
110
|
+
cleanup();
|
|
111
|
+
reject(new AlyteConsentError(code));
|
|
112
|
+
} };
|
|
113
|
+
const abort = () => fail('consent_cancelled');
|
|
114
|
+
const receive = (event) => {
|
|
115
|
+
if (done || event.origin !== base || event.source !== iframe.contentWindow)
|
|
116
|
+
return;
|
|
117
|
+
const data = event.data;
|
|
118
|
+
if (!data || data.type !== 'alyte:consent' || data.merchantId !== opts.merchantId)
|
|
119
|
+
return;
|
|
120
|
+
if (data.event === 'ready') {
|
|
121
|
+
// Language changes reload this same trusted frame. Each fresh document
|
|
122
|
+
// needs bootstrap; the Alyte page accepts it only once per document.
|
|
123
|
+
ready = true;
|
|
124
|
+
clearTimeout(timer);
|
|
125
|
+
iframe.contentWindow?.postMessage({ type: 'alyte:consent', event: 'bootstrap', bearer: opts.bearer }, base);
|
|
126
|
+
}
|
|
127
|
+
else if (data.event === 'granted' && ready) {
|
|
128
|
+
if (typeof data.agentId !== 'string' || !data.agentId || typeof data.mandateId !== 'string' || !data.mandateId)
|
|
129
|
+
return;
|
|
130
|
+
done = true;
|
|
131
|
+
cleanup();
|
|
132
|
+
resolve({ agentId: data.agentId, mandateId: data.mandateId });
|
|
133
|
+
}
|
|
134
|
+
else if (data.event === 'cancelled')
|
|
135
|
+
abort();
|
|
136
|
+
else if (data.event === 'error' && typeof data.code === 'string')
|
|
137
|
+
fail(data.code);
|
|
138
|
+
else if (data.event === 'resize' && Number.isFinite(data.height))
|
|
139
|
+
iframe.style.height = `${Math.max(240, Math.min(1200, Math.ceil(data.height)))}px`;
|
|
140
|
+
else if (data.event === 'navigate' && typeof data.url === 'string') {
|
|
141
|
+
try {
|
|
142
|
+
const back = new URL(data.url);
|
|
143
|
+
if (back.origin === host.location.origin)
|
|
144
|
+
opts.onNavigate?.(back.href);
|
|
145
|
+
}
|
|
146
|
+
catch { /* Ignore malformed navigation messages. */ }
|
|
147
|
+
}
|
|
148
|
+
};
|
|
149
|
+
if (opts.signal?.aborted) {
|
|
150
|
+
abort();
|
|
151
|
+
return;
|
|
152
|
+
}
|
|
153
|
+
host.addEventListener('message', receive);
|
|
154
|
+
opts.signal?.addEventListener('abort', abort, { once: true });
|
|
155
|
+
timer = setTimeout(() => fail('consent_unavailable'), opts.readyTimeoutMs ?? 15_000);
|
|
156
|
+
iframe.addEventListener('error', () => fail('consent_unavailable'), { once: true });
|
|
157
|
+
opts.container.append(iframe);
|
|
158
|
+
});
|
|
159
|
+
}
|
package/dist/http.d.ts
ADDED
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
/** Minimal fetch transport shared by both clients. Zero dependencies. */
|
|
2
|
+
export interface ClientOptions {
|
|
3
|
+
/** Your Alyte deployment origin, e.g. https://alyte-sandbox-….run.app */
|
|
4
|
+
baseUrl: string;
|
|
5
|
+
/** The bearer credential (merchant API token or agent JWT). Keep it server-side. */
|
|
6
|
+
token: string;
|
|
7
|
+
/** Override fetch (tests, polyfills). Defaults to globalThis.fetch. */
|
|
8
|
+
fetch?: typeof globalThis.fetch;
|
|
9
|
+
}
|
|
10
|
+
/** A typed Alyte API failure: HTTP status + the stable error code from the taxonomy. */
|
|
11
|
+
export declare class AlyteApiError extends Error {
|
|
12
|
+
readonly status: number;
|
|
13
|
+
readonly code: string;
|
|
14
|
+
readonly details?: unknown | undefined;
|
|
15
|
+
constructor(status: number, code: string, message: string, details?: unknown | undefined);
|
|
16
|
+
}
|
|
17
|
+
export declare class Transport {
|
|
18
|
+
private readonly base;
|
|
19
|
+
private readonly token;
|
|
20
|
+
private readonly fetchImpl;
|
|
21
|
+
constructor(opts: ClientOptions);
|
|
22
|
+
request<T>(method: 'GET' | 'POST' | 'PATCH' | 'DELETE', path: string, body?: unknown, headers?: Record<string, string>): Promise<T>;
|
|
23
|
+
}
|
package/dist/http.js
ADDED
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
/** Minimal fetch transport shared by both clients. Zero dependencies. */
|
|
2
|
+
/** A typed Alyte API failure: HTTP status + the stable error code from the taxonomy. */
|
|
3
|
+
export class AlyteApiError extends Error {
|
|
4
|
+
status;
|
|
5
|
+
code;
|
|
6
|
+
details;
|
|
7
|
+
constructor(status, code, message, details) {
|
|
8
|
+
super(message);
|
|
9
|
+
this.status = status;
|
|
10
|
+
this.code = code;
|
|
11
|
+
this.details = details;
|
|
12
|
+
this.name = 'AlyteApiError';
|
|
13
|
+
}
|
|
14
|
+
}
|
|
15
|
+
export class Transport {
|
|
16
|
+
base;
|
|
17
|
+
token;
|
|
18
|
+
fetchImpl;
|
|
19
|
+
constructor(opts) {
|
|
20
|
+
if (!opts.baseUrl)
|
|
21
|
+
throw new Error('baseUrl is required');
|
|
22
|
+
if (!opts.token)
|
|
23
|
+
throw new Error('token is required');
|
|
24
|
+
this.base = opts.baseUrl.replace(/\/+$/, '');
|
|
25
|
+
this.token = opts.token;
|
|
26
|
+
this.fetchImpl = opts.fetch ?? globalThis.fetch;
|
|
27
|
+
}
|
|
28
|
+
async request(method, path, body, headers) {
|
|
29
|
+
const res = await this.fetchImpl(`${this.base}${path}`, {
|
|
30
|
+
method,
|
|
31
|
+
headers: {
|
|
32
|
+
authorization: `Bearer ${this.token}`,
|
|
33
|
+
...(body !== undefined ? { 'content-type': 'application/json' } : {}),
|
|
34
|
+
...headers,
|
|
35
|
+
},
|
|
36
|
+
body: body !== undefined ? JSON.stringify(body) : undefined,
|
|
37
|
+
});
|
|
38
|
+
const text = await res.text();
|
|
39
|
+
let json;
|
|
40
|
+
try {
|
|
41
|
+
json = text ? JSON.parse(text) : undefined;
|
|
42
|
+
}
|
|
43
|
+
catch {
|
|
44
|
+
json = undefined;
|
|
45
|
+
}
|
|
46
|
+
// 2xx AND 202 (sca_required rides a 202 with a normal body) succeed; everything
|
|
47
|
+
// else surfaces the taxonomy code so callers can branch on retryable-vs-terminal.
|
|
48
|
+
if (res.ok || res.status === 202)
|
|
49
|
+
return json;
|
|
50
|
+
const err = json?.error;
|
|
51
|
+
throw new AlyteApiError(res.status, err?.code ?? `http_${res.status}`, err?.message ?? `Alyte API error (HTTP ${res.status})`, err?.details ?? json);
|
|
52
|
+
}
|
|
53
|
+
}
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
export { AlyteMerchant } from './merchant.js';
|
|
2
|
+
export { AlyteAgent } from './agent.js';
|
|
3
|
+
export { AlyteApiError, type ClientOptions } from './http.js';
|
|
4
|
+
export { verifyWebhookSignature } from './webhookVerify.js';
|
|
5
|
+
export { handleWebhook, createWebhookHandler, type AlyteEventEnvelope, type PaymentSettled, type WatchFailed, type WebhookTest, type PurchaseHandlers, type OnPurchaseOptions, type WebhookResult, } from './onPurchase.js';
|
|
6
|
+
export type * from './types.js';
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,171 @@
|
|
|
1
|
+
import { type ClientOptions } from './http.js';
|
|
2
|
+
import type { BuyerSessionMint, CatalogMerchant, Merchant, EventItem, MerchantPspLink, Tier, TierKind, FeeBearer, Scheme, PaymentRow, WebhookEndpoint, MerchantInsights } from './types.js';
|
|
3
|
+
/**
|
|
4
|
+
* Merchant integration client — drives the `/v1/integration/*` surface with a
|
|
5
|
+
* console-minted API token (`merchant:read` / `merchant:write` scopes).
|
|
6
|
+
*
|
|
7
|
+
* SERVER-SIDE ONLY: the API token is a secret. Never ship it to a browser.
|
|
8
|
+
*
|
|
9
|
+
* Auth integration (the primary path): your customer is already signed in on
|
|
10
|
+
* YOUR site with YOUR auth — attest them via `buyerSessions.mint()` and redirect
|
|
11
|
+
* to the returned redeem link. No email round-trip; same buyer identity as the
|
|
12
|
+
* magic-link fallback.
|
|
13
|
+
*/
|
|
14
|
+
export declare class AlyteMerchant {
|
|
15
|
+
private readonly t;
|
|
16
|
+
constructor(opts: ClientOptions);
|
|
17
|
+
/** Your tenant's full catalog: shops → events → tiers (with restriction fields). */
|
|
18
|
+
catalog(): Promise<{
|
|
19
|
+
catalog: CatalogMerchant[];
|
|
20
|
+
}>;
|
|
21
|
+
createShop(input: {
|
|
22
|
+
name: string;
|
|
23
|
+
geo: string;
|
|
24
|
+
currency: string;
|
|
25
|
+
checkout?: 'api' | 'hosted';
|
|
26
|
+
checkoutUrl?: string;
|
|
27
|
+
allowedSchemes?: Scheme[];
|
|
28
|
+
feeBearer?: FeeBearer;
|
|
29
|
+
taxRateBps?: number;
|
|
30
|
+
}): Promise<{
|
|
31
|
+
merchant: Merchant;
|
|
32
|
+
}>;
|
|
33
|
+
/**
|
|
34
|
+
* Public discovery is OPT-IN and off by default. Flipping `discoverable: true`
|
|
35
|
+
* publishes the shop window (events, tiers, prices, availability states — never
|
|
36
|
+
* counts or PSP data) at `/v1/discovery/merchants/:id` and the ACP product feed
|
|
37
|
+
* at `…/feed.jsonl`. `imageUrl` is the shop image the feed requires.
|
|
38
|
+
*/
|
|
39
|
+
updateShopDiscovery(merchantId: string, input: {
|
|
40
|
+
discoverable?: boolean;
|
|
41
|
+
imageUrl?: string | null;
|
|
42
|
+
embedOrigin?: string | null;
|
|
43
|
+
}): Promise<{
|
|
44
|
+
merchant: Merchant;
|
|
45
|
+
}>;
|
|
46
|
+
createEvent(input: {
|
|
47
|
+
merchantId: string;
|
|
48
|
+
title: string;
|
|
49
|
+
startsAt: string;
|
|
50
|
+
}): Promise<{
|
|
51
|
+
event: EventItem;
|
|
52
|
+
}>;
|
|
53
|
+
/** `priceMinor` is integer minor units (cents) — the server refuses floats. */
|
|
54
|
+
createTier(input: {
|
|
55
|
+
eventId: string;
|
|
56
|
+
title: string;
|
|
57
|
+
priceMinor: number;
|
|
58
|
+
currency: string;
|
|
59
|
+
kind: TierKind;
|
|
60
|
+
availableCount?: number;
|
|
61
|
+
maxQtyPerPurchase?: number | null;
|
|
62
|
+
sellable?: boolean;
|
|
63
|
+
onSaleStart?: string | null;
|
|
64
|
+
onSaleEnd?: string | null;
|
|
65
|
+
allowedGeos?: string[] | null;
|
|
66
|
+
allowedSchemes?: Scheme[] | null;
|
|
67
|
+
}): Promise<{
|
|
68
|
+
tier: Tier;
|
|
69
|
+
}>;
|
|
70
|
+
updateTier(tierId: string, patch: {
|
|
71
|
+
priceMinor?: number;
|
|
72
|
+
availableCount?: number;
|
|
73
|
+
maxQtyPerPurchase?: number | null;
|
|
74
|
+
sellable?: boolean;
|
|
75
|
+
onSaleStart?: string | null;
|
|
76
|
+
onSaleEnd?: string | null;
|
|
77
|
+
allowedGeos?: string[] | null;
|
|
78
|
+
allowedSchemes?: Scheme[] | null;
|
|
79
|
+
}): Promise<{
|
|
80
|
+
tier: Tier;
|
|
81
|
+
}>;
|
|
82
|
+
deleteTier(tierId: string): Promise<{
|
|
83
|
+
ok: boolean;
|
|
84
|
+
}>;
|
|
85
|
+
deleteEvent(eventId: string): Promise<{
|
|
86
|
+
ok: boolean;
|
|
87
|
+
}>;
|
|
88
|
+
listPsps(merchantId: string): Promise<{
|
|
89
|
+
psps: MerchantPspLink[];
|
|
90
|
+
}>;
|
|
91
|
+
/**
|
|
92
|
+
* Link a PSP. `secret` (your PSP secret key) is captured straight into Alyte's
|
|
93
|
+
* secret store — only an opaque `credentialRef` is ever persisted or returned.
|
|
94
|
+
* `publishableKey` (pk_…) is public material for the card-capture iframe.
|
|
95
|
+
*/
|
|
96
|
+
linkPsp(merchantId: string, input: {
|
|
97
|
+
psp: {
|
|
98
|
+
id: string;
|
|
99
|
+
name: string;
|
|
100
|
+
};
|
|
101
|
+
rateBps?: number;
|
|
102
|
+
isDefault?: boolean;
|
|
103
|
+
secret?: string;
|
|
104
|
+
publishableKey?: string;
|
|
105
|
+
}): Promise<{
|
|
106
|
+
ok: boolean;
|
|
107
|
+
pspId: string;
|
|
108
|
+
credentialRef?: string;
|
|
109
|
+
}>;
|
|
110
|
+
/**
|
|
111
|
+
* The payments feed, newest first. Poll with `since` = the newest `createdAt`
|
|
112
|
+
* you have seen and dedupe by `intentId`. FULFIL on `status === 'authorized'`
|
|
113
|
+
* using `tierId` + `quantity` — never by price-matching. Do not advance your
|
|
114
|
+
* cursor past a row that is still `pending` (it becomes `authorized` seconds
|
|
115
|
+
* later and `since` would skip it) — or use webhooks, which only fire on
|
|
116
|
+
* authorized and have no such race.
|
|
117
|
+
*/
|
|
118
|
+
listPayments(opts?: {
|
|
119
|
+
limit?: number;
|
|
120
|
+
since?: string;
|
|
121
|
+
} | number): Promise<{
|
|
122
|
+
payments: PaymentRow[];
|
|
123
|
+
}>;
|
|
124
|
+
getPayment(intentId: string): Promise<unknown>;
|
|
125
|
+
/** Agent adoption + per-tier watch demand for a shop (counts only — the
|
|
126
|
+
* "N in line" number; never buyer identities). */
|
|
127
|
+
insights(merchantId: string): Promise<MerchantInsights>;
|
|
128
|
+
readonly webhooks: {
|
|
129
|
+
/**
|
|
130
|
+
* Register a payment.settled push endpoint (https; ≤3 active per account).
|
|
131
|
+
* The returned `secret` (whsec_…) is shown ONLY here — store it like a
|
|
132
|
+
* password and verify every delivery with `verifyWebhookSignature`.
|
|
133
|
+
*/
|
|
134
|
+
create: (input: {
|
|
135
|
+
url: string;
|
|
136
|
+
description?: string;
|
|
137
|
+
}) => Promise<{
|
|
138
|
+
webhook: WebhookEndpoint;
|
|
139
|
+
secret: string;
|
|
140
|
+
}>;
|
|
141
|
+
list: () => Promise<{
|
|
142
|
+
webhooks: WebhookEndpoint[];
|
|
143
|
+
}>;
|
|
144
|
+
/** Disable an endpoint — delivery (including queued retries) stops immediately. */
|
|
145
|
+
delete: (id: string) => Promise<{
|
|
146
|
+
ok: boolean;
|
|
147
|
+
}>;
|
|
148
|
+
};
|
|
149
|
+
readonly buyerSessions: {
|
|
150
|
+
/**
|
|
151
|
+
* Attest YOUR authenticated user → a single-use redeem link (15-min TTL).
|
|
152
|
+
* Redirect the user to `baseUrl + redeemPath`; the buyer-session cookie and
|
|
153
|
+
* the shop's authorize page take over from there.
|
|
154
|
+
* Unknown fields are rejected with 400 and error.details.fields.
|
|
155
|
+
*/
|
|
156
|
+
mint: (input: {
|
|
157
|
+
merchantId: string;
|
|
158
|
+
email: string;
|
|
159
|
+
/** The tier the buyer chose — opens the authorize page as a checkout for it. */
|
|
160
|
+
tierId?: string;
|
|
161
|
+
/** Ticket count hint (1–10), requires tierId; permission and tier limits still govern. */
|
|
162
|
+
quantity?: number;
|
|
163
|
+
/** Back-to-shop link, not an automatic redirect. HTTPS (local HTTP allowed);
|
|
164
|
+
* restricted to registered embed origins when configured. */
|
|
165
|
+
returnUrl?: string;
|
|
166
|
+
/** The buyer's language on YOUR site (BCP-47, e.g. "de" or "de-AT"), so Alyte's
|
|
167
|
+
* pages open in the same language. Presentation only. */
|
|
168
|
+
lang?: string;
|
|
169
|
+
}) => Promise<BuyerSessionMint>;
|
|
170
|
+
};
|
|
171
|
+
}
|
package/dist/merchant.js
ADDED
|
@@ -0,0 +1,107 @@
|
|
|
1
|
+
import { Transport } from './http.js';
|
|
2
|
+
/**
|
|
3
|
+
* Merchant integration client — drives the `/v1/integration/*` surface with a
|
|
4
|
+
* console-minted API token (`merchant:read` / `merchant:write` scopes).
|
|
5
|
+
*
|
|
6
|
+
* SERVER-SIDE ONLY: the API token is a secret. Never ship it to a browser.
|
|
7
|
+
*
|
|
8
|
+
* Auth integration (the primary path): your customer is already signed in on
|
|
9
|
+
* YOUR site with YOUR auth — attest them via `buyerSessions.mint()` and redirect
|
|
10
|
+
* to the returned redeem link. No email round-trip; same buyer identity as the
|
|
11
|
+
* magic-link fallback.
|
|
12
|
+
*/
|
|
13
|
+
export class AlyteMerchant {
|
|
14
|
+
t;
|
|
15
|
+
constructor(opts) {
|
|
16
|
+
this.t = new Transport(opts);
|
|
17
|
+
}
|
|
18
|
+
/** Your tenant's full catalog: shops → events → tiers (with restriction fields). */
|
|
19
|
+
catalog() {
|
|
20
|
+
return this.t.request('GET', '/v1/integration/catalog');
|
|
21
|
+
}
|
|
22
|
+
createShop(input) {
|
|
23
|
+
return this.t.request('POST', '/v1/integration/merchants', input);
|
|
24
|
+
}
|
|
25
|
+
/**
|
|
26
|
+
* Public discovery is OPT-IN and off by default. Flipping `discoverable: true`
|
|
27
|
+
* publishes the shop window (events, tiers, prices, availability states — never
|
|
28
|
+
* counts or PSP data) at `/v1/discovery/merchants/:id` and the ACP product feed
|
|
29
|
+
* at `…/feed.jsonl`. `imageUrl` is the shop image the feed requires.
|
|
30
|
+
*/
|
|
31
|
+
updateShopDiscovery(merchantId, input) {
|
|
32
|
+
return this.t.request('PATCH', `/v1/integration/merchants/${encodeURIComponent(merchantId)}`, input);
|
|
33
|
+
}
|
|
34
|
+
createEvent(input) {
|
|
35
|
+
return this.t.request('POST', '/v1/integration/events', input);
|
|
36
|
+
}
|
|
37
|
+
/** `priceMinor` is integer minor units (cents) — the server refuses floats. */
|
|
38
|
+
createTier(input) {
|
|
39
|
+
return this.t.request('POST', '/v1/integration/tiers', input);
|
|
40
|
+
}
|
|
41
|
+
updateTier(tierId, patch) {
|
|
42
|
+
return this.t.request('PATCH', `/v1/integration/tiers/${encodeURIComponent(tierId)}`, patch);
|
|
43
|
+
}
|
|
44
|
+
deleteTier(tierId) {
|
|
45
|
+
return this.t.request('DELETE', `/v1/integration/tiers/${encodeURIComponent(tierId)}`);
|
|
46
|
+
}
|
|
47
|
+
deleteEvent(eventId) {
|
|
48
|
+
return this.t.request('DELETE', `/v1/integration/events/${encodeURIComponent(eventId)}`);
|
|
49
|
+
}
|
|
50
|
+
listPsps(merchantId) {
|
|
51
|
+
return this.t.request('GET', `/v1/integration/merchants/${encodeURIComponent(merchantId)}/psps`);
|
|
52
|
+
}
|
|
53
|
+
/**
|
|
54
|
+
* Link a PSP. `secret` (your PSP secret key) is captured straight into Alyte's
|
|
55
|
+
* secret store — only an opaque `credentialRef` is ever persisted or returned.
|
|
56
|
+
* `publishableKey` (pk_…) is public material for the card-capture iframe.
|
|
57
|
+
*/
|
|
58
|
+
linkPsp(merchantId, input) {
|
|
59
|
+
return this.t.request('POST', `/v1/integration/merchants/${encodeURIComponent(merchantId)}/psps`, input);
|
|
60
|
+
}
|
|
61
|
+
/**
|
|
62
|
+
* The payments feed, newest first. Poll with `since` = the newest `createdAt`
|
|
63
|
+
* you have seen and dedupe by `intentId`. FULFIL on `status === 'authorized'`
|
|
64
|
+
* using `tierId` + `quantity` — never by price-matching. Do not advance your
|
|
65
|
+
* cursor past a row that is still `pending` (it becomes `authorized` seconds
|
|
66
|
+
* later and `since` would skip it) — or use webhooks, which only fire on
|
|
67
|
+
* authorized and have no such race.
|
|
68
|
+
*/
|
|
69
|
+
listPayments(opts) {
|
|
70
|
+
const o = typeof opts === 'number' ? { limit: opts } : (opts ?? {});
|
|
71
|
+
const q = new URLSearchParams();
|
|
72
|
+
if (o.limit)
|
|
73
|
+
q.set('limit', String(o.limit));
|
|
74
|
+
if (o.since)
|
|
75
|
+
q.set('since', o.since);
|
|
76
|
+
const qs = q.toString();
|
|
77
|
+
return this.t.request('GET', `/v1/integration/payments${qs ? `?${qs}` : ''}`);
|
|
78
|
+
}
|
|
79
|
+
getPayment(intentId) {
|
|
80
|
+
return this.t.request('GET', `/v1/integration/payments/${encodeURIComponent(intentId)}`);
|
|
81
|
+
}
|
|
82
|
+
/** Agent adoption + per-tier watch demand for a shop (counts only — the
|
|
83
|
+
* "N in line" number; never buyer identities). */
|
|
84
|
+
insights(merchantId) {
|
|
85
|
+
return this.t.request('GET', `/v1/integration/merchants/${encodeURIComponent(merchantId)}/insights`);
|
|
86
|
+
}
|
|
87
|
+
webhooks = {
|
|
88
|
+
/**
|
|
89
|
+
* Register a payment.settled push endpoint (https; ≤3 active per account).
|
|
90
|
+
* The returned `secret` (whsec_…) is shown ONLY here — store it like a
|
|
91
|
+
* password and verify every delivery with `verifyWebhookSignature`.
|
|
92
|
+
*/
|
|
93
|
+
create: (input) => this.t.request('POST', '/v1/integration/webhooks', input),
|
|
94
|
+
list: () => this.t.request('GET', '/v1/integration/webhooks'),
|
|
95
|
+
/** Disable an endpoint — delivery (including queued retries) stops immediately. */
|
|
96
|
+
delete: (id) => this.t.request('DELETE', `/v1/integration/webhooks/${encodeURIComponent(id)}`),
|
|
97
|
+
};
|
|
98
|
+
buyerSessions = {
|
|
99
|
+
/**
|
|
100
|
+
* Attest YOUR authenticated user → a single-use redeem link (15-min TTL).
|
|
101
|
+
* Redirect the user to `baseUrl + redeemPath`; the buyer-session cookie and
|
|
102
|
+
* the shop's authorize page take over from there.
|
|
103
|
+
* Unknown fields are rejected with 400 and error.details.fields.
|
|
104
|
+
*/
|
|
105
|
+
mint: (input) => this.t.request('POST', '/v1/integration/buyer-sessions', input),
|
|
106
|
+
};
|
|
107
|
+
}
|
|
@@ -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>;
|