This is the official Waffo Pancake Skill file. The content stays aligned with the team-managed source skill and is distributed as a standard English
SKILL.md.Available Files
| File | Purpose |
|---|---|
SKILL.md | Complete Waffo Pancake integration guide for AI agents |
llms-full.txt | Full AI-readable documentation snapshot |
SKILL.md: The Complete Guide
This is the main skill file for AI-assisted Pancake integrations. It includes:- Merchant authentication and required environment variables
- Store setup and product creation guidance
- Product creation for one-time and subscription products
- Checkout session creation (authenticated, anonymous and low-level)
- Discounts with coupons and promotion codes
- Subscription plan changes (upgrade / downgrade) and customer self-service
- Webhook verification, reliable event processing and local testing with the CLI
- GraphQL queries, error handling, and integration rules
Quick Reference
Save the standardSKILL.md locally after copying or downloading it from this page.
SKILL.md Preview
Inspect the complete standard
SKILL.md source directly on this page before downloading it.↓ View Full SKILL.md BelowWaffo Pancake Skill
Use the complete skill file in your AI coding workflow. You can copy the full skill content or download it directly as a standard
SKILL.md file.What’s Inside
- Platform overview and supported billing models
- SDK-first setup flow and direct dashboard-to-checkout flow
- Merchant authentication and environment setup
- Product, checkout, and webhook implementation examples
- Test cards, common gotchas, and critical integration rules
Installation
mkdir -p ~/.waffo/skills
SKILL.md file from this page.
For AI Agents
- Save
SKILL.mdlocally so you can reference it without re-fetching every conversation. - Use the Skill first when the human asks about Pancake products, checkout, subscriptions, webhooks, or merchant setup.
- Follow the product, checkout, and webhook flows exactly as written in the Skill file.
- For store operations that don’t need application code — listing products, creating coupons, configuring test webhooks — use the Pancake CLI:
pancake commands --jsonlists every command andpancake schema <command.id> --jsonreturns its input contract, so nothing has to be guessed.
Full Documentation
For a full documentation snapshot beyond the skill file itself:curl -s https://docs.waffo.ai/llms-full.txt
Full SKILL.md Content
Use the built-in copy control on the code block to copy the full Skill.---
name: waffo-pancake
description: "Step-by-step guide for integrating @waffo/pancake-ts into any TypeScript/Node.js project — covers store setup, products, checkout, discounts (coupons and promotion codes), subscription plan changes (upgrade/downgrade), customer self-service, webhooks, and GraphQL queries. Use when implementing payment processing, checkout flows, subscriptions, discounts, plan changes, webhooks, product management, or any Waffo Pancake API integration."
user-invokable: true
args: "[scenario]"
---
# Waffo Pancake SDK Integration
You are integrating the `@waffo/pancake-ts` payment SDK into a TypeScript project. Follow these steps exactly. The SDK uses Merchant API Key authentication — all requests are signed automatically.
**Trigger when:** code imports `@waffo/pancake-ts`, user asks about Waffo Pancake payments, checkout integration, webhook verification, or product/order management.
**Do NOT trigger when:** general payment concepts, other payment SDKs (Stripe, PayPal), or frontend-only UI work unrelated to payment logic.
---
## When to Use This SDK
Waffo Pancake is a merchant-of-record payment platform. Use it when your project needs:
- **SaaS subscription billing** — monthly/yearly plans with upgrade/downgrade, cancellation, and renewal handling
- **Digital product sales** — one-time purchases for e-books, templates, courses, software licenses
- **Per-usage or per-download payments** — charge users per action like downloading a file or API call credits
- **Hybrid models** — combine subscriptions with one-time purchases
- **Discounts** — coupons and promotion codes for launches, campaigns, KOL codes or win-backs
- **Plan changes** — let subscribers upgrade, downgrade or switch billing period, with merchant-priced or self-service links
### Example Use Cases
| Project Type | Payment Model | Products to Create |
|---|---|---|
| AI Skills marketplace | Per-download + Pro subscription | 1 one-time product ($0.99/download) + 2 subscription products (monthly/yearly) |
| Online course platform | One-time purchase per course | 1 one-time product per course ($29–$199) |
| SaaS tool (Starter/Pro/Enterprise) | Subscription tiers | 3 subscription products with a product group for plan switching |
| Design template shop | One-time per template | 1 one-time product per template |
| API service with usage credits | Credit packs + subscription | 1 one-time product per credit pack + subscription for monthly quota |
| Newsletter / community | Membership subscription | 1 monthly + 1 yearly subscription product |
---
## Installation
```bash
npm install @waffo/pancake-ts
```
Zero dependencies. Works in Node.js 18+. Server-side only — never expose the private key to the browser.
---
## Getting Started
You only need **two values** to start:
```bash
WAFFO_MERCHANT_ID=<your-merchant-id>
WAFFO_PRIVATE_KEY=<your-rsa-private-key>
```
Both live on Dashboard → API & Development (API 与开发), inside the "Create an API Key" section.
`WAFFO_MERCHANT_ID` means your **Merchant ID**, not `storeId` and not a store identifier from a URL. `storeId` is still part of the current API model for store and product management flows, so do not confuse the two.
For the first working integration, only these two env vars need to exist: `WAFFO_MERCHANT_ID` and `WAFFO_PRIVATE_KEY`. Store IDs and Product IDs are runtime values you can keep in code, app config, or your own database.
**Client options.** The API key decides the environment: a test-mode key only reaches test data and a production key only production data, so merchant calls take no `environment` option (only `client.customer(token, { environment })` does). `baseUrl` defaults to `https://api.waffo.ai`; set it only when you were explicitly given another gateway (for example a UAT preview), and use a key issued for that same environment.
### Store Selection Rule
When creating products, first determine whether the merchant already has one or more stores:
- If the merchant has no store yet, create a store first.
- If the merchant has exactly one store, use that store automatically.
- If the merchant has multiple stores, ask which store the product should be created in before calling any product creation API.
Do not guess the target store when multiple stores exist.
### Path A: Create Everything via SDK (Starting Fresh)
```typescript
import { WaffoPancake, BillingPeriod, TaxCategory } from "@waffo/pancake-ts";
const client = new WaffoPancake({
merchantId: process.env.WAFFO_MERCHANT_ID!,
privateKey: process.env.WAFFO_PRIVATE_KEY!,
});
// 1. Create a store
const { store } = await client.stores.create({ name: "My SaaS" });
console.log("Store ID:", store.id); // Save this
// 2. Create products
const { product: monthly } = await client.subscriptionProducts.create({
storeId: store.id,
name: "Pro Monthly",
billingPeriod: BillingPeriod.Monthly,
prices: { USD: { amount: "9.99", taxCategory: TaxCategory.SaaS } },
});
const { product: yearly } = await client.subscriptionProducts.create({
storeId: store.id,
name: "Pro Yearly",
billingPeriod: BillingPeriod.Yearly,
prices: { USD: { amount: "99.00", taxCategory: TaxCategory.SaaS } },
});
console.log("Monthly Product ID:", monthly.id); // Save this
console.log("Yearly Product ID:", yearly.id); // Save this
// 3. Create a checkout session
const session = await client.checkout.createSession({
productId: monthly.id,
currency: "USD",
});
// Redirect customer to session.checkoutUrl
```
### Path B: Use Existing Products from Dashboard
If you've already created products in the Dashboard, copy the Product ID and go straight to checkout. In this flow, you still only need the same two env vars above:
```typescript
const client = new WaffoPancake({
merchantId: process.env.WAFFO_MERCHANT_ID!,
privateKey: process.env.WAFFO_PRIVATE_KEY!,
});
const session = await client.checkout.createSession({
productId: "PROD_xxx_from_dashboard",
currency: "USD",
buyerEmail: "customer@example.com",
successUrl: "https://myapp.com/welcome",
});
// Redirect customer to session.checkoutUrl
```
---
## PEM Key Handling
The private key is RSA PEM format. Multiple approaches for environment variables:
**Option A: Escaped newlines**
```
WAFFO_PRIVATE_KEY="-----BEGIN PRIVATE KEY-----\nMIIEv...\n-----END PRIVATE KEY-----"
```
**Option B: Base64 encode the entire PEM (recommended for CI/CD)**
```bash
# Encode
cat private.pem | base64 | tr -d '\n'
# Set env var
WAFFO_PRIVATE_KEY_BASE64=LS0tLS1CRUdJTi...
```
```typescript
const privateKey = Buffer.from(process.env.WAFFO_PRIVATE_KEY_BASE64!, "base64").toString("utf-8");
const client = new WaffoPancake({ merchantId, privateKey });
```
**Option C: File path (local development)**
```typescript
import { readFileSync } from "fs";
const privateKey = readFileSync("./keys/private.pem", "utf-8");
const client = new WaffoPancake({ merchantId, privateKey });
```
The SDK auto-normalizes all formats (PEM headers, raw base64, literal `\n`, Windows line endings). The constructor throws immediately if the key is invalid.
---
## Available Resources
| Namespace | Methods | Description |
|-----------|---------|-------------|
| `client.checkout.authenticated` | `create()` `createPlanChange()` | Checkout / plan change for a signed-in customer (recommended) |
| `client.checkout.anonymous` | `create()` | Checkout without customer identity (shared links, template stores) |
| `client.checkout` | `createSession()` `createPlanChangeSession()` | Low-level checkout session / plan change link |
| `client.auth` | `issueSessionToken()` `createCustomerPortalLink()` | Customer session token / customer portal SSO link |
| `client.customer(token, opts?)` | `cancelSubscription()` `reactivateSubscription()` `cancelOnetimeOrder()` `createRefundTicket()` `resubmitRefundTicket()` `createPlanChangeSession()` | Customer self-service on your own site |
| `client.stores` | `create()` `update()` `delete()` | Store management (webhook, notification, checkout settings) |
| `client.onetimeProducts` | `create()` `update()` `publish()` `updateStatus()` | One-time product CRUD with multi-currency pricing |
| `client.subscriptionProducts` | `create()` `update()` `publish()` `updateStatus()` | Subscription product CRUD with billing period |
| `client.subscriptionProductGroups` | `create()` `update()` `delete()` `publish()` | Product groups for shared trial and plan switching |
| `client.coupons` | `create()` `update()` `deactivate()` | Coupons (percentage or fixed-amount discounts) |
| `client.promotionCodes` | `create()` `generate()` `deactivate()` | Promotion codes with buyer restrictions |
| `client.orders` | `cancelSubscription()` | Cancel subscription (pending→canceled, active→canceling) |
| `client.graphql` | `query<T>()` | Typed GraphQL queries (read-only) |
| `client.webhooks` | `verify<T>()` `add()` `update()` `remove()` | Webhook config + signature verification |
---
## Full API Reference
### Stores
```typescript
// Create
const { store } = await client.stores.create({ name: "My Store" });
// Update (partial — only provided fields change)
const { store } = await client.stores.update({
id: "store_id",
name: "New Name",
});
// Soft-delete
const { store } = await client.stores.delete({ id: "store_id" });
```
### One-Time Products
Set each currency independently in `prices`. Use decimal strings in the currency’s display unit, such as `"29.00"` for USD 29 and `"4500"` for JPY 4,500. When updating prices, include every currency you want to keep.
```typescript
import { ProductVersionStatus, TaxCategory } from "@waffo/pancake-ts";
// Create
const { product } = await client.onetimeProducts.create({
storeId: "STO_xxx",
name: "E-Book",
description: "A great e-book",
prices: {
USD: { amount: "29.00", taxCategory: TaxCategory.Ebook },
JPY: { amount: "4500", taxCategory: TaxCategory.Ebook },
},
successUrl: "https://example.com/thanks",
metadata: { sku: "EB-001" },
});
// Update (creates new version; no-op if unchanged)
await client.onetimeProducts.update({
id: product.id,
name: "E-Book v2",
prices: {
USD: { amount: "39.00", taxCategory: TaxCategory.Ebook },
JPY: { amount: "4500", taxCategory: TaxCategory.Ebook },
},
});
// Publish test version to production (one-way)
await client.onetimeProducts.publish({ id: product.id });
// Activate / deactivate
await client.onetimeProducts.updateStatus({
id: product.id,
status: ProductVersionStatus.Inactive,
});
```
**taxCategory** is the `TaxCategory` enum: `DigitalGoods` | `SaaS` | `Software` | `Ebook` | `OnlineCourse` | `Consulting` | `ProfessionalService` (wire values `digital_goods` … `professional_service`). `billingPeriod` is the `BillingPeriod` enum: `Weekly` | `Monthly` | `Quarterly` | `Yearly`. Under `strict` TypeScript the bare string literals do not type-check — import both enums from `@waffo/pancake-ts`.
### Subscription Products
```typescript
// Create
const { product } = await client.subscriptionProducts.create({
storeId: "store_id",
name: "Pro Monthly",
billingPeriod: BillingPeriod.Monthly, // BillingPeriod.Weekly | .Monthly | .Quarterly | .Yearly
prices: {
USD: { amount: "9.99", taxCategory: TaxCategory.SaaS },
},
metadata: { trialDays: 14 }, // optional trial
});
// Update, publish, updateStatus — same pattern as one-time products
```
### Subscription Product Groups
Groups enable shared trials and plan switching between subscription products. `rules.sharedTrial` shares one trial across the group; `rules.selfServicePlanChange` lets customers change plans within the group themselves (see Plan Changes). On update, rules merge switch by switch.
```typescript
// Create group
const { group } = await client.subscriptionProductGroups.create({
storeId: "store_id",
name: "Pro Plans",
rules: { sharedTrial: true, selfServicePlanChange: true },
productIds: ["monthly_product_id", "yearly_product_id"],
});
// Update (productIds is a full replacement)
await client.subscriptionProductGroups.update({
id: "group_id",
productIds: ["monthly_id", "quarterly_id", "yearly_id"],
});
// Publish to production (supports repeated UPSERT)
await client.subscriptionProductGroups.publish({ id: "group_id" });
// Delete (physical delete, not soft)
await client.subscriptionProductGroups.delete({ id: "group_id" });
```
### Checkout (Recommended Entry Points)
Pick the mode by whether you know who the customer is:
| Mode | Method | Customer identity | Use case |
|------|--------|-------------------|----------|
| Authenticated (recommended) | `client.checkout.authenticated.create()` | You pass a stable `buyerIdentity` (your user ID) | Sites with user accounts |
| Anonymous | `client.checkout.anonymous.create()` | Customer types it on the checkout page | Shared purchase links, template stores |
Authenticated checkout binds orders to your `buyerIdentity`, so changing the email on the form cannot unlink past orders or re-use a trial, and the customer can later self-serve (cancel, refund, change plan). `buyerIdentity` is not shown on the page — pass `buyerEmail` to pre-fill the email field.
```typescript
const result = await client.checkout.authenticated.create({
productId: "PROD_xxx",
currency: "USD",
buyerIdentity: user.id, // stable ID from your system
buyerEmail: user.email, // optional, pre-fills the form
orderMerchantExternalId: "ORDER-2026-00891", // optional, your own reference (max 128 chars)
});
// result.checkoutUrl carries the session token after "#" — redirect the customer to it
const anon = await client.checkout.anonymous.create({ productId: "PROD_xxx", currency: "USD" });
```
Both accept `priceSnapshot`, `withTrial`, `billingDetail`, `successUrl`, `metadata`, and the discount fields below.
### Checkout Sessions (Low-Level)
`createSession()` is the low-level call behind the entry points above. It creates a payment page; redirect the customer to `checkoutUrl`.
```typescript
const session = await client.checkout.createSession({
productId: "product_id",
currency: "USD",
buyerEmail: "buyer@example.com", // optional, pre-fills email
successUrl: "https://example.com/thanks", // redirect after payment
metadata: { orderId: "internal-123" }, // custom key-value pairs
// Optional overrides:
priceSnapshot: { amount: "19.99", taxCategory: TaxCategory.SaaS }, // dynamic pricing
billingDetail: { country: "US", postcode: "10001", isBusiness: false },
expiresInSeconds: 3600, // default: 86400 (24 hours), recommended: 60–604800
withTrial: true, // for subscriptions with trial
darkMode: true, // true=dark / false=light / omit=store default
});
// session.checkoutUrl — redirect customer here
// session.sessionId — for tracking
// session.expiresAt — ISO 8601 expiry
```
**Parameter priority:**
| Parameter | Purpose | Notes |
|-----------|---------|-------|
| `priceSnapshot` | Override product price (dynamic pricing) | Highest priority — ignores product's set price |
| `currency` | Specify checkout currency | Required |
| `buyerEmail` | Pre-fill consumer email | Optional |
| `billingDetail` | Pre-fill billing info | Optional |
| `successUrl` | Redirect after payment | Overrides product-level successUrl |
| `metadata` | Custom key-value pairs | Passed through to webhook `event.data` |
| `withTrial` | Enable trial period | Overrides product-level trial settings |
| `expiresInSeconds` | Session expiration | Default 86400 (24 h), recommended 60–604800 (1 min to 7 days) |
| `darkMode` | Checkout dark mode | `true`=dark / `false`=light / omit=store default |
| `couponId` | Apply a coupon the customer cannot change | `CPN_` ID; never together with the two fields below |
| `promotionCode` | Prefill a promotion code (code string) | Locked unless `allowPromotionCodes: true` |
| `allowPromotionCodes` | Show a code entry field | Defaults to `false` for API Key sessions |
### Discounts: Coupons & Promotion Codes
A **coupon** defines the discount (percentage or fixed amount per currency) and how long it lasts on a subscription. It has its own `code` (random when omitted); its only limits are `redeemBy` and `maxRedemptions`. **Promotion codes** are extra codes for a coupon that carry buyer restrictions (emails, per-customer limit, minimum amount). Create up to 20 together with the coupon, or later with `client.promotionCodes`. Deactivation is permanent and frees the codes for reuse. Coupons are scoped to a store and an environment (test / prod).
```typescript
import { CouponDiscountType, CouponDuration } from "@waffo/pancake-ts";
const { coupon } = await client.coupons.create(
{
storeId: "STO_xxx",
name: "Black Friday 20% off",
discount: { type: CouponDiscountType.Percentage, percentOff: 20 },
// or { type: CouponDiscountType.FixedAmount, amountOff: { USD: "5.00" } }
duration: CouponDuration.Repeating, // Once | Repeating | Forever (subscriptions)
durationInPeriods: 3,
code: "BF2026",
productIds: ["PROD_xxx"], // optional: limit to these products
promotionCodes: [{ code: "BF-NEW", restrictions: { perCustomerLimit: 1 } }],
},
{ idempotencyKey: "coupon-bf2026" },
);
// One more code with restrictions
await client.promotionCodes.create({
couponId: coupon.id,
code: "KOL-ALICE",
restrictions: { maxRedemptions: 100, minimumAmount: { USD: "50.00" } },
});
// 1–500 random single-use codes — always retry with the same idempotency key
const { promotionCodes } = await client.promotionCodes.generate(
{ couponId: coupon.id, count: 100, prefix: "KOL-", restrictions: { maxRedemptions: 1 } },
{ idempotencyKey: "kol-batch-2026-11" },
);
await client.coupons.update({ id: coupon.id, name: "BF 2026" }); // only the name can change
await client.coupons.deactivate({ id: coupon.id });
```
Read coupons and codes with GraphQL (`coupons`, `coupon`, `promotionCodes`).
**Applying a discount at checkout** — every checkout and plan change method takes the same three fields:
```typescript
// Locked coupon: the customer sees the discount, not a code
await client.checkout.authenticated.create({ productId, currency: "USD", buyerIdentity, couponId: "CPN_xxx" });
// Code entry field: the customer types a coupon or promotion code
await client.checkout.anonymous.create({ productId, currency: "USD", allowPromotionCodes: true });
// Prefilled promotion code the customer may replace or remove
await client.checkout.createSession({ productId, currency: "USD", promotionCode: "SPRING-20", allowPromotionCodes: true });
```
Rules:
- `couponId` together with `promotionCode` or `allowPromotionCodes` throws `WaffoPancakeError` (400, `layer: "sdk"`) before any request is sent.
- A coupon or prefilled code that belongs to another store or environment, is inactive, expires within 60 seconds, does not cover the product, or is fixed-amount without the session currency is rejected with 409. Customer-tied rules (eligible emails, per-customer limits) are checked when the order is placed.
- On subscriptions, `duration` decides how many paid periods are discounted (`once` = 1, `repeating` = `durationInPeriods`, `forever` = all). A free trial uses no discount period; renewals after the coupon's `redeemBy` are charged full price.
- Set these fields from your server, never from values the browser sends — they are honored because the request is signed with your API Key.
### Plan Changes (Upgrade / Downgrade)
Switching an existing subscription to another plan has its own methods with `originOrderId` required.
```typescript
import { ChangeTiming } from "@waffo/pancake-ts";
// Merchant-issued link (API Key) — send the customer to session.checkoutUrl
const session = await client.checkout.createPlanChangeSession({
originOrderId: "ORD_xxx", // the subscription being changed
productId: "PROD_target_plan", // the plan to switch to
currency: "USD",
changeTiming: ChangeTiming.Immediate, // or NextPeriod; omit to let the platform decide
changeCreditAmount: "8.00", // optional: credit this much — or changeAmount, never both
});
// Same, for a signed-in customer (lands on the confirmation page already signed in)
const result = await client.checkout.authenticated.createPlanChange({
originOrderId: "ORD_xxx",
productId: "PROD_target_plan",
currency: "USD",
buyerIdentity: user.id,
changeTiming: ChangeTiming.NextPeriod,
});
```
- `changeAmount` sets what you charge for this period; `changeCreditAmount` sets how much you credit against it. Sending both is a 400.
- `couponId` / `promotionCode` / `allowPromotionCodes` work here too: a new coupon or code replaces the current discount; without one, the current discount carries over while it still applies.
- Anonymous checkout has no plan change (403) — the change must be tied to the subscription's customer.
- **Customer self-service plan change:** turn on `rules.selfServicePlanChange` on the product group, then call `client.customer(token, { environment }).createPlanChangeSession({ originOrderId, productId, currency })`. The target plan must be in the same group as the current one; merchant-only pricing fields are dropped on this path.
- Watch `subscription.plan_change_scheduled` (next-period change confirmed), `subscription.plan_changed` (took effect) and `subscription.plan_change_failed` (current plan stays).
### Customer Self-Service & Portal
```typescript
// Your backend, behind your own login: issue a customer session
const { token } = await client.auth.issueSessionToken({ storeId: "STO_xxx", buyerIdentity: user.id });
const customer = client.customer(token, { environment: "test" }); // environment is required here
await customer.cancelSubscription({ orderId: "ORD_xxx" }); // -> "canceling" / "canceled"
await customer.reactivateSubscription({ orderId: "ORD_xxx" }); // undo a pending cancel
await customer.createRefundTicket({
paymentId: "PAY_xxx",
reason: "Not as described",
requestedAmount: { amount: "29.00", currency: "USD" },
});
// Or send the customer to the hosted portal (orders, subscriptions, payments)
const { portalUrl } = await client.auth.createCustomerPortalLink({ storeId: "STO_xxx", buyerIdentity: user.id });
// 302 redirect to portalUrl right away; never log or cache it (it carries a token)
```
Take `buyerIdentity` and `storeId` from your own authenticated session, never from request parameters — whoever controls `buyerIdentity` can act as that customer.
### Cancel Subscription
```typescript
const { orderId, status } = await client.orders.cancelSubscription({
orderId: "order_id",
});
// status: "canceled" (was pending) or "canceling" (was active, ends at period end)
```
### GraphQL Queries
Read-only queries. Return type is `{ data: T | null, errors?: [...] }` — access via `result.data`.
```typescript
const result = await client.graphql.query<{
stores: Array<{ id: string; name: string; status: string }>;
}>({
query: `query { stores { id name status } }`,
});
const stores = result.data?.stores ?? [];
// With variables
const productResult = await client.graphql.query<{
onetimeProduct: { id: string; name: string; prices: Array<{ currency: string; priceInfo: { amount: string } }> };
}>({
query: `query ($id: String!) { onetimeProduct(id: $id) { id name prices { currency priceInfo { amount } } } }`,
variables: { id: "PROD_xxx" },
});
```
---
## Webhook Verification
Read the original request body with `request.text()` in Next.js or Hono, or `express.raw()` before JSON middleware in Express. Pass it and `X-Waffo-Signature` to `verifyWebhook`. For a registered endpoint, pass its configured `environment` (`test` or `prod`). For local listener protocol 2, pass `{ publicKey }` with the current session’s PEM from `data.signingPublicKey` in the NDJSON `ready` event. Keep the timestamp check enabled. After verification, check that the signed `mode` and `storeId` match the endpoint.
Use a database uniqueness constraint on (`eventType`, `eventId`) within the store and environment. Commit the event record together with the business change or a durable queue entry in one transaction. Return 2xx after commit, including for a duplicate whose transaction already committed. Return a failure on a storage error so the event can be delivered again. See signature verification and delivery handling in [Webhooks](https://docs.waffo.ai/api-reference/webhooks).
### Webhook Event Types
Compare `event.eventType` against the `WebhookEventType` enum (import it from `@waffo/pancake-ts`):
| Event | Enum member |
|-------|-------------|
| `order.completed` | `WebhookEventType.OrderCompleted` |
| `subscription.activated` | `WebhookEventType.SubscriptionActivated` |
| `subscription.payment_succeeded` | `WebhookEventType.SubscriptionPaymentSucceeded` |
| `subscription.renewed` | `WebhookEventType.SubscriptionRenewed` |
| `subscription.recovered` | `WebhookEventType.SubscriptionRecovered` |
| `subscription.plan_changed` | `WebhookEventType.SubscriptionPlanChanged` |
| `subscription.plan_change_scheduled` | `WebhookEventType.SubscriptionPlanChangeScheduled` |
| `subscription.plan_change_failed` | `WebhookEventType.SubscriptionPlanChangeFailed` |
| `subscription.canceling` | `WebhookEventType.SubscriptionCanceling` |
| `subscription.uncanceled` | `WebhookEventType.SubscriptionUncanceled` |
| `subscription.canceled` | `WebhookEventType.SubscriptionCanceled` |
| `subscription.past_due` | `WebhookEventType.SubscriptionPastDue` |
| `refund.succeeded` | `WebhookEventType.RefundSucceeded` |
| `refund.failed` | `WebhookEventType.RefundFailed` |
| Event | Trigger |
|-------|---------|
| `order.completed` | One-time payment succeeded |
| `subscription.activated` | First subscription payment succeeded |
| `subscription.payment_succeeded` | A subscription payment succeeded (payment only — no period or status) |
| `subscription.renewed` | Billing period rolled forward (renewal) |
| `subscription.recovered` | Past-due subscription recovered after a retried charge |
| `subscription.canceling` | Buyer initiated cancel (active until period end) |
| `subscription.uncanceled` | Buyer withdrew cancellation |
| `subscription.plan_change_scheduled` | Plan change confirmed, takes effect next period |
| `subscription.plan_changed` | Plan change took effect (upgrade/downgrade) |
| `subscription.plan_change_failed` | Plan change did not complete; current plan stays |
| `subscription.canceled` | Subscription fully terminated |
| `subscription.past_due` | Renewal payment failed |
| `refund.succeeded` | Refund completed |
| `refund.failed` | Refund failed |
### Webhook Event Shape
```typescript
interface WebhookEvent {
id: string; // Event entity ID
timestamp: string; // ISO 8601 UTC
eventType: string;
eventId: string; // Business event ID (payment/order ID)
storeId: string;
mode: "test" | "prod";
data: {
orderId: string;
buyerEmail: string;
currency: string;
amount: string; // display amount string (for example "9.99" for USD)
taxAmount: string;
productName: string;
};
}
```
### Configuring Webhook URLs via SDK
A store can have multiple webhooks, each delivering to a different channel (`http`, `feishu`, `discord`, `telegram`, `slack`). Register one entry per channel and environment:
```typescript
// HTTP — Test environment
await client.webhooks.add({
storeId: "STO_xxx",
channel: "http",
url: "https://test.example.com/api/webhooks/waffo",
events: ["order.completed", "subscription.activated", "subscription.canceled"],
testMode: true,
});
// HTTP — Production environment
await client.webhooks.add({
storeId: "STO_xxx",
channel: "http",
url: "https://example.com/api/webhooks/waffo",
events: ["order.completed", "subscription.activated", "subscription.canceled"],
testMode: false,
});
// Update / remove
await client.webhooks.update({ id: "WBH_xxx", events: ["order.completed"] });
await client.webhooks.remove({ id: "WBH_xxx" });
```
To list webhooks, use the GraphQL `Store.storeWebhooks` field — it is the only query entry point.
---
## Common Gotchas
| Gotcha | Why it breaks | Fix |
|--------|---------------|-----|
| `billingPeriod: "monthly"` / `taxCategory: "saas"` as strings | Both fields are enums; `strict` TypeScript rejects the literal | Use `BillingPeriod.Monthly` / `TaxCategory.SaaS` from `@waffo/pancake-ts` |
| Passing `environment` to merchant calls, or pointing at the wrong gateway | The API key already fixes test vs production; `baseUrl` is only for a gateway you were given | Drop `environment`; set `baseUrl` only for a non-production gateway, with a key from that environment |
| Reading webhook body as JSON | `request.json()` re-serializes; signature fails | Use `request.text()` (App Router/Hono) or `express.raw()` (Express) |
| Testing a local webhook handler | A receiver on localhost needs a way to receive test events. | With listener protocol 2, use Test forwarding after browser login and verify locally with the current session’s PEM. |
| Forgetting `.publish()` | Products created in test env by default; prod checkout sessions fail silently | Call `.publish()` before going live |
| Accessing `result` instead of `result.data` in GraphQL | GraphQL returns `{ data: T, errors?: [...] }` | Destructure: `const stores = result.data?.stores ?? []` |
| Using `$id: ID!` in GraphQL variables | Backend uses `String!` not `ID!`; wrong type silently returns null | Always declare ID variables as `$id: String!` |
| `productIds` in group update is full replacement | Replaces entire list, does not append | Pass complete desired list every time |
| No code entry field at checkout | `allowPromotionCodes` defaults to `false` for API Key sessions | Pass `allowPromotionCodes: true` |
| `couponId` plus `promotionCode` / `allowPromotionCodes` | A locked coupon and a code are mutually exclusive | Send one or the other |
| Plan change via a new checkout | Creates a second subscription instead of changing the first | Use `createPlanChangeSession()` / `authenticated.createPlanChange()` with `originOrderId` |
---
## Error Handling
```typescript
import { WaffoPancakeError } from "@waffo/pancake-ts";
try {
await client.stores.create({ name: "" });
} catch (err) {
if (err instanceof WaffoPancakeError) {
console.log(err.status); // HTTP status code
console.log(err.errors); // [{ message, layer }]
console.log(err.errors[0].layer); // "store" | "product" | "order" | ...
}
}
```
Errors ordered by call stack depth: `errors[0]` = deepest layer (root cause), `errors[n]` = outermost.
| Status | Cause | Fix |
|--------|-------|-----|
| 400 | Invalid request body | Check required fields and types |
| 401 | Bad signature or expired token | Verify API key and private key match |
| 403 | `prodEnabled=false` | Complete KYB review in dashboard |
| 403 | Product not found or not accessible | Check the product belongs to the current merchant and environment |
| 409 | Idempotency conflict or duplicate nickname | Wait and retry, or use unique nickname |
| 429 | Rate limited | Back off and retry |
---
## Critical Rules
### ALWAYS DO
- **Raw body for webhooks**: `express.raw()` or `request.text()`. Parsed JSON breaks signatures.
- **Redirect synchronously in the click handler**: `window.location.href = checkoutUrl` (same tab; `successUrl` brings the buyer back) or `window.open(url, "_blank")` called directly in the handler. Server-side, use `res.redirect(checkoutUrl)`.
- **Built-in verification**: `verifyWebhook()` has embedded public keys for test and prod.
- **Use display amounts**: pass `"29.00"` for USD instead of cents-based integers.
- **Env vars for secrets**: `WAFFO_MERCHANT_ID` and `WAFFO_PRIVATE_KEY` in `.env`.
- **Separate API keys**: Different keys for test and production environments.
- Return 2xx after the event and its business change or queue entry commit together.
### NEVER DO
- **Never** use `express.json()` on webhook routes.
- **Never** call `window.open()` from an async callback (after `await`) — Safari and mobile browsers block the popup.
- **Never** implement RSA-SHA256 signing manually — the SDK handles it.
- **Never** hardcode private keys in source code.
- **Never** use the same API key for test and production.
- **Never** mix cents-based integers with display amounts in the same integration.
---
## Data Conventions
| Type | Format | Example |
|------|--------|---------|
| Amounts | Display amount string | `"29.00"` for USD |
| Currency | ISO 4217 | `USD`, `EUR`, `JPY` |
| Timestamps | ISO 8601 UTC | `2026-01-23T00:00:00.000Z` |
| IDs | `{PREFIX}_{base62}` | `STO_xxx`, `PROD_xxx`, `ORD_xxx` |
| Checkout Session ID | `cs_` + UUID | `cs_550e8400-...` |
---
## Dashboard UI Glossary (EN → ZH → JA)
The Dashboard supports English, Chinese, and Japanese. When referencing a Dashboard location, use this mapping.
| English | 中文 | 日本語 |
|---------|------|--------|
| Home | 首页 | ホーム |
| Products | 产品 | 商品 |
| Customers | 客户 | 顧客 |
| Analytics | 分析 | 分析 |
| Payments | 付款 | 支払い |
| Subscriptions | 订阅 | サブスクリプション |
| Revenue | 收入 | 収益 |
| API & Development | API 与开发 | API と開発 |
| Settings | 设置 | 設定 |
| Merchant ID | 商户 ID | マーチャントID |
| Store ID | 店铺 ID | ストアID |
| API Key | API 密钥 | APIキー |
| Private Key | 私钥 | 秘密鍵 |
| Test Mode | 测试模式 | テストモード |
| Live Mode | 生产模式 | 本番モード |
| One-time | 一次性 | 単発 |
| Subscription | 订阅 | サブスクリプション |
| Active | 生效中 | 有効 |
| Canceled | 已取消 | キャンセル済み |
| Completed | 已完成 | 完了 |
**Where to find IDs:**
- `WAFFO_MERCHANT_ID` → Dashboard → API & Development (API 与开发) → the "Create an API Key" section → first row above the key list, with a copy button. It is **not** at the top of the page and the section heading does not mention it
- `Store ID` → Dashboard → Settings (设置) → Store Profile (店铺资料)
- `Product ID` → Dashboard → Products (产品) → click product → shown in URL and detail page
- `API Key` → Dashboard → API & Development (API 与开发) → "Create an API Key" section → Create Key
---
## Test Cards
### Successful Payments
| Card | Type |
|------|------|
| `4576 7500 0000 0110` | Visa Credit |
| `2226 9000 0000 0110` | Mastercard Credit |
| `4001 7000 0000 0110` | Visa Debit |
| `2226 9300 0000 0110` | Mastercard Debit |
### Declined Payments
| Card | Type |
|------|------|
| `4576 7500 0000 0220` | Visa Credit |
| `2226 9000 0000 0220` | Mastercard Credit |
| `4001 7000 0000 0220` | Visa Debit |
| `2226 9300 0000 0220` | Mastercard Debit |
Any future expiry. Any CVC.
---
## Local Development Tips
1. For local testing with listener protocol 2, sign in through the browser, start `pancake listen` in Test and load the new session’s PEM into your receiver after each start. See the [CLI release requirements and SDK example](https://docs.waffo.ai/integrate/cli#listener-signing). To test a registered public HTTPS endpoint, you can also use a tunnel that preserves the body and signature header.
2. **Idempotency** — opt-in. No `X-Idempotency-Key` is sent unless you pass one: `client.stores.create(params, { idempotencyKey: myKey })`. Without a key a retried write executes again; with one the platform replays the first response for 24h (and answers 409 while the original is still in flight). You own the key's uniqueness.
3. **Test vs Prod** — Products created in test environment by default. Use `.publish()` to promote to production. Webhook events include `mode: "test" | "prod"`.
---
## Product Model Decision Table
| Situation | Model |
|-----------|-------|
| Fixed public price | Product price set on the product |
| Runtime-calculated amount (overage, credits) | Checkout session with `priceSnapshot` |
| Recurring plan | Subscription product |
| Multiple subscription tiers | One subscription product per tier + product group |
| Setup fee or credits top-up | One-time product |
| Overage charge for a subscription customer | One-time product with dynamic `priceSnapshot` |
| Discount (launch, campaign, KOL code) | Coupon + optional promotion codes, applied with `couponId`, `promotionCode` or `allowPromotionCodes` — not `priceSnapshot` |
| Upgrade / downgrade / switch billing period | Plan change link (`createPlanChangeSession` / `authenticated.createPlanChange`), plans in one product group |
---
## Quick Start Checklist
1. `npm install @waffo/pancake-ts`
2. Set only `WAFFO_MERCHANT_ID` and `WAFFO_PRIVATE_KEY` env vars (see "Where to find IDs" above)
3. Initialize `new WaffoPancake({ merchantId, privateKey })`
4. Create store: `client.stores.create({ name })` — or use an existing store from Dashboard
5. Before creating product(s), confirm which store should own them when the merchant has multiple stores
6. Create product(s): `client.onetimeProducts.create(...)` or `client.subscriptionProducts.create(...)` — or copy existing Product IDs from Dashboard
7. Create checkout: `client.checkout.createSession(...)` → redirect to `checkoutUrl`
8. Test with card `4576750000000110` (success) or `4576750000000220` (declined) in sandbox
9. For a registered endpoint, verify the raw body and signature for its configured environment, then commit the event before acknowledging it.
10. Configure webhook URL: `client.webhooks.add({ storeId, channel: "http", url, events, testMode })`
11. Optional: discounts — `client.coupons.create(...)`, then `couponId` or `allowPromotionCodes: true` at checkout
12. Optional: plan changes — group the plans, then `client.checkout.createPlanChangeSession({ originOrderId, productId, currency })`
---
## Documentation
- Full docs: https://docs.waffo.ai/
- AI-readable full reference: https://docs.waffo.ai/llms-full.txt
- SDK integration: https://docs.waffo.ai/integrate/sdks
- Discounts guide: https://docs.waffo.ai/guides/discounts
- AI Skills guide: https://docs.waffo.ai/integrate/ai-integration
- npm: https://www.npmjs.com/package/@waffo/pancake-ts
- Dashboard: https://pancake.waffo.ai/merchant/dashboard/integration