waffo

package
v0.21.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Oct 30, 2026 License: MIT Imports: 24 Imported by: 0

Documentation

Overview

Package waffo 实现 ploykit billing 的 Waffo Pancake(MoR)支付渠道 (billing/app.PaymentChannel),走 waffo REST API(https://api.waffo.ai):

POST /v1/actions/checkout/create-session          创建收银台会话
POST /v1/actions/subscription-order/cancel-order  取消订阅(BC-9)
POST /v1/graphql { stores { id } }                探活(BC-9,同一套请求签名)
POST /webhooks/billing/waffo(产品仓路由)         接收 waffo 事件推送

请求鉴权:RSA-SHA256 签名 —— canonical = METHOD\nPATH\nTIMESTAMP\nB64(SHA256(body)), 放 X-Signature;商户号放 X-Merchant-Id,Unix 秒放 X-Timestamp(±5min 窗口)。 webhook 验签:X-Waffo-Signature: "t=<毫秒>,v1=<b64>",对 "t.rawBody" 用 waffo 平台公钥(后台 Settings→Webhooks 复制,按环境区分)验 RSA-SHA256(PKCS1v15), 容忍窗口 24h —— 官方重试链最长 8h,窗口须覆盖整条链;重试原样重放签名头, t 不会重打,防重放靠 ploykit 按 ChannelEventID(eventType:eventId)幂等 入库,不靠时间窗。

订阅标识:waffo 事件载荷没有 subscriptionId,data.orderId 在 activated/ renewed/canceled 全程不变,充当稳定订阅引用(SMS = subscription mark), 也是 CancelSubscription 的 providerSubID;checkout 会话 metadata.order_id (ploykit 订单号)经 orderMetadata 透传回每个事件,用它反查本地订单 (resolveOrder 的 OrderID 路径)。

价格:真源在 DB plan limits($19/$190),waffo 后台商品只是目录壳;创建会话 用 priceSnapshot 按 order.AmountCents 覆盖价格,taxIncluded 默认 true —— MoR 模式下税款从 $19 里出,买家实付与站内标价一致,handlePaid 的金额 对账(chargedAmount == order.AmountCents)才不会把付款拒之门外。 金额换算统一走 billing/money(BC-3),本包不再私藏 formatAmount/parseAmount。

事件映射(→ ploykit domain.PaymentEvent):

subscription.activated          → checkout.completed(首付款,发权益+落订阅引用)
subscription.payment_succeeded  → periodNumber>1: subscription.renewed(续费推进到期日)
                                  periodNumber=1: ignored(activated 已覆盖,避免双发)
subscription.canceled           → subscription.canceled(降级 free)
refund.succeeded                → refund.created(退款撤权)
order.completed                 → checkout.completed(一次性,预留卖包)
其余(renewed/recovered/canceling/past_due/plan_changed/…) → ignored:
  renewed 与 payment_succeeded 双事件同到,只认钱那一条,否则 pro_until
  被推进两个周期;canceling 是"期末才停"(等 canceled);past_due 是 waffo
  侧催收,权益保留到期末(与 Stripe 路径只失败订单、不降级订阅一致)。

Index

Constants

View Source
const (
	EnvMerchantID     = "WAFFO_MERCHANT_ID"
	EnvPrivateKey     = "WAFFO_PRIVATE_KEY"
	EnvProductMonthly = "WAFFO_PRODUCT_MONTHLY"
	EnvProductYearly  = "WAFFO_PRODUCT_YEARLY"
	EnvWebhookPubKey  = "WAFFO_WEBHOOK_PUBLIC_KEY"
	EnvTaxCategory    = "WAFFO_TAX_CATEGORY"
	EnvTaxIncluded    = "WAFFO_TAX_INCLUDED"
	EnvAPIBase        = "WAFFO_API_BASE"
	EnvStoreID        = "WAFFO_STORE_ID"
	EnvMode           = "WAFFO_MODE"
)

环境变量名(生产部署清单见 docs;密钥一律走 env 或 BC-5 后台落库,绝不入日志)。

View Source
const (
	FieldMerchantID       = "merchant_id"
	FieldPrivateKey       = "private_key"
	FieldStoreID          = "store_id"
	FieldProductMonthly   = "product_monthly"
	FieldProductYearly    = "product_yearly"
	FieldWebhookPublicKey = "webhook_public_key"
	FieldMode             = "mode"
)

ConfigSchema 字段键(BC-5/BC-6:后台渠道卡的表单字段名,同时是 billing_channel.waffo.<field> 设置键与 NewFromFields 的 fields 键)。

View Source
const (
	ModeTest = "test"
	ModeProd = "prod"
)

渠道模式常量(BC-4 五律 5:test/prod 凭据与回调分环境)。

View Source
const DefaultAPIBase = "https://api.waffo.ai"

DefaultAPIBase waffo 公有云 API;测试可指向 httptest server。

Variables

This section is empty.

Functions

func Caps added in v0.14.0

func Caps() app.ChannelCaps

Caps 是包级能力声明单一真源:实例方法与 DisabledChannel 桩共用(未配置 waffo 的后台卡片排序/币种声明与真渠道一致)。

func FromEnv

func FromEnv(getenv func(string) string, log *slog.Logger, production bool) (app.PaymentChannel, error)

FromEnv 从环境装配渠道(BC-1 上游化定名,原产品仓 FromEnvStrict),装配纪律 与 bracelet.ProviderFromEnvStrict 同哲学:四个必填变量全缺 = 未配置, 返回 *app.DisabledChannel 桩(后台渠道页可见可贴密钥,活动渠道集 /config 不含它);缺任何一个 = 配置事故 —— production 直接报错拒启 (收银台半残等于丢钱),dev 打 warn 降级为桩,不挡本地开发。 返回类型是 app.PaymentChannel 接口直返:typed-nil 陷阱(nil *Channel 包成 非 nil 接口)从签名上消失,调用方无需再判 nil 重包装。

func NewFromFields

func NewFromFields(fields map[string]string, getenv func(string) string, log *slog.Logger, production bool) (app.PaymentChannel, error)

NewFromFields 按 BC-5 装配:字段值(fields,键=ConfigSchema 字段名,来自 billing_channel.waffo.* 设置行)优先,缺失回退进程 env(env-only 老接法 不断)。与 FromEnv 的纪律差异:静态商品 id 不再必填 —— 目录模式 (BC-7)下商品在后台注册、checkout 经 CheckoutRequest.ChannelProductID 解析,merchant_id/private_key 仍全缺=未配置(返回 DisabledChannel 桩, 后台渠道页可见可贴密钥)、缺一报错(production 拒启/dev 降级为桩), 与 FromEnv 同哲学。返回类型是 app.PaymentChannel 接口直返 —— typed-nil 陷阱从签名上消失。

func Schema added in v0.14.0

func Schema() []app.FieldSpec

Schema 是包级 ConfigSchema 单一真源(BC-6):实例方法、DisabledChannel 桩 (FromEnv/NewFromFields 未配置分支)、后台渠道卡的表单渲染共用此描述符, 字段键同时是 billing_channel.waffo.<field> 设置键与 NewFromFields 的 fields 键 —— 三处一份真源。每个字段的 Help 都注明 「清空=回退 env」:管理员清空字段保存后,该值会回退到环境变量提供的 值(NewFromFields 的 fields-优先-env-回退装配),不是"清空即删除配置" —— 不写明这一点,管理员会误以为清空能彻底摘掉某个值(P3-7)。

Types

type Channel

type Channel struct {
	// contains filtered or unexported fields
}

Channel 实现 app.PaymentChannel。不实现 CheckoutCanceller —— waffo 收银台 会话没有作废 API,放任过期即可(ploykit 的 CancelPendingOrder 对未实现 该接口的渠道直接跳过,弃单由 OrderExpiryWorker 清扫)。

func New

func New(cfg Config) (*Channel, error)

New 校验并解析密钥,构造渠道。私钥/公钥解析失败立刻报错——半配置 不能等到第一笔收款才发现。ProductMonthly/ProductYearly 可空:目录模式 (BC-7)下商品映射走 billing_channel_products + CheckoutRequest. ChannelProductID,静态商品 id 只是 env-only 老接法的兜底(两者皆空时 CreateCheckout 报错;FromEnv 对 env 接法仍维持四必填纪律)。

func (*Channel) CancelSubscription

func (c *Channel) CancelSubscription(ctx context.Context, providerSubID string) error

CancelSubscription 实现 app.SubscriptionCanceller(BC-9/F13)。 providerSubID 就是我们落的 SubscriptionRef = waffo orderId(ORD_xxx, 激活/续费/取消全程不变的稳定订阅引用)。

func (*Channel) Capabilities

func (c *Channel) Capabilities() app.ChannelCaps

func (*Channel) ChannelConfig

func (c *Channel) ChannelConfig() app.ChannelConfigInfo

ChannelConfig 进 billing 配置面(service_billingcfg):Configured 是纯凭据 语义(client 就绪 = merchant_id + 私钥可签名),与 paypal 的 Configured = ClientID+Secret 同判 —— 目录模式(BC-7)下静态商品 id 留空 是合法形态(schema help 自己说"目录模式下留空"),把 products 拼进判定 会让目录模式渠道卡恒显"未配置"、测试连接被 billingcfg 的门误拒。 商品缺失在 CreateCheckout 才是问题,那里已有清晰报错。webhook 公钥 未配时如实标未配置 —— 收银台能开但回调进不来,运营必须看得见这个半残态。

func (*Channel) ConfigSchema

func (c *Channel) ConfigSchema() []app.FieldSpec

func (*Channel) CreateCheckout

func (c *Channel) CreateCheckout(ctx context.Context, req app.CheckoutRequest) (domain.CheckoutSession, error)

func (*Channel) EnvProvidedKeys

func (c *Channel) EnvProvidedKeys() []string

EnvProvidedKeys 返回进程环境变量当前实际提供(os.Getenv 非空)的配置 字段键(与 ConfigSchema 的 Key 同名;env 变量名走 NewFromFields/ FromEnv 共用的 envOfField 映射)。billing 侧以 ChannelEnvViewer 鸭子 类型断言取用:后台渠道卡据此展示"清空该字段后将回退到的 env 值", 没被 env 提供的键不列。顺序与 ConfigSchema 一致,便于展示与断言。

func (*Channel) Name

func (c *Channel) Name() string

func (*Channel) ParseWebhook

func (c *Channel) ParseWebhook(_ context.Context, req app.WebhookRequest) (domain.PaymentEvent, error)

ParseWebhook 验签 + 事件映射。验签必须用原始 body(本包拿到的就是 ploykit billinghttp 读出的 raw bytes,未经过任何 JSON 再编码)。 ChannelEventID = eventType + ":" + eventId:waffo 文档要求按 (eventType, eventId) 二元组去重,而 ploykit 的幂等键只有 ChannelEventID 一列 —— 必须把类型拼进去(不同事件类型可能共享同一顶层 id,如订阅 事件 id = ORD_xxx)。eventId 取事件级 eventId 字段;同一订阅订单的 各期 payment_succeeded 顶层 id 相同(ORD_xxx),只有 eventId 互异, 回退顶层 id 会把第 2 期之后的续费当重复吞掉(客户持续扣费但权益 掉回 free);eventId 缺失时回退顶层 id(兼容旧载荷,行为与初版一致)。

func (*Channel) RegisterProduct

func (c *Channel) RegisterProduct(ctx context.Context, plan domain.Plan, interval domain.BillingInterval) (string, error)

func (*Channel) StaticProductID added in v0.18.1

func (c *Channel) StaticProductID(_ string, interval domain.BillingInterval) string

RegisterProduct 实现 app.ProductRegistrar:在 waffo 侧创建订阅商品并 返回 PROD_ id(F4:一次性 create-products 脚本收编为后台按钮)。名称 "套餐名 (Monthly|Yearly)";价格真源仍是 DB plan limits —— 渠道侧价目 只是目录壳,checkout 时 priceSnapshot 覆盖。 StaticProductID 实现 app.StaticProductResolver:与 CreateCheckout 内部 的静态回退同源(env WAFFO_PRODUCT_* / DB 渠道字段 product_monthly/ product_yearly),让服务层在映射表缺行、自动注册关闭时先吃到静态商品 而不是 400(shuijing 生产实修:env 商品在配,checkout 仍被服务层拒绝)。

func (*Channel) SyncPrice

func (c *Channel) SyncPrice(ctx context.Context, channelProductID string, plan domain.Plan, interval domain.BillingInterval) error

SyncPrice 实现 app.ProductRegistrar:把 plan 当前 DB 价推给已注册商品 (BC-7 改价联动;迁移+手工 update-product 的组合消失)。

func (*Channel) TestConnection

func (c *Channel) TestConnection(ctx context.Context) error

TestConnection 实现 app.ConnectionTester(BC-9/F12):最便宜的无副作用 读 —— GraphQL stores 查询(POST /v1/graphql,与 REST 同一套 RSA 请求 签名;docs/api-reference/endpoints/graphql/overview)。2xx = 凭据/签名/ 时钟全通;401 = 认证失败(密钥错或时钟漂移 >5min)。REST 侧没有 list-webhooks 端点(webhook 列表查询走 GraphQL Store.storeWebhooks, 还需 storeId),stores 查询不需要任何额外配置,是文档给的探活路径。

type Client

type Client struct {
	MerchantID string
	BaseURL    string
	HTTP       *http.Client
	// contains filtered or unexported fields
}

Client 是带请求签名的 waffo REST/GraphQL 客户端。签名算法 (docs/api-reference/authentication):

canonical = METHOD + "\n" + PATH + "\n" + TIMESTAMP + "\n" + B64(SHA256(body))
X-Signature = B64(RSA-SHA256(canonical, privateKey))

TIMESTAMP 为 Unix 秒,服务端容忍 -5min/+1min;本机时钟漂移过大时 waffo 回 401, 那是机器时钟问题不是密钥问题。

type Config

type Config struct {
	MerchantID       string // MER_xxx
	PrivateKey       string // PEM / 转义 \n PEM / 整段 PEM 的 base64 / 裸 base64 体,四种形态都收
	ProductMonthly   string // PROD_xxx(waffo 后台的 Seller Plan (Monthly));目录模式(BC-7)可空
	ProductYearly    string // PROD_xxx(Seller Plan (Yearly));目录模式可空
	WebhookPublicKey string // 可空;为空则 webhook 一律验签失败(先通收银台、后通回调的部署顺序)
	TaxCategory      string // 空 = "saas"
	TaxIncluded      *bool  // nil = true
	APIBase          string // 空 = DefaultAPIBase
	StoreID          string // 可空;BC-7 RegisterProduct 建品用(storeId),仅后台注册商品时需要
	Mode             string // 可空;"test"/"prod";非空时跨环境 webhook 事件直接拒收(五律 5)
}

Config 组装渠道所需的全部外部输入。

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL