@waffo/pancake-ts 0.1.7 → 0.1.9

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/README.md CHANGED
@@ -2,7 +2,7 @@
2
2
 
3
3
  TypeScript SDK for the Waffo Pancake Merchant of Record (MoR) payment platform.
4
4
 
5
- - Zero runtime dependencies, ESM-only, Node >= 18
5
+ - Zero runtime dependencies, ESM + CJS, Node >= 20
6
6
  - Automatic RSA-SHA256 request signing with deterministic idempotency keys
7
7
  - Full TypeScript type definitions (15 enums, 40+ interfaces)
8
8
  - Webhook verification with embedded public keys (test/prod)
@@ -15,258 +15,223 @@ npm install @waffo/pancake-ts
15
15
 
16
16
  ## Quick Start
17
17
 
18
+ > Most merchants create stores and products in the [Dashboard](https://pancake.waffo.ai/dashboard). The SDK is primarily used for **checkout integration** — redirecting buyers from your site to the Waffo checkout page.
19
+
18
20
  ```typescript
19
21
  import { WaffoPancake } from "@waffo/pancake-ts";
20
22
 
23
+ // Merchant ID and API Key are available in Dashboard > Settings > Developers
21
24
  const client = new WaffoPancake({
22
- merchantId: process.env.WAFFO_MERCHANT_ID!,
25
+ merchantId: process.env.WAFFO_MERCHANT_ID!, // MER_{base62} format
23
26
  privateKey: process.env.WAFFO_PRIVATE_KEY!,
24
27
  });
25
28
 
26
- // Create a store
27
- const { store } = await client.stores.create({ name: "My Store" });
28
-
29
- // Create a one-time product with multi-currency pricing
30
- const { product } = await client.onetimeProducts.create({
31
- storeId: store.id,
32
- name: "E-Book: TypeScript Handbook",
33
- prices: {
34
- USD: { amount: 2900, taxCategory: "digital_goods" },
35
- EUR: { amount: 2700, taxCategory: "digital_goods" },
36
- },
37
- });
38
-
39
- // Create a checkout session and redirect the buyer
40
- const session = await client.checkout.createSession({
41
- storeId: store.id,
42
- productId: product.id,
29
+ // Create a checkout session — one call handles token + session + URL
30
+ const result = await client.checkout.authenticated.create({
31
+ storeId: "STO_xxx", // from Dashboard > Stores
32
+ productId: "PROD_xxx", // from Dashboard > Products
43
33
  productType: "onetime",
44
34
  currency: "USD",
35
+ buyerIdentity: req.user.email, // your user's identity
45
36
  });
46
- // => redirect buyer to session.checkoutUrl
47
37
 
48
- // Query data via GraphQL (Query only, no Mutations)
49
- const result = await client.graphql.query<{ stores: Array<{ id: string; name: string }> }>({
50
- query: `query { stores { id name status } }`,
51
- });
38
+ // Redirect buyer to the checkout page (opens in new tab)
39
+ res.json({ checkoutUrl: result.checkoutUrl });
40
+ // => checkoutUrl includes #token=... (form pre-filled)
52
41
  ```
53
42
 
54
43
  ## Configuration
55
44
 
56
45
  | Parameter | Type | Required | Description |
57
46
  |-----------|------|----------|-------------|
58
- | `merchantId` | `string` | Yes | Merchant ID, sent as `X-Merchant-Id` header |
59
- | `privateKey` | `string` | Yes | RSA private key (see [Private Key Formats](#private-key-formats) below) |
60
- | `baseUrl` | `string` | No | API base URL (default: `https://waffo-pancake-auth-service.vercel.app`) |
47
+ | `merchantId` | `string` | Yes | Merchant ID in `MER_{base62}` format |
48
+ | `privateKey` | `string` | Yes | RSA private key in PEM format (auto-normalized, see [docs](docs/api-reference.md)) |
49
+ | `baseUrl` | `string` | No | API base URL override |
61
50
  | `fetch` | `typeof fetch` | No | Custom fetch implementation |
62
- | `webhookPublicKey` | `string \| { test?, prod? }` | No | Custom webhook public key(s) (see [Webhook Public Key Resolution](#webhook-public-key-resolution) below) |
51
+ | `webhookPublicKey` | `string \| { test?, prod? }` | No | Custom webhook public key(s) |
63
52
 
64
- ### Private Key Formats
53
+ The SDK auto-normalizes key formats: standard PEM, PKCS#1, literal `\n` from env vars, raw base64, and Windows line endings are all accepted.
65
54
 
66
- The SDK automatically normalizes `privateKey` at construction time, so all of the following formats are accepted:
55
+ ## Checkout Integration
67
56
 
68
- | Format | Example | Notes |
69
- |--------|---------|-------|
70
- | Standard PKCS#8 PEM | `-----BEGIN PRIVATE KEY-----\n...` | Recommended |
71
- | PKCS#1 PEM | `-----BEGIN RSA PRIVATE KEY-----\n...` | Also accepted |
72
- | Literal `\n` (env vars) | `"-----BEGIN PRIVATE KEY-----\\nMIIE..."` | Common when stored in `.env` or CI secrets |
73
- | Windows line endings | `\r\n` | Converted to `\n` |
74
- | Raw base64 (no headers) | `MIIEvQIBADANBgkqhki...` | Wrapped with PKCS#8 headers automatically |
75
- | Single-line base64 with headers | Header + all base64 on one line + footer | Re-wrapped to 64-char lines |
57
+ Waffo supports two checkout modes based on whether the merchant knows the buyer's identity:
76
58
 
77
- If the key is invalid or empty, the constructor throws a descriptive error immediately rather than failing silently on the first API call.
59
+ - **Merchants with their own sites** know who the buyer is they have user accounts, login systems, or collect buyer info before checkout. The merchant provides the buyer's identity upfront, and the checkout form arrives pre-filled.
60
+ - **Template stores and shared links** have no prior buyer context — the buyer arrives directly at the checkout page and fills in their own details.
78
61
 
79
- ```typescript
80
- // All of these work:
81
- new WaffoPancake({ merchantId: "m_1", privateKey: process.env.PRIVATE_KEY! }); // .env with literal \n
82
- new WaffoPancake({ merchantId: "m_1", privateKey: fs.readFileSync("key.pem", "utf8") }); // file read
83
- new WaffoPancake({ merchantId: "m_1", privateKey: rawBase64String }); // raw base64
84
- ```
62
+ | Mode | Method | Buyer Identity | Form State | Use Case |
63
+ |------|--------|---------------|------------|----------|
64
+ | **Authenticated** | `checkout.authenticated.create()` | Merchant provides | Pre-filled | Merchant sites with user accounts |
65
+ | **Anonymous** | `checkout.anonymous.create()` | Not provided | Empty | Template stores, one-time purchase links |
85
66
 
86
- ### Webhook Public Key Resolution
67
+ > **We recommend authenticated checkout whenever possible.** The most important reason: authenticated checkout binds the order to the `buyerIdentity` you provide, which is a **merchant-controlled stable identifier**. Even if the buyer changes the email on the checkout form, the order is still tied to the identity you specified. In anonymous mode, the buyer self-reports their email on the form — if they enter a different address, the system treats them as a new user, which means **previous orders become unlinked** and **subscription trial periods can be exploited** (a new email = a new user = a fresh trial).
68
+ >
69
+ > Anonymous checkout also uses the `shopper` role, which can **only create orders** (no cancellation, subscription management, or refund tickets) with a **1-minute single-use session**.
70
+ >
71
+ > | | Authenticated (`customer`) | Anonymous (`shopper`) |
72
+ > |---|---|---|
73
+ > | **Identity** | Merchant-provided, stable across orders | Self-reported email, may vary |
74
+ > | **Permissions** | Create orders, cancel orders, manage subscriptions, submit refund tickets | Create orders **only** |
75
+ > | **Session** | 5-minute TTL, auto-refreshes on each API call | 1-minute TTL, **single-use** (consumed on first API call) |
76
+ > | **Subscriptions** | Fully supported — buyers can manage, cancel, or reactivate | Not practical — buyer has no session to manage the subscription afterward |
87
77
 
88
- The SDK resolves the webhook verification public key per environment using a multi-level fallback chain:
78
+ ### Authenticated Checkout (Recommended)
89
79
 
90
- | Priority | Source | Description |
91
- |----------|--------|-------------|
92
- | 1 | `options.publicKey` | Per-call override (highest priority, skips all resolution) |
93
- | 2 | `config.webhookPublicKey[env]` | Config object per-environment key |
94
- | 3 | `config.webhookPublicKey` (string) | Config shared key (both environments) |
95
- | 4 | `WAFFO_WEBHOOK_TEST_PUBLIC_KEY` / `WAFFO_WEBHOOK_PROD_PUBLIC_KEY` | Environment variable per-environment |
96
- | 5 | `WAFFO_WEBHOOK_PUBLIC_KEY` | Environment variable shared |
97
- | 6 | Built-in hardcoded key | SDK-embedded Waffo public key (default) |
80
+ The merchant provides buyer identity the SDK issues a session token, creates a checkout session, and returns a checkout URL with the token appended as a URL fragment. One call does everything.
98
81
 
99
82
  ```typescript
100
- // Shared key for both environments
101
- new WaffoPancake({ merchantId: "m_1", privateKey: "...", webhookPublicKey: "MIIBIjAN..." });
102
-
103
- // Per-environment keys
104
- new WaffoPancake({
105
- merchantId: "m_1",
106
- privateKey: "...",
107
- webhookPublicKey: {
108
- test: process.env.WAFFO_TEST_PUB_KEY!,
109
- prod: process.env.WAFFO_PROD_PUB_KEY!,
110
- },
83
+ const result = await client.checkout.authenticated.create({
84
+ storeId: "STO_xxx",
85
+ productId: "PROD_xxx",
86
+ productType: "onetime",
87
+ currency: "USD",
88
+ buyerIdentity: "customer@example.com",
89
+ // Optional: pre-fill billing details
90
+ billingDetail: { country: "US", isBusiness: false },
111
91
  });
92
+ // result.checkoutUrl = "https://pancake.waffo.ai/store/{slug}/checkout/{sessionId}#token={JWT}"
112
93
 
113
- // Or rely on environment variables (no config needed)
114
- // export WAFFO_WEBHOOK_TEST_PUBLIC_KEY="-----BEGIN PUBLIC KEY-----\n..."
115
- // export WAFFO_WEBHOOK_PROD_PUBLIC_KEY="-----BEGIN PUBLIC KEY-----\n..."
116
- new WaffoPancake({ merchantId: "m_1", privateKey: "..." });
117
- // => SDK auto-reads from env vars, falls back to built-in keys
118
- ```
119
-
120
- ### Public Key Formats
121
-
122
- All public key inputs (config, env vars, per-call) accept the same flexible formats as private keys:
123
-
124
- | Format | Example | Notes |
125
- |--------|---------|-------|
126
- | Standard SPKI PEM | `-----BEGIN PUBLIC KEY-----\n...` | Recommended |
127
- | PKCS#1 PEM | `-----BEGIN RSA PUBLIC KEY-----\n...` | Also accepted |
128
- | Literal `\n` (env vars) | `"-----BEGIN PUBLIC KEY-----\\nMIIB..."` | Common when stored in `.env` or CI secrets |
129
- | Windows line endings | `\r\n` | Converted to `\n` |
130
- | Raw base64 (no headers) | `MIIBIjANBgkqhki...` | Wrapped with SPKI headers automatically |
131
- | Single-line base64 with headers | Header + all base64 on one line + footer | Re-wrapped to 64-char lines |
132
-
133
- ## Resources
134
-
135
- | Namespace | Methods | Description |
136
- |-----------|---------|-------------|
137
- | `client.auth` | `issueSessionToken()` | Issue a buyer session token (JWT) |
138
- | `client.stores` | `create()` `update()` `delete()` | Store management (webhook, notification, checkout settings) |
139
- | `client.storeMerchants` | `add()` `remove()` `updateRole()` | Store member management (coming soon, returns 501) |
140
- | `client.onetimeProducts` | `create()` `update()` `publish()` `updateStatus()` | One-time product CRUD with multi-currency pricing and version management |
141
- | `client.subscriptionProducts` | `create()` `update()` `publish()` `updateStatus()` | Subscription product CRUD with billing period and version management |
142
- | `client.subscriptionProductGroups` | `create()` `update()` `delete()` `publish()` | Product groups for shared trial and plan switching |
143
- | `client.orders` | `cancelSubscription()` | Order management (pending→canceled, active→canceling) |
144
- | `client.checkout` | `createSession()` | Create a checkout session with trial toggle, billing detail, and price snapshot |
145
- | `client.graphql` | `query<T>()` | Typed GraphQL queries (Query only, no Mutations) |
146
- | `client.webhooks` | `verify<T>()` | Webhook signature verification (uses configured `webhookPublicKey` or built-in keys) |
147
-
148
- See [API Reference](docs/api-reference.md) for complete parameter tables and return types.
149
-
150
- ## Checkout Integration
151
-
152
- Guide buyers from your site to the Waffo checkout page in three steps:
153
-
154
- ```
155
- 1. Issue Session Token → Obtain a buyer identity credential (JWT)
156
- 2. Create Checkout Session → Create a session and get the checkout URL
157
- 3. Open Checkout Page → Open the checkout in a new browser tab
94
+ // Frontend open in a new tab (recommended)
95
+ window.open(result.checkoutUrl, "_blank", "noopener,noreferrer");
158
96
  ```
159
97
 
160
- ### Step 1 Issue a Session Token
161
-
162
- Your backend requests a Session Token on behalf of the buyer. The token carries the buyer's identity and is used by the checkout page to load order details and place orders.
163
-
164
- ```typescript
165
- const { token } = await client.auth.issueSessionToken({
166
- storeId: "store_xxx",
167
- buyerIdentity: "customer@example.com",
168
- });
169
- ```
98
+ The token is passed via the URL fragment (after `#`), which is never sent to the server and never appears in the `Referer` header.
170
99
 
171
- ### Step 2 — Create a Checkout Session
100
+ ### Anonymous Checkout
172
101
 
173
- Create a checkout session with your API Key. The response includes a checkout URL with the token embedded in the URL fragment.
102
+ No buyer identity required the buyer fills in billing details manually on the checkout page.
174
103
 
175
104
  ```typescript
176
- import { CheckoutSessionProductType } from "@waffo/pancake-ts";
177
-
178
- const session = await client.checkout.createSession({
179
- storeId: "store_xxx",
180
- productId: "prod_xxx",
181
- productType: CheckoutSessionProductType.Onetime,
105
+ const result = await client.checkout.anonymous.create({
106
+ storeId: "STO_xxx",
107
+ productId: "PROD_xxx",
108
+ productType: "onetime",
182
109
  currency: "USD",
183
- buyerEmail: "customer@example.com",
184
- successUrl: "https://example.com/thank-you",
185
110
  });
186
- // session.checkoutUrl format:
187
- // https://waffo.ai/store/{slug}/checkout/{sessionId}#token={JWT}
188
- ```
111
+ // result.checkoutUrl = "https://pancake.waffo.ai/store/{slug}/checkout/{sessionId}"
189
112
 
190
- The token is passed via the URL fragment (after `#`), which is never sent to the server and never appears in the `Referer` header.
113
+ window.open(result.checkoutUrl, "_blank", "noopener,noreferrer");
114
+ ```
191
115
 
192
- ### Step 3 — Open Checkout Page (New Tab)
116
+ ### Opening the Checkout Page
193
117
 
194
- **We recommend opening the checkout page in a new tab** rather than navigating in the current page. Benefits:
118
+ **We recommend opening the checkout page in a new tab** rather than navigating in the current page:
195
119
 
196
120
  - Buyers can return to your site immediately after payment or if they close the checkout tab
197
121
  - Merchant page state (cart, forms, scroll position) is preserved
198
122
  - Payment flow is decoupled from the browsing experience, reducing checkout abandonment
199
123
 
200
124
  ```typescript
201
- // Frontend — recommended: open in a new tab
202
- window.open(session.checkoutUrl, "_blank", "noopener,noreferrer");
125
+ // Recommended: open in a new tab
126
+ window.open(result.checkoutUrl, "_blank", "noopener,noreferrer");
203
127
 
204
128
  // Or via an <a> tag
205
129
  // <a href={checkoutUrl} target="_blank" rel="noopener noreferrer">Proceed to Checkout</a>
206
130
  ```
207
131
 
208
- > **Not recommended:** `window.location.href = session.checkoutUrl` replaces the current page, preventing buyers from returning to your site without browser back navigation.
132
+ > **Not recommended:** `window.location.href = result.checkoutUrl` replaces the current page, preventing buyers from returning to your site without browser back navigation.
133
+
134
+ See [API Reference — Checkout](docs/api-reference.md#checkout) for full parameter tables and `BillingDetail` field requirements.
135
+
136
+ ## Webhook Verification
137
+
138
+ After a buyer completes payment, Waffo sends webhook events to your server. The SDK provides two ways to verify signatures:
209
139
 
210
- ### Complete Example (Express)
140
+ ### Standalone Function (built-in keys)
211
141
 
212
142
  ```typescript
213
- import express from "express";
214
- import { WaffoPancake, CheckoutSessionProductType } from "@waffo/pancake-ts";
143
+ import { verifyWebhook, WebhookEventType } from "@waffo/pancake-ts";
215
144
 
216
- const client = new WaffoPancake({
217
- merchantId: process.env.WAFFO_MERCHANT_ID!,
218
- privateKey: process.env.WAFFO_PRIVATE_KEY!,
219
- });
145
+ // Express (IMPORTANT: use raw body — parsed JSON breaks signature verification)
146
+ app.post("/webhooks", express.raw({ type: "application/json" }), (req, res) => {
147
+ try {
148
+ const event = verifyWebhook(
149
+ req.body.toString("utf-8"),
150
+ req.headers["x-waffo-signature"] as string,
151
+ );
220
152
 
221
- const app = express();
222
-
223
- app.post("/api/checkout", async (req, res) => {
224
- const { productId, currency, buyerEmail } = req.body;
225
-
226
- // Step 1: Issue session token
227
- const { token } = await client.auth.issueSessionToken({
228
- storeId: "store_xxx",
229
- buyerIdentity: buyerEmail,
230
- });
231
-
232
- // Step 2: Create checkout session
233
- const session = await client.checkout.createSession({
234
- storeId: "store_xxx",
235
- productId,
236
- productType: CheckoutSessionProductType.Onetime,
237
- currency,
238
- buyerEmail,
239
- successUrl: "https://example.com/thank-you",
240
- });
241
-
242
- // Return URL to frontend (frontend opens in new tab)
243
- res.json({ checkoutUrl: session.checkoutUrl });
153
+ // Respond immediately, process asynchronously
154
+ res.status(200).send("OK");
155
+
156
+ switch (event.eventType) {
157
+ case WebhookEventType.OrderCompleted:
158
+ console.log(`Order ${event.data.orderId} completed`);
159
+ break;
160
+ case WebhookEventType.SubscriptionActivated:
161
+ console.log(`Subscription activated for ${event.data.buyerEmail}`);
162
+ break;
163
+ }
164
+ } catch {
165
+ res.status(401).send("Invalid signature");
166
+ }
244
167
  });
168
+
169
+ // Next.js App Router
170
+ export async function POST(request: Request) {
171
+ const body = await request.text();
172
+ const sig = request.headers.get("x-waffo-signature");
173
+ try {
174
+ const event = verifyWebhook(body, sig);
175
+ return new Response("OK");
176
+ } catch {
177
+ return new Response("Invalid signature", { status: 401 });
178
+ }
179
+ }
245
180
  ```
246
181
 
182
+ ### Client Instance Method (multi-level key resolution)
183
+
247
184
  ```typescript
248
- // Frontend
249
- const res = await fetch("/api/checkout", {
250
- method: "POST",
251
- headers: { "Content-Type": "application/json" },
252
- body: JSON.stringify({ productId: "prod_xxx", currency: "USD", buyerEmail: "customer@example.com" }),
185
+ const client = new WaffoPancake({
186
+ merchantId: "MER_xxx",
187
+ privateKey: "...",
188
+ webhookPublicKey: {
189
+ test: process.env.WAFFO_TEST_PUB_KEY!,
190
+ prod: process.env.WAFFO_PROD_PUB_KEY!,
191
+ },
253
192
  });
254
- const { checkoutUrl } = await res.json();
255
- window.open(checkoutUrl, "_blank", "noopener,noreferrer");
193
+ const event = client.webhooks.verify(rawBody, sig, { environment: "prod" });
256
194
  ```
257
195
 
258
- ## Usage Examples
196
+ See [Webhook Guide](docs/webhook-guide.md) for event types, dual-environment key architecture, key resolution chain, retry mechanism, and best practices.
259
197
 
260
- ### AuthIssue a Buyer Session Token
198
+ ## GraphQLTyped Queries
261
199
 
262
200
  ```typescript
263
- const { token, expiresAt } = await client.auth.issueSessionToken({
264
- storeId: "store_xxx",
265
- buyerIdentity: "customer@example.com",
201
+ // Simple query
202
+ interface StoresQuery {
203
+ stores: Array<{ id: string; name: string; status: string }>;
204
+ }
205
+ const result = await client.graphql.query<StoresQuery>({
206
+ query: `query { stores { id name status } }`,
207
+ });
208
+
209
+ // Query with variables
210
+ const product = await client.graphql.query({
211
+ query: `query ($id: ID!) { onetimeProduct(id: $id) { id name prices } }`,
212
+ variables: { id: "PROD_xxx" },
213
+ });
214
+
215
+ // Nested relationships in a single request
216
+ const detail = await client.graphql.query({
217
+ query: `query ($id: ID!) {
218
+ store(id: $id) {
219
+ id name
220
+ onetimeProducts { id name status prices }
221
+ subscriptionProducts { id name billingPeriod status }
222
+ }
223
+ }`,
224
+ variables: { id: "STO_xxx" },
266
225
  });
267
226
  ```
268
227
 
269
- ### Stores Create, Update, Delete
228
+ See [GraphQL Guide](docs/graphql-guide.md) for filters, analytics queries, delivery logs, and more.
229
+
230
+ ## Programmatic Store & Product Management
231
+
232
+ > Most merchants manage stores and products in the [Dashboard](https://pancake.waffo.ai/dashboard). The following APIs are for merchants who need programmatic automation.
233
+
234
+ ### Stores
270
235
 
271
236
  ```typescript
272
237
  // Create a store
@@ -298,20 +263,20 @@ const { store: updated } = await client.stores.update({
298
263
  const { store: deleted } = await client.stores.delete({ id: store.id });
299
264
  ```
300
265
 
301
- ### Onetime Products — Create, Update, Publish
266
+ ### Products
302
267
 
303
268
  ```typescript
304
- import { TaxCategory, ProductVersionStatus } from "@waffo/pancake-ts";
269
+ import { TaxCategory, BillingPeriod, ProductVersionStatus } from "@waffo/pancake-ts";
305
270
 
306
- // Create with multi-currency pricing
271
+ // One-time product with multi-currency pricing
307
272
  const { product } = await client.onetimeProducts.create({
308
- storeId: "store_xxx",
273
+ storeId: "STO_xxx",
309
274
  name: "E-Book: TypeScript Handbook",
310
275
  description: "Complete TypeScript guide for developers",
311
276
  prices: {
312
- USD: { amount: 2900, taxCategory: TaxCategory.DigitalGoods },
313
- EUR: { amount: 2700, taxCategory: TaxCategory.DigitalGoods },
314
- JPY: { amount: 4500, taxCategory: TaxCategory.DigitalGoods },
277
+ USD: { amount: "29.00", taxCategory: TaxCategory.DigitalGoods },
278
+ EUR: { amount: "27.00", taxCategory: TaxCategory.DigitalGoods },
279
+ JPY: { amount: "4500", taxCategory: TaxCategory.DigitalGoods },
315
280
  },
316
281
  media: [{ type: "image", url: "https://example.com/cover.jpg", alt: "Book cover" }],
317
282
  metadata: { sku: "ebook-ts-001" },
@@ -321,7 +286,7 @@ const { product } = await client.onetimeProducts.create({
321
286
  await client.onetimeProducts.update({
322
287
  id: product.id,
323
288
  name: "E-Book: TypeScript Handbook v2",
324
- prices: { USD: { amount: 3900, taxCategory: "digital_goods" } },
289
+ prices: { USD: { amount: "39.00", taxCategory: "digital_goods" } },
325
290
  });
326
291
 
327
292
  // Publish test version → production
@@ -329,40 +294,32 @@ await client.onetimeProducts.publish({ id: product.id });
329
294
 
330
295
  // Deactivate
331
296
  await client.onetimeProducts.updateStatus({ id: product.id, status: ProductVersionStatus.Inactive });
332
- ```
333
297
 
334
- ### Subscription Products — Create with Billing Period
335
-
336
- ```typescript
337
- import { BillingPeriod, TaxCategory } from "@waffo/pancake-ts";
338
-
339
- const { product } = await client.subscriptionProducts.create({
340
- storeId: "store_xxx",
298
+ // Subscription product
299
+ const { product: sub } = await client.subscriptionProducts.create({
300
+ storeId: "STO_xxx",
341
301
  name: "Pro Plan",
342
302
  billingPeriod: BillingPeriod.Monthly,
343
- prices: { USD: { amount: 999, taxCategory: TaxCategory.SaaS } },
344
- description: "Unlimited access to all features",
303
+ prices: { USD: { amount: "9.99", taxCategory: TaxCategory.SaaS } },
345
304
  });
346
-
347
- // Same update/publish/updateStatus pattern as onetime products
348
- await client.subscriptionProducts.publish({ id: product.id });
305
+ await client.subscriptionProducts.publish({ id: sub.id });
349
306
  ```
350
307
 
351
- ### Subscription Product Groups — Shared Trial & Plan Switching
308
+ ### Subscription Product Groups
352
309
 
353
310
  ```typescript
354
311
  // Create a group linking related subscription tiers
355
312
  const { group } = await client.subscriptionProductGroups.create({
356
- storeId: "store_xxx",
313
+ storeId: "STO_xxx",
357
314
  name: "Pro Plans",
358
315
  rules: { sharedTrial: true },
359
- productIds: ["prod_aaa", "prod_bbb"],
316
+ productIds: ["PROD_aaa", "PROD_bbb"],
360
317
  });
361
318
 
362
319
  // Update members (full replacement, not merge)
363
320
  await client.subscriptionProductGroups.update({
364
321
  id: group.id,
365
- productIds: ["prod_aaa", "prod_bbb", "prod_ccc"],
322
+ productIds: ["PROD_aaa", "PROD_bbb", "PROD_ccc"],
366
323
  });
367
324
 
368
325
  // Publish / delete
@@ -370,161 +327,15 @@ await client.subscriptionProductGroups.publish({ id: group.id });
370
327
  await client.subscriptionProductGroups.delete({ id: group.id });
371
328
  ```
372
329
 
373
- ### Orders — Cancel a Subscription
330
+ ### Orders
374
331
 
375
332
  ```typescript
376
333
  const { orderId, status } = await client.orders.cancelSubscription({
377
- orderId: "order_xxx",
334
+ orderId: "ORD_xxx",
378
335
  });
379
336
  // status: "canceled" (was pending) or "canceling" (was active, PSP notified)
380
337
  ```
381
338
 
382
- ### Checkout — Create a Session
383
-
384
- ```typescript
385
- import { CheckoutSessionProductType } from "@waffo/pancake-ts";
386
-
387
- // One-time product checkout
388
- const session = await client.checkout.createSession({
389
- storeId: "store_xxx",
390
- productId: "prod_xxx",
391
- productType: CheckoutSessionProductType.Onetime,
392
- currency: "USD",
393
- buyerEmail: "customer@example.com",
394
- successUrl: "https://example.com/thank-you",
395
- });
396
- // => redirect buyer to session.checkoutUrl
397
-
398
- // Subscription with trial and billing detail
399
- const subSession = await client.checkout.createSession({
400
- storeId: "store_xxx",
401
- productId: "prod_yyy",
402
- productType: CheckoutSessionProductType.Subscription,
403
- currency: "USD",
404
- withTrial: true,
405
- billingDetail: { country: "US", isBusiness: false, state: "CA", postcode: "94105" },
406
- });
407
- ```
408
-
409
- ### GraphQL — Typed Queries
410
-
411
- ```typescript
412
- // Simple query
413
- interface StoresQuery {
414
- stores: Array<{ id: string; name: string; status: string }>;
415
- }
416
- const result = await client.graphql.query<StoresQuery>({
417
- query: `query { stores { id name status } }`,
418
- });
419
-
420
- // Query with variables
421
- const product = await client.graphql.query({
422
- query: `query ($id: ID!) { onetimeProduct(id: $id) { id name prices } }`,
423
- variables: { id: "prod_xxx" },
424
- });
425
-
426
- // Nested relationships in a single request
427
- const detail = await client.graphql.query({
428
- query: `query ($id: ID!) {
429
- store(id: $id) {
430
- id name
431
- onetimeProducts { id name status prices }
432
- subscriptionProducts { id name billingPeriod status }
433
- }
434
- }`,
435
- variables: { id: "store_xxx" },
436
- });
437
- ```
438
-
439
- See [GraphQL Guide](docs/graphql-guide.md) for introspection, filters, pagination, and more examples.
440
-
441
- ## Webhook Verification
442
-
443
- Two ways to verify webhooks: the **standalone function** `verifyWebhook()` with built-in public keys, or the **client instance method** `client.webhooks.verify()` which uses the configured `webhookPublicKey`.
444
-
445
- ### Option A — Standalone Function (built-in keys)
446
-
447
- ```typescript
448
- import { verifyWebhook, WebhookEventType } from "@waffo/pancake-ts";
449
-
450
- // Express (IMPORTANT: use raw body — parsed JSON breaks signature verification)
451
- app.post("/webhooks", express.raw({ type: "application/json" }), (req, res) => {
452
- try {
453
- const event = verifyWebhook(
454
- req.body.toString("utf-8"),
455
- req.headers["x-waffo-signature"] as string,
456
- );
457
-
458
- // Respond immediately, process asynchronously
459
- res.status(200).send("OK");
460
-
461
- // Use event.id for idempotent deduplication
462
- switch (event.eventType) {
463
- case WebhookEventType.OrderCompleted:
464
- console.log(`Order ${event.data.orderId} completed`);
465
- break;
466
- case WebhookEventType.SubscriptionActivated:
467
- console.log(`Subscription activated for ${event.data.buyerEmail}`);
468
- break;
469
- case WebhookEventType.SubscriptionCanceled:
470
- console.log(`Subscription canceled: ${event.data.orderId}`);
471
- break;
472
- case WebhookEventType.RefundSucceeded:
473
- console.log(`Refund ${event.data.amount} ${event.data.currency}`);
474
- break;
475
- }
476
- } catch {
477
- res.status(401).send("Invalid signature");
478
- }
479
- });
480
-
481
- // Next.js App Router
482
- export async function POST(request: Request) {
483
- const body = await request.text();
484
- const sig = request.headers.get("x-waffo-signature");
485
- try {
486
- const event = verifyWebhook(body, sig);
487
- // handle event ...
488
- return new Response("OK");
489
- } catch {
490
- return new Response("Invalid signature", { status: 401 });
491
- }
492
- }
493
-
494
- // Options: specify environment, disable/customize replay protection
495
- const event = verifyWebhook(body, sig, { environment: "prod" });
496
- const event = verifyWebhook(body, sig, { toleranceMs: 0 }); // disable replay check
497
- ```
498
-
499
- ### Option B — Client Instance Method (multi-level key resolution)
500
-
501
- `client.webhooks.verify()` uses the [multi-level fallback chain](#webhook-public-key-resolution) automatically: config keys → env vars → built-in keys.
502
-
503
- ```typescript
504
- // Per-environment keys via config
505
- const client = new WaffoPancake({
506
- merchantId: process.env.WAFFO_MERCHANT_ID!,
507
- privateKey: process.env.WAFFO_PRIVATE_KEY!,
508
- webhookPublicKey: {
509
- test: process.env.WAFFO_TEST_PUB_KEY!,
510
- prod: process.env.WAFFO_PROD_PUB_KEY!,
511
- },
512
- });
513
- const event = client.webhooks.verify(rawBody, sig, { environment: "prod" });
514
-
515
- // Or rely on env vars (WAFFO_WEBHOOK_TEST_PUBLIC_KEY / WAFFO_WEBHOOK_PROD_PUBLIC_KEY)
516
- const client2 = new WaffoPancake({
517
- merchantId: process.env.WAFFO_MERCHANT_ID!,
518
- privateKey: process.env.WAFFO_PRIVATE_KEY!,
519
- });
520
- const event2 = client2.webhooks.verify(rawBody, sig); // auto-detect environment
521
-
522
- // Per-call override (highest priority, skips all resolution)
523
- const event3 = client.webhooks.verify(rawBody, sig, { publicKey: oneOffKey });
524
- ```
525
-
526
- See [Webhook Guide](docs/webhook-guide.md) for event types, signature algorithm, public key resolution, and best practices.
527
-
528
339
  ## Error Handling
529
340
 
530
341
  API errors throw `WaffoPancakeError` with the HTTP status code and a call-stack-ordered errors array.
@@ -543,25 +354,44 @@ try {
543
354
  }
544
355
  ```
545
356
 
357
+ ## Resources
358
+
359
+ | Namespace | Methods | Description |
360
+ |-----------|---------|-------------|
361
+ | `client.checkout.authenticated` | `create()` | Authenticated checkout (recommended) |
362
+ | `client.checkout.anonymous` | `create()` | Anonymous checkout |
363
+ | `client.checkout` | `createSession()` | Low-level checkout session |
364
+ | `client.webhooks` | `verify<T>()` | Webhook signature verification |
365
+ | `client.graphql` | `query<T>()` | Typed GraphQL queries |
366
+ | `client.auth` | `issueSessionToken()` | Issue a buyer session token (JWT) |
367
+ | `client.stores` | `create()` `update()` `delete()` | Store management |
368
+ | `client.storeMerchants` | `add()` `remove()` `updateRole()` | Store members (coming soon) |
369
+ | `client.onetimeProducts` | `create()` `update()` `publish()` `updateStatus()` | One-time products |
370
+ | `client.subscriptionProducts` | `create()` `update()` `publish()` `updateStatus()` | Subscription products |
371
+ | `client.subscriptionProductGroups` | `create()` `update()` `delete()` `publish()` | Product groups |
372
+ | `client.orders` | `cancelSubscription()` | Order management |
373
+
374
+ ## Documentation
375
+
376
+ | Document | Content |
377
+ |----------|---------|
378
+ | [API Reference](docs/api-reference.md) | Complete method reference — parameters, return types, `BillingDetail` fields |
379
+ | [GraphQL Guide](docs/graphql-guide.md) | Queries, filters, analytics, introspection, delivery logs |
380
+ | [Webhook Guide](docs/webhook-guide.md) | Signature verification, event types, key resolution, retry mechanism |
381
+ | [Changelog](CHANGELOG.md) | Version history and migration guides |
382
+
546
383
  ## Exports
547
384
 
548
- ### Classes
385
+ ### Classes & Functions
549
386
 
550
387
  | Export | Description |
551
388
  |--------|-------------|
552
389
  | `WaffoPancake` | SDK client with auto-signed requests |
553
390
  | `WaffoPancakeError` | API error with status and call-stack errors |
554
-
555
- ### Functions
556
-
557
- | Export | Description |
558
- |--------|-------------|
559
- | `verifyWebhook` | RSA-SHA256 webhook signature verification |
391
+ | `verifyWebhook` | Standalone webhook signature verification |
560
392
 
561
393
  ### Enums
562
394
 
563
- Runtime-accessible values. Both `Enum.Value` and string literal syntax are supported.
564
-
565
395
  | Export | Values |
566
396
  |--------|--------|
567
397
  | `Environment` | `Test`, `Prod` |
@@ -571,18 +401,18 @@ Runtime-accessible values. Both `Enum.Value` and string literal syntax are suppo
571
401
  | `EntityStatus` | `Active`, `Inactive`, `Suspended` |
572
402
  | `StoreRole` | `Owner`, `Admin`, `Member` |
573
403
  | `OnetimeOrderStatus` | `Pending`, `Completed`, `Canceled` |
574
- | `SubscriptionOrderStatus` | `Pending`, `Active`, `Canceling`, `Canceled`, `PastDue`, `Expired` |
404
+ | `SubscriptionOrderStatus` | `Pending`, `Active`, `Canceling`, `PastDue`, `Closed`, `Canceled`, `Expired` |
575
405
  | `PaymentStatus` | `Pending`, `Succeeded`, `Failed`, `Canceled` |
576
406
  | `RefundTicketStatus` | `Pending`, `Approved`, `Rejected`, `Processing`, `Succeeded`, `Failed` |
577
407
  | `RefundStatus` | `Succeeded`, `Failed` |
578
408
  | `MediaType` | `Image`, `Video` |
579
409
  | `CheckoutSessionProductType` | `Onetime`, `Subscription` |
580
- | `ErrorLayer` | `Gateway`, `User`, `Store`, `Product`, `Order`, `GraphQL`, `Resource`, `Email` |
410
+ | `ErrorLayer` | `Gateway`, `User`, `Store`, `Product`, `Order`, `Ticket`, `GraphQL`, `Resource`, `Email` |
581
411
  | `WebhookEventType` | `OrderCompleted`, `SubscriptionActivated`, `SubscriptionPaymentSucceeded`, `SubscriptionCanceling`, `SubscriptionUncanceled`, `SubscriptionUpdated`, `SubscriptionCanceled`, `SubscriptionPastDue`, `RefundSucceeded`, `RefundFailed` |
582
412
 
583
413
  ### Types
584
414
 
585
- Key types: `WaffoPancakeConfig`, `WebhookPublicKeys`, `VerifyWebhookOptions`, `WebhookEvent<T>`, `Store`, `OnetimeProductDetail`, `SubscriptionProductDetail`, `CheckoutSessionResult`, `GraphQLResponse<T>`, and 30+ more. See [API Reference — Types](docs/api-reference.md#types) for the full list.
415
+ Key types: `WaffoPancakeConfig`, `AuthenticatedCheckoutParams`, `AuthenticatedCheckoutResult`, `AnonymousCheckoutParams`, `CheckoutSessionResult`, `Store`, `OnetimeProductDetail`, `SubscriptionProductDetail`, `WebhookEvent<T>`, `GraphQLResponse<T>`, and 30+ more. See [API Reference](docs/api-reference.md#types) for the full list.
586
416
 
587
417
  ## Development
588
418
 
@@ -591,7 +421,7 @@ npm run lint # ESLint 9 (TypeScript ESLint + import order + JSDoc)
591
421
  npm run test # Vitest
592
422
  npm run test:watch # Vitest in watch mode
593
423
  npm run test:coverage # Vitest with v8 coverage
594
- npm run build # TypeScript compilation to dist/
424
+ npm run build # tsup ESM + CJS + DTS
595
425
  ```
596
426
 
597
427
  ## Project Structure
@@ -615,11 +445,13 @@ src/
615
445
  ├── subscription-product-groups.ts
616
446
  ├── orders.ts
617
447
  ├── checkout.ts
448
+ ├── checkout-anonymous.ts
449
+ ├── checkout-authenticated.ts
618
450
  ├── graphql.ts
619
451
  └── webhooks.ts
620
452
  docs/
621
453
  ├── api-reference.md # Complete API reference
622
- ├── graphql-guide.md # GraphQL usage guide
454
+ ├── graphql-guide.md # GraphQL queries & analytics
623
455
  └── webhook-guide.md # Webhook verification guide
624
456
  ```
625
457