Skip to content

[BugFix] fix webhook process - #5047

Merged
seefs001 merged 29 commits into
QuantumNous:mainfrom
Hill-waffo:refactor/pancake-sdk-migration
May 24, 2026
Merged

seefs001 merged 29 commits into
QuantumNous:mainfrom
Hill-waffo:refactor/pancake-sdk-migration

Conversation

@Hill-waffo

@Hill-waffo Hill-waffo commented May 22, 2026 •

Copy link
Copy Markdown
Contributor

📝 变更描述 / Description

#4935 合并后接着补几件事,最重要的是修一个会让所有 Waffo Pancake 充值静默失败的 webhook bug。

🔴 关键 bug fix:webhook 收到 order.completed 后,原来用 event.Data.OrderID(Pancake 内部的 ORD_* ID)去 top_ups.trade_no 里查行 —— 这俩字段格式完全不一样(我们 trade_no 是 WAFFO_PANCAKE-<userId>-<ts>-<rand>),永远查不到,handler 返回 200 OK + "order not found" Error 日志,订单留在 pending 永远不发额度。

修法:在 create-session 时把 trade_no 通过 CreateCheckoutSessionParams.OrderMerchantExternalID 发给 Pancake,webhook 改用 event.Data.OrderMerchantExternalID 查表。SDK 需要 bump 到 v0.3.1(v0.2.0 没这个字段)。

🟡 视觉打磨:

  • 钱包页 / 付款确认弹窗里把 🥞 emoji 换成 Waffo 品牌 logo(深浅主题双 SVG,CSS 切换)
  • "Waffo Pancake MoR" 和 "Waffo Aggregator Gateway" section 的标题字号 / 间距对齐到跟 Stripe / Creem 一致(之前用 SettingsSection 包装,标题是 text-base font-semibold,peer 是 text-lg font-medium)

🚀 变更类型 / Type of change

  • 🐛 Bug 修复 (Bug fix) — 主要是修 webhook 订单查找
  • ✨ 新功能 (New feature)
  • ⚡ 性能优化 / 重构 (Refactor)
  • 📝 文档更新 (Documentation)

🔗 关联任务 / Related Issue

✅ 提交前检查项 / Checklist

Summary by CodeRabbit

Release Notes

  • New Features

    • Added Waffo Pancake settings tab in payment settings.
  • Bug Fixes / Improvements

    • Checkout sessions now include an external order identifier to improve webhook matching and order reconciliation.
    • Buyer email is only sent when a real email exists (no placeholder addresses).
  • Tests

    • Updated webhook-related tests to reflect the new external identifier behavior.
  • Chores

    • Updated Waffo Pancake SDK to a newer version.

Review Change Stack

Hill-waffo and others added 28 commits May 15, 2026 19:22
…dpoints

Backend: new POST endpoints under /api/option/waffo-pancake/ for listing
the merchant's stores + products, minting a fresh store/product pair in
one round-trip, and atomically committing all five operator-controlled
fields. All three fall back to persisted credentials when the body is
blank, so a returning admin doesn't need to re-paste the private key
(which is stripped from GET /api/option/ by the sensitive-key filter).
Catalog query passes `stores(limit: 100)` to bypass the SDK's default
single-store cap. A GraphQL response envelope-fix transport works
around a single/double wrap mismatch in waffo-pancake-sdk-go v0.1.1.

Frontend: new no-auto-save admin section. Typed creds debounce-verify
against /catalog, "+ Create" mints a fresh pair via /pair and refreshes
the dropdown from the authoritative GraphQL response (rather than
echoing the response body), Save commits all five fields atomically.
Dropdowns seed from saved bindings on mount with a raw-ID fallback
item while the catalog query is in flight, so refreshing the page
shows the bound store + product immediately; both bound IDs are also
rendered next to the Save button.

Settings: drop the legacy Enabled / Sandbox / WebhookPublicKey fields.
The gateway is on iff MerchantID + PrivateKey + ProductID are
populated; environment is decided by the API key the operator pastes;
webhook public keys ship inside the SDK.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Routes:
- POST /api/user/waffo-pancake/amount (quote)
- POST /api/user/waffo-pancake/pay (create checkout session)
- POST /api/waffo-pancake/webhook/:env (test/prod-segregated webhook)

All three were already implemented in the controllers but kept commented
in the router. Uncommenting unblocks the end-user wallet top-up flow that
the binding-flow commit (4f7ea8b) made configurable in the admin UI.

User top-up page now lists Waffo Pancake above legacy Waffo
(controller/topup.go reordering); the Pancake gateway gates on
presence of MerchantID + PrivateKey + ProductID rather than the
removed Enabled/Sandbox/WebhookPublicKey flags
(controller/option.go drops the isVisiblePublicKeyOption helper that
exposed those keys).

Wallet redirects in-tab (window.location.href) rather than
window.open in both default and classic frontends — window.open fires
after `await pay(...)` returns, by which point the user-gesture
context is gone and pop-up blockers kick in. Same pattern as Stripe
Checkout / Lemonsqueezy / Creem hosted checkouts.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
The Pancake SDK auto-generates X-Idempotency-Key on every signed POST
as SHA256(merchantID + path + body), including queries to /v1/graphql.
Pancake server-side dedupes on this key, so two identical query bodies
return the same cached snapshot — and a freshly-created Store or
OnetimeProduct would never appear in the catalog dropdown because the
catalog query body never changes.

Idempotency keys belong on state-changing operations (create / update /
delete) where they protect against duplicate side effects from retries
and double-clicks. Queries are reads; they should always be fresh.

Strip the header at the transport layer for /v1/graphql only — every
other endpoint (/v1/stores, /v1/onetime-products/{create,publish},
/v1/checkout-sessions, etc.) keeps its idempotency key intact so the
double-click safety on "+ Create" / Save / Pair flows is preserved.

The proper fix is upstream in waffo-pancake-sdk-go (the SDK shouldn't
set X-Idempotency-Key on GraphQL queries at all); this workaround
unblocks new-api in the meantime.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
User-facing purchase:
- POST /api/subscription/waffo-pancake/pay creates a SubscriptionOrder
  (status=pending) with a WAFFO_PANCAKE_SUB- prefixed trade_no, then
  hands Pancake an authenticated checkout session pinned to the plan's
  WaffoPancakeProductId with a PriceSnapshot override at PriceAmount.
- subscription-purchase-dialog now shows a Waffo Pancake button when
  enableWaffoPancake && plan.waffo_pancake_product_id; handler uses
  in-tab redirect (window.location.href) to avoid the popup-blocker
  pattern the existing Stripe/Creem buttons still suffer from.

Webhook dispatch:
- WaffoPancakeWebhook now dispatches by trade_no prefix:
  WAFFO_PANCAKE_SUB-… → ResolveWaffoPancakeSubscriptionTradeNo +
  model.CompleteSubscriptionOrder; plain WAFFO_PANCAKE-… → existing
  TopUp recharge flow. Same buyer-identity defence in depth on both.

Admin plan editing:
- SubscriptionPlan model gains WaffoPancakeProductId (varchar 128).
- Mutate drawer renders a dropdown of existing Pancake OnetimeProducts
  in the saved store (POST /api/option/waffo-pancake/subscription-
  product-options) with a "+ 新建" button that mints a new product
  server-side using persisted creds + StoreID + ReturnURL (POST
  /api/option/waffo-pancake/subscription-product). Refetches from the
  authoritative GraphQL catalog after mint rather than echoing the
  response body — matches the wallet binding's pattern.
- Plan-form schema + defaults + planToFormValues extended; columns
  badge added; pay-link API helper added.

Schema migration: GORM AutoMigrate adds the column on next startup; dev
SQLite needs a one-off `ALTER TABLE subscription_plans ADD COLUMN
waffo_pancake_product_id varchar(128) NOT NULL DEFAULT ''` if not
restarting.

Why OnetimeProduct (not SubscriptionProduct): new-api's
SubscriptionPlan is a time-limited prepayment — UserSubscription has a
fixed expiration and renewal is a manual re-purchase. There's no
renewal-event handling on the webhook side, mirroring the existing
Stripe integration. SubscriptionProduct would mean Pancake auto-renews
on its side but new-api never extends the user's access — bad UX.
Revisit if/when new-api adds renewal-event handling.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
…c tab

Settings page (default frontend):
- Explainer chip under the binding section spells out why one Store +
  Product is enough at the gateway level and what each is used for:
  the bound Store is the parent of every Pancake product new-api
  creates (wallet top-up + subscription-plan products), the bound
  Product powers wallet top-ups specifically (per-session price
  override means no pre-made $1/$5/$10 SKUs), and subscription plans
  do NOT share the bound Product — each plan owns its own product set
  via the Subscriptions admin.
- Subtitle dedup: removed the duplicate "无需注册公司 / without
  registering a company" without losing any information.

Pancake icon:
- 🥞 emoji replaces the generic credit-card icon in both default
  (wallet/lib/ui.tsx) and classic (topup/RechargeCard.jsx) wallets —
  lucide doesn't ship a pancake glyph and react-icons/si is brand-
  only, so emoji is the cleanest path. Sized via the same className
  the caller passes, role=img + aria-label for accessibility.

Classic frontend admin:
- Waffo Pancake settings tab uncommented in PaymentSetting.jsx.
- SettingsPaymentGatewayWaffoPancake.jsx slimmed to the three
  operator-facing fields the new backend setting struct exposes
  (MerchantID + PrivateKey + ReturnURL) — Store/Product binding still
  happens through the default frontend's catalog flow.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
ensureSubscriptionPlanTableSQLite is hand-maintained — the new column was
present in the GORM model (handled by AutoMigrate for MySQL/Postgres) but
missing from the SQLite CREATE TABLE DDL and the upgrade-path required[]
array, so SQLite-backed deploys errored on subscription writes.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
…dpoint

The classic admin's Save handler POSTed /api/option/waffo-pancake/initialize
after persisting credentials, intending to auto-provision a Store + Product.
That route was removed in 4f7ea8b (replaced by /save + /pair, with binding
now operator-driven), so every classic-frontend save 404'd and surfaced a
misleading "Waffo Pancake 自动创建商品失败" error.

Classic now just persists the three operator-typed fields. Store/Product
binding is exclusively the default frontend's catalog flow, matching the
documented design.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
…+ TS errors

Audit-driven cleanup of the binding-flow + subscription commits:

- Remove WaffoPancakeProvisionedMerchantID + WaffoPancakeProvisionedReturnURL
  across setting / option / service / billing-defaults / system-settings-types.
  They were written on every Save but never read — relics of a removed
  EnsureWaffoPancakePrimaryProduct re-provision loop that the Pair + Save
  split made redundant. Two fewer OptionMap entries, two fewer UpdateOption
  calls per save.

- Rewrite the setting/payment_waffo_pancake.go module doc to describe the
  actual flow (SaveWaffoPancakeConfig + CreateWaffoPancakePrimaryPair) and
  reclassify StoreID/ProductID from "internally-managed" to "operator-bound"
  — operators pick them from the catalog or click "+ Create", they're
  never silently auto-provisioned now.

- Coerce Base UI Select's `string | null` onValueChange to `string` in
  waffo-pancake-settings-section.tsx — the Store and Product selects fed
  null straight into `Dispatch<SetStateAction<string>>` setters, which tsc
  has been flagging since 4f7ea8b.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
…tions

Peer Go controllers (Stripe / Creem) sit at 5–7% inline-comment density;
peer TSX integration sections (creem-product-dialog, payment-settings-
section, waffo-settings-section) have 0–2 inline comments. Pancake code
had 18–31% in Go and 102 inline comments in waffo-pancake-settings-
section.tsx — a 3-30x outlier.

Trimmed long rationale prose, deleted peer-alignment notes ("matches
Stripe pattern"), section-divider banners ("// =====") and inline trivia
that restated the code. Kept the genuinely-non-obvious comments:

  - waffoPancakeGraphQLEnvelopeFixTransport: SDK envelope-decode bug +
    GraphQL idempotency-key strip (both block readers from inferring
    "why this transport exists" without the comment).
  - Brief godoc-style function headers (matches peer Go convention).
  - State-machine comments where behaviour is non-obvious (mount-only
    PrivateKey init, debounce signature dedupe, returning-admin
    blank-creds fallback).

Comment counts before → after:
  service/waffo_pancake.go                             211 → 71
  controller/topup_waffo_pancake.go                    116 → 32
  controller/subscription_payment_waffo_pancake.go      20 → 4
  waffo-pancake-settings-section.tsx                   102 → 33
  subscriptions-mutate-drawer.tsx + etc.                    compressed

`go build ./...` ✅. `tsc --noEmit` ✅.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Adds inline User Agreement / Privacy Policy links next to the copyright
on the home-page Footer when either is configured in System Settings →
Site → System Information. Same `user_agreement_enabled` /
`privacy_policy_enabled` status flags that drive the sign-in / sign-up
legal footers and the registration consent gate — admin clears the
document field → all three surfaces hide their link in lockstep.

UX: single inline row separated by `·` (Linear / Vercel / Notion
pattern). Two render branches:
  - default Footer: copyright + legal links on the left flex group,
    project attribution on the right.
  - custom-HTML Footer: legal links inline-composed with project
    attribution in the right-hand cell of the rounded box.

Implementation notes:
  - LegalLinks emits fragmented siblings (no wrapper div) so the
    parent flex container's gap-x uniformly controls separator and
    link spacing.
  - ProjectAttribution gains an `inline` prop so callers can compose
    it inline with other footer elements (e.g. legal links) instead
    of always wrapping in its own centered/right-aligned div.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
…rs, and API layering

Style audit (commit 1b17d68 trimmed comment density; this lands the rest).

Backend (Go):
- Admin endpoints' logger format aligned with peer (Stripe / Creem / Waffo):
  Chinese verb + key=value field chain + %q-quoted strings, instead of the
  English "Waffo Pancake X failed: %v" style.
- Admin endpoints' error data switched from English to Chinese ("参数错误",
  "Waffo Pancake 凭证未配置", etc.) to match the rest of the codebase's
  user-facing error message convention.
- Webhook event types exported: waffoPancakeWebhookEvent →
  WaffoPancakeWebhookEvent and waffoPancakeWebhookData →
  WaffoPancakeWebhookData, so VerifyConfiguredWaffoPancakeWebhook's
  exported signature no longer leaks an unexported return type (Go
  unexported-return lint).

Frontend (TS):
- WaffoPancakePaymentResponse and SubscriptionPayResponse now declare
  the `token` / `token_expires_at` (and Pancake-only session_id /
  expires_at / order_id on the shared subscription response) that the
  backend has been returning all along. Removes a real contract drift —
  the fields were live but invisible to TS consumers.
- Lifted three direct api.post calls out of waffo-pancake-settings-
  section.tsx into a new waffo-pancake-api.ts helper module
  (listWaffoPancakeCatalog / createWaffoPancakePair /
  saveWaffoPancakeConfig). The section is now the only file in
  system-settings/integrations/ that no longer reaches into api.post
  directly — matching the convention used by every other integration
  section.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Updated the "Pancake 控制台" link in both the default and classic admin
settings pages from /dashboard to /merchant/dashboard — the former is a
public landing page, the operator actually needs the merchant console.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
The Pancake GraphQL Store.onetimeProducts nested field returns all
products regardless of status (the resolver is a DataLoader, takes no
filter args). Operators would see archived / draft products in the
binding dropdowns and could bind them, only to hit "product
unavailable" at checkout time.

Filter at the service layer rather than restructuring the catalog query
into two phases (server-side filter would need top-level
onetimeProducts(storeId, filter) + GraphQL aliases per store, adds a
round-trip without practical bandwidth gain for typical catalogs of
< 5 stores).

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
SDK v0.2.0 fixed both issues that waffoPancakeGraphQLEnvelopeFixTransport
was working around — the SDK now returns the GraphQL envelope verbatim
(no more double-unwrap), and queries no longer carry X-Idempotency-Key
(GraphQLResource.Query sets postOptions.NoIdempotency internally). The
whole custom transport is gone; HTTP plumbing reverts to the SDK's
defaults.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
SDK v0.2.0 exposes VerifyWebhookTyped[T] which combines signature
verification + typed Data unmarshal in one call. Replacing the previous
VerifyWebhook + json.Unmarshal pair drops the encoding/json import and
the derefString helper (its sole caller is now a 3-line inline).

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
…ransaction

Previously SaveWaffoPancakeConfig claimed atomicity in its doc but ran
five independent model.UpdateOption calls in sequence — a mid-sequence
failure (DB error, constraint violation, etc.) left the gateway in a
partially-configured state, e.g. MerchantID updated but StoreID still
pointing at the old value.

Adds model.UpdateOptionsBulk which wraps all writes in a single
DB.Transaction and only dispatches updateOptionMap after the commit
succeeds. Other multi-field config saves can adopt the same helper.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
The classic wallet was setting window.location.href = checkoutUrl with
no scheme check; the default frontend had isSafeHttpCheckoutUrl in
features/wallet/hooks/use-waffo-pancake-payment.ts but classic was the
parity gap. Mirrors the http/https-only validator inline.

Pancake itself never returns unsafe schemes, but the check is cheap
defence-in-depth against a compromised gateway or an injection
upstream.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Two keys differed only by trailing period and translated separately
("Merchant ID is required" / "Merchant ID is required."). The dotted
variant had a single call site in waffo-pancake-settings-section.tsx —
switched it to the period-less canonical key and removed the duplicate
entries from en.json + zh.json.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
The Chinese translation for the empty-state hint on the admin binding
page kept the English "Create" verb verbatim, mixing scripts in an
otherwise all-Chinese sentence. Replaced with 「创建」 to match the
surrounding text.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
The 🥞 span's aria-label was hardcoded "pancake" — a screen-reader-only
string that should respect the user's locale. Switched to
i18next.t('Pancake') (using the global i18next instance since
getPaymentIcon is a plain function, not a React component, so the
useTranslation hook is unavailable).

Brand strings on the wallet/subscription badge labels ("Waffo Pancake",
"Stripe", "Creem") stay hardcoded — peer convention.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
The bind-status hint had a 4-way nested ternary (credsReady / verifying
/ hasCatalog) that was hard to read past the second level. Lifted it to
a derived bindStatusMessage variable computed via if/else above the
JSX; the render site is now a single {bindStatusMessage}.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
…tionTradeNo

Four-case parity with the existing TopUp resolver tests: happy path,
unknown order, buyer identity mismatch, missing buyer identity. Catches
behaviour drift between top-up and subscription webhook paths — the
two functions share the same defence-in-depth pattern but their
underlying lookups (TopUp vs SubscriptionOrder) could diverge in
subtle ways without coverage on both.

setupWaffoPancakeTestDB now also migrates SubscriptionOrder.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Upstream main moved 29 commits ahead. The 9 conflicting files all needed
manual reconciliation because upstream added overlapping features:

- payment_setting.compliance_*: new compliance gate (RootAuth must
  confirm legal terms before any payment surface unlocks). Kept the
  new isPaymentComplianceConfirmed() guard in isWaffoPancakeTopUpEnabled
  alongside our credentials-presence check; added confirmPayment-
  ComplianceForTest helper to the Pancake webhook test.

- paymentReturnPath helper (theme-aware return URL builder): upstream
  reintroduced getWaffoPancakeReturnURL via this helper. We had removed
  the function because SuccessURL is now bound to the OnetimeProduct at
  creation time, not per-checkout — dropped the upstream snippet, kept
  our admin-flow ReturnURL plumbing.

- isPaymentComplianceOptionKey / isPositiveOptionValue (new helpers in
  controller/option.go): kept upstream's additions. Did NOT keep
  upstream's revived isVisiblePublicKeyOption (it references
  WaffoPancakeWebhookPublicKey / WaffoPancakeWebhookTestKey, which our
  branch removed; the helper has zero call sites).

- web/classic admin Tabs got a card-style wrapper from upstream; kept
  that wrapper AND our uncommented Waffo Pancake tab.

- PaymentSettingsSection props: kept BOTH our waffoPancakeProvisioned-
  StoreID/ProductID AND upstream's complianceDefaults — independent
  additive props.

- i18n locales: alphabetical inserts on each side, kept both.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Two SVG variants for theme-aware rendering — a black-W-on-transparent
glyph for light themes and a white-W-on-transparent glyph for dark
themes. The W letterform occupies only ~40% of the SVG viewBox
vertically (it's a wide, short letterform), so the wrapper applies
transform: scale(2) to bring the rendered glyph height in line with
Stripe's S and Creem's Landmark icons in the payment-method buttons.

Default frontend switches variants via Tailwind's dark: prefix (no JS);
classic frontend reads the current theme via the existing useActualTheme
hook and selects the src accordingly.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
…dings with peers

Both Waffo sections used <SettingsSection>, which renders an h3 in
text-base font-semibold. The other integrations on the page (Stripe,
Creem, Epay, General) all use an inline h3 in text-lg font-medium
straight off the parent form, with sibling Separators creating the
visual rhythm.

Switched both Waffo sections to the inline heading pattern and added
pt-4 to their root containers so the gap above each heading matches
the inside-form rhythm (the parent SettingsSection uses space-y-4
between children where the inner form uses space-y-8 — pt-4 closes
the gap).

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
…rder lookup

The webhook handler was reading event.Data.OrderID as the trade_no to
look up in top_ups / subscription_orders. But OrderID is Pancake's
internal ORD_* identifier and has nothing to do with the trade_no we
generate (WAFFO_PANCAKE-... / WAFFO_PANCAKE_SUB-...) — so every
production webhook silently failed to credit quota, returning 200 OK
with an "order not found" error log.

The correct field is OrderMerchantExternalID, which Pancake echoes
back from the merchant-provided business identifier set at session
creation. Two-sided fix:

  - service.CreateWaffoPancakeCheckoutSession now sets
    CreateCheckoutSessionParams.OrderMerchantExternalID = tradeNo
    on the SDK call.
  - ResolveWaffoPancakeTradeNo / ResolveWaffoPancakeSubscriptionTradeNo
    read event.Data.OrderMerchantExternalID for lookup. OrderID stays
    in the webhook event struct for log cross-referencing.

Requires SDK bump to v0.3.1 — v0.2.0 didn't model the
OrderMerchantExternalID field on either CreateCheckoutSessionParams or
WebhookEventData.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
…cake-sdk-migration

PR QuantumNous#4935 was merged at 19f1821. Subsequent main commit f2c7647
("enforce Waffo subscription compliance and product ID update")
added requirePaymentCompliance(c) to SubscriptionRequestWaffoPancakePay.

Conflicts came from this branch's three post-PR commits sitting on top
of the pre-merge state while main now has the merged-then-extended
version. Resolution kept the post-PR work intact:

- go.mod / go.sum: SDK v0.3.1 (main is still on v0.2.0)
- controller/subscription_payment_waffo_pancake.go: keep
  requirePaymentCompliance check from main AND OrderMerchantExternalID
  from this branch
- controller/topup_waffo_pancake.go: same merge of both sides
- service/waffo_pancake.go: keep all OrderMerchantExternalID plumbing
- service/waffo_pancake_test.go: keep updated test fixtures

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
@coderabbitai

coderabbitai Bot commented May 22, 2026 •

Copy link
Copy Markdown
Contributor

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 8892809f-5837-404a-adc3-f6e718891f2a

📥 Commits

Reviewing files that changed from the base of the PR and between 6f4faa4 and d204607.

📒 Files selected for processing (1)
  • controller/topup_waffo_pancake.go
💤 Files with no reviewable changes (1)
  • controller/topup_waffo_pancake.go

Walkthrough

This PR refactors the Waffo Pancake payment integration to use OrderMerchantExternalID (the local trade_no) as the stable identifier for webhook correlation, replacing the previous use of OrderID. The SDK is upgraded to v0.3.1, service contracts are extended, controllers and tests are updated throughout, and a new Waffo Pancake settings UI tab is added.

Changes

Waffo Pancake Order Identifier Refactoring

Layer / File(s) Summary
Service contract and SDK update
service/waffo_pancake.go, go.mod
WaffoPancakeCreateSessionParams and WaffoPancakeWebhookData structs now include OrderMerchantExternalID. SDK dependency upgraded from v0.2.0 to v0.3.1.
Service implementation - session and webhook handling
service/waffo_pancake.go
CreateWaffoPancakeCheckoutSession wires OrderMerchantExternalID into Pancake params; VerifyConfiguredWaffoPancakeWebhook extracts OrderMerchantExternalID into normalized event data.
Trade-no resolution for topup and subscription
service/waffo_pancake.go
ResolveWaffoPancakeTradeNo and ResolveWaffoPancakeSubscriptionTradeNo now use event.Data.OrderMerchantExternalID as the lookup key instead of OrderID, with updated validation and messages.
Controller integration and webhook dispatch
controller/topup_waffo_pancake.go, controller/subscription_payment_waffo_pancake.go
Topup and Subscription controllers include OrderMerchantExternalID (set to generated tradeNo) when creating checkout sessions. Webhook handlers derive rawTradeNo from OrderMerchantExternalID. getWaffoPancakeBuyerEmail fallback behavior adjusted.
Service test coverage for new identifier mapping
service/waffo_pancake_test.go
Tests updated: OrderID set to a fixed internal Pancake id, OrderMerchantExternalID carries the local trade reference across existing-order, identity-mismatch, missing-identity, and unknown-order scenarios for both topup and subscription resolvers.
Waffo Pancake settings tab
web/classic/src/components/settings/PaymentSetting.jsx
Adds "Waffo Pancake 设置" tab pane rendering SettingsPaymentGatewayWaffoPancake with shared inputs and onRefresh.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Possibly related PRs

  • QuantumNous/new-api#4089: Both PRs touch the Waffo Pancake webhook/trade-number handling in service/waffo_pancake.go.
  • QuantumNous/new-api#5038: Both PRs modify SubscriptionRequestWaffoPancakePay in controller/subscription_payment_waffo_pancake.go.
  • QuantumNous/new-api#4935: Overlaps on webhook and trade-number resolution refactoring in service/waffo_pancake.go and related controllers.

Suggested reviewers

  • seefs001

Poem

🐰 A pancake by any other name's still sweet,
I stamp my trade_no, steady and neat.
Webhooks echo back the merchant's sign,
Tests nod along — the mappings align.
Hop, code, deploy — the flow's now complete.

🚥 Pre-merge checks | ✅ 3 | ❌ 2

❌ Failed checks (1 warning, 1 inconclusive)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 31.25% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
Title check ❓ Inconclusive The title "[BugFix] fix webhook process" is partially related to the changeset but insufficiently specific about the main change. Revise to be more specific: "[BugFix] Use OrderMerchantExternalID instead of OrderID for Pancake webhook lookups" or similar.
✅ Passed checks (3 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
service/waffo_pancake.go (1)

103-117: 🛠️ Refactor suggestion | 🟠 Major | ⚡ Quick win

Require OrderMerchantExternalID before creating the checkout session.

Both resolver paths now hard-fail when this field is missing, but session creation still drops it when empty via optionalString(...). That leaves this service API able to create orders the webhook can never reconcile, which is the same pending-order failure mode this hotfix is fixing.

🧩 Proposed fix
 func CreateWaffoPancakeCheckoutSession(ctx context.Context, params *WaffoPancakeCreateSessionParams) (*WaffoPancakeCheckoutSession, error) {
 	if params == nil {
 		return nil, fmt.Errorf("missing checkout params")
 	}
 	if strings.TrimSpace(params.BuyerIdentity) == "" {
 		return nil, fmt.Errorf("missing buyer identity")
 	}
+	if strings.TrimSpace(params.OrderMerchantExternalID) == "" {
+		return nil, fmt.Errorf("missing order merchant external id")
+	}
 	client, err := newWaffoPancakeClient()
 	if err != nil {
 		return nil, fmt.Errorf("build Waffo Pancake client: %w", err)
 	}
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@service/waffo_pancake.go` around lines 103 - 117, The code currently allows
params.OrderMerchantExternalID to be empty (it's passed through optionalString),
which can create checkouts that webhooks can't reconcile; add a required-field
check like the BuyerIdentity check: verify
strings.TrimSpace(params.OrderMerchantExternalID) != "" and return an error
(e.g., "missing order merchant external id") before constructing the client or
building pancake.AuthenticatedCheckoutParams, and stop using optionalString for
OrderMerchantExternalID so the real value is enforced when creating the
CreateCheckoutSessionParams.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@web/classic/src/components/settings/PaymentSetting.jsx`:
- Around line 307-313: The component SettingsPaymentGatewayWaffoPancake is used
in the Tabs but never imported; add an import statement for
SettingsPaymentGatewayWaffoPancake at the top of the file (matching the
component's exported module) and ensure the named/default import matches how it
is exported so the JSX <SettingsPaymentGatewayWaffoPancake ... /> resolves
correctly and the tab compiles.

---

Outside diff comments:
In `@service/waffo_pancake.go`:
- Around line 103-117: The code currently allows params.OrderMerchantExternalID
to be empty (it's passed through optionalString), which can create checkouts
that webhooks can't reconcile; add a required-field check like the BuyerIdentity
check: verify strings.TrimSpace(params.OrderMerchantExternalID) != "" and return
an error (e.g., "missing order merchant external id") before constructing the
client or building pancake.AuthenticatedCheckoutParams, and stop using
optionalString for OrderMerchantExternalID so the real value is enforced when
creating the CreateCheckoutSessionParams.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 4c8fa137-76cb-4879-b815-b42e88420a51

📥 Commits

Reviewing files that changed from the base of the PR and between b9bc6f0 and 6f4faa4.

⛔ Files ignored due to path filters (1)
  • go.sum is excluded by !**/*.sum
📒 Files selected for processing (6)
  • controller/subscription_payment_waffo_pancake.go
  • controller/topup_waffo_pancake.go
  • go.mod
  • service/waffo_pancake.go
  • service/waffo_pancake_test.go
  • web/classic/src/components/settings/PaymentSetting.jsx

Comment on lines +307 to +313
<Tabs.TabPane tab={t('Waffo Pancake 设置')} itemKey='waffo-pancake'>
<SettingsPaymentGatewayWaffoPancake
options={inputs}
refresh={onRefresh}
hideSectionTitle
/>
</Tabs.TabPane>

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🔴 Critical | ⚡ Quick win

Missing import for SettingsPaymentGatewayWaffoPancake breaks this tab.

SettingsPaymentGatewayWaffoPancake is used at Line 308 but never imported, so this page will fail to compile/render.

Proposed fix
 import SettingsPaymentGatewayWaffo from '../../pages/Setting/Payment/SettingsPaymentGatewayWaffo';
+import SettingsPaymentGatewayWaffoPancake from '../../pages/Setting/Payment/SettingsPaymentGatewayWaffoPancake';
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@web/classic/src/components/settings/PaymentSetting.jsx` around lines 307 -
313, The component SettingsPaymentGatewayWaffoPancake is used in the Tabs but
never imported; add an import statement for SettingsPaymentGatewayWaffoPancake
at the top of the file (matching the component's exported module) and ensure the
named/default import matches how it is exported so the JSX
<SettingsPaymentGatewayWaffoPancake ... /> resolves correctly and the tab
compiles.

@Hill-waffo Hill-waffo changed the title Refactor/pancake sdk migration [BugFix] fix webhook May 22, 2026
Previously, if the local user had no email set, we synthesized a
placeholder like `<userId>@new-api.local` and sent it as BuyerEmail to
Pancake. The buyer would then land on Pancake's hosted checkout with
that fake address prefilled and have to correct it before paying.

Drop the fallback — when there's no real email, leave BuyerEmail empty
so Pancake's checkout collects it from the buyer directly.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
@Hill-waffo Hill-waffo changed the title [BugFix] fix webhook [BugFix] fix webhook process May 22, 2026
@seefs001
seefs001 merged commit 0354c38 into QuantumNous:main May 24, 2026
yiranxiaohui added a commit to yiranxiaohui/new-api that referenced this pull request May 25, 2026
Range: 18282e6..3b9ed0a8 (upstream/main as of fetch)

Highlights:
- feat: support request_header key source (QuantumNous#4903)
- feat: Waffo Pancake gateway + admin catalog binding (QuantumNous#4935)
- perf: optimize request metadata extraction, drop dead batch
  helpers in relay/channel/openai/helper.go (QuantumNous#5009)
- perf: reduce heap residency for large base64 relay requests
- fix(channel): evict auto-disabled multi-key channels from cache (QuantumNous#4983)
- fix: resolve model owned_by from active channels (QuantumNous#4416) — introduces
  channelOwnerName/getPreferredModelOwners/buildOpenAIModel + ListModels refactor
- fix: GetAllChannels respects group filter (QuantumNous#4847, QuantumNous#4885)
- fix(auth): expose register_enabled, aff_code, localize reset (QuantumNous#4871, QuantumNous#4945, QuantumNous#4769)
- fix(webhook): processing + Waffo subscription compliance (QuantumNous#5047, QuantumNous#5038)
- refactor(ui): system settings drill-in sidebar + log filter responsiveness

Conflicts resolved:
- controller/model.go: kept local hiddenMappedModels filter
  (resolveAccessibleModelGroups + getHiddenMappedModelNamesForGroups)
  on top of upstream's ListModels refactor; adopted upstream
  channelOwnerName helper.
- relay/channel/openai/helper.go: adopted upstream (HEAD's
  processChatCompletions/processCompletions were dead code after
  upstream's perf refactor in QuantumNous#5009).

Local patches verified intact: Username + fillTopUpUsernames (model/topup.go,
locked by topup_username_test.go), HideUpstreamErrors, Claude developer-role
normalization, Gemini role fallback, Model Chat header nav entry,
channel affinity auto-clear.

Note: go build not run (no Go toolchain in this environment); CI to verify.

Generated with [Claude Code](https://claude.ai/code)
via [Happy](https://happy.engineering)

Co-Authored-By: Claude <[email protected]>
Co-Authored-By: Happy <[email protected]>
xyfacai pushed a commit to xyfacai/new-api that referenced this pull request May 30, 2026
SamuelSxy pushed a commit to SamuelSxy/new-api-rh that referenced this pull request Jun 7, 2026
fx247562340 pushed a commit to fx247562340/vancine-platform that referenced this pull request Jun 11, 2026
330079598 pushed a commit to 330079598/new-api that referenced this pull request Aug 19, 2026
salem-2007 added a commit to salem-2007/new-api that referenced this pull request Sep 10, 2026
junjundesk pushed a commit to junjundesk/new-api that referenced this pull request Oct 3, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants