Documentation
¶
Overview ¶
Package sim 提供三个「模拟支付渠道」方言(simwaffo / simpaypal / simstripe), 用于在真库上对 billing 全管线做端到端验收。每个方言忠实镜像对应真实渠道 (billing/adapters/waffo、paypal、stripe)的 **协议形状**——webhook 事件 JSON 的信封/字段结构与 → domain.PaymentEvent 的五律映射语义——但不复用其代码, 也不出任何网络调用:CreateCheckout 返回本地 approve URL + 会话引用, ParseWebhook 做 HMAC-SHA256 验签(每渠道独立 secret,签名放 X-Sim-Signature 头、对 raw body 计算——保持与真渠道一致的 raw-body 纪律)后按同款语义映射。
与真实渠道的**有意差异**(其余形状一致):
- 验签传输简化:三个方言统一用 X-Sim-Signature: hex(HMAC-SHA256(secret, rawBody)), 而不是 waffo 的 RSA "t=,v1=" / paypal 的 verify-webhook-signature API / stripe 的 Stripe-Signature。验签语义(对 raw body、缺头拒收、错签拒收) 保持一致;密钥形态学不是本模拟器的验收对象。
- CatalogBased=false:sim 渠道不做渠道侧商品目录(那是 waffo/paypal 的 REST 面能力,与事件管线无关),checkout 直接成功,测试无需注册商品。
本包是 DEV/测试设施:只允许在 example 的 DEV 接线(PLOYKIT_DEV_ENABLED=1 且非 production)与测试中注册,绝不进生产(见 simhttp.Mount 的 panic 兜底)。
Harness 是测试接口核心:持三渠道 + 已装配 BillingService,Checkout 走真实 svc.CreateCheckout,Deliver 构造签名信封经真实 HTTP 层(billinghttp.Mount 的 POST /webhooks/billing/{channel} + httptest)投递——raw body 保真。
Index ¶
- Constants
- func DefaultSecret(name string) string
- func DeliverTo(ctx context.Context, svc *app.BillingService, channels app.ChannelSet, ...) error
- func Factories(getenv func(string) string) map[string]func(fields map[string]string) (app.PaymentChannel, error)
- func OverridePlanPrice(ctx context.Context, pool *pgxpool.Pool, planCode string, ...) error
- func SetOrderExpiresAt(ctx context.Context, pool *pgxpool.Pool, orderID string, expiresAt time.Time) error
- func SignBody(secret string, body []byte) string
- func WorkspaceOwner(ctx context.Context, pool *pgxpool.Pool, workspaceID string) (string, error)
- type AssembleDeps
- type CheckoutOpts
- type CheckoutResult
- type DeliverResult
- type EventSpec
- type Harness
- func (h *Harness) Checkout(ctx context.Context, channel, workspaceID, planCode string, ...) (CheckoutResult, error)
- func (h *Harness) Close()
- func (h *Harness) Deliver(ctx context.Context, channel string, spec EventSpec) (DeliverResult, error)
- func (h *Harness) EnsurePlan(ctx context.Context, code, name, currency string, ...) error
- func (h *Harness) EnsureWorkspace(ctx context.Context, label string) (userID, workspaceID string, err error)
- func (h *Harness) URL() string
- type Paypal
- func (c *Paypal) Capabilities() app.ChannelCaps
- func (c *Paypal) ChannelConfig() app.ChannelConfigInfo
- func (c *Paypal) ConfigSchema() []app.FieldSpec
- func (c *Paypal) CreateCheckout(_ context.Context, req app.CheckoutRequest) (domain.CheckoutSession, error)
- func (c *Paypal) EnvProvidedKeys() []string
- func (c *Paypal) Name() string
- func (c *Paypal) ParseWebhook(_ context.Context, req app.WebhookRequest) (domain.PaymentEvent, error)
- func (c Paypal) PaymentChannelDialect()
- func (c Paypal) SigningSecret() string
- type Signer
- type Stripe
- func (c *Stripe) Capabilities() app.ChannelCaps
- func (c *Stripe) ChannelConfig() app.ChannelConfigInfo
- func (c *Stripe) ConfigSchema() []app.FieldSpec
- func (c *Stripe) CreateCheckout(_ context.Context, req app.CheckoutRequest) (domain.CheckoutSession, error)
- func (c *Stripe) EnvProvidedKeys() []string
- func (c *Stripe) Name() string
- func (c *Stripe) ParseWebhook(_ context.Context, req app.WebhookRequest) (domain.PaymentEvent, error)
- func (c Stripe) PaymentChannelDialect()
- func (c Stripe) SigningSecret() string
- type Waffo
- func (c *Waffo) Capabilities() app.ChannelCaps
- func (c *Waffo) ChannelConfig() app.ChannelConfigInfo
- func (c *Waffo) ConfigSchema() []app.FieldSpec
- func (c *Waffo) CreateCheckout(_ context.Context, req app.CheckoutRequest) (domain.CheckoutSession, error)
- func (c *Waffo) EnvProvidedKeys() []string
- func (c *Waffo) Name() string
- func (c *Waffo) ParseWebhook(_ context.Context, req app.WebhookRequest) (domain.PaymentEvent, error)
- func (c Waffo) PaymentChannelDialect()
- func (c Waffo) SigningSecret() string
Constants ¶
const ( EnvWaffoSecret = "SIMWAFFO_SECRET" EnvPaypalSecret = "SIMPAYPAL_SECRET" EnvStripeSecret = "SIMSTRIPE_SECRET" )
环境变量名(BC-5 DB 值 > env > 内置 dev 缺省 三级回退)。
const ( NameWaffo = "simwaffo" NamePaypal = "simpaypal" NameStripe = "simstripe" )
渠道名(与 factory 注册键一致)。
const FieldSecret = "secret"
FieldSecret 是 ConfigSchema 唯一字段键,同时是 billing_channel.<name>.secret 设置键。
const SignatureHeader = "X-Sim-Signature"
SignatureHeader 是三个 sim 方言共用的验签头(见包注释的有意差异节)。
Variables ¶
This section is empty.
Functions ¶
func DefaultSecret ¶
DefaultSecret 是未配置任何密钥时的内置 dev 缺省(每渠道不同,跨渠道 互不可签——一个渠道的签名在另一个渠道的验签下必须失败)。
func DeliverTo ¶
func DeliverTo(ctx context.Context, svc *app.BillingService, channels app.ChannelSet, repo app.Repo, channel string, spec EventSpec) error
DeliverTo 是 Harness.Deliver 的同进程孪生(simhttp dev 端点用):信封与 签名构造完全同一份代码,但不自环回 HTTP——同进程 handler 直接调 Svc.HandleWebhook(真实管线里 webhook 经 HTTP 进来的地方就是它包 raw body;此处保真的恰是 raw body + 验签,注释说明的降级路径)。
func Factories ¶
func Factories(getenv func(string) string) map[string]func(fields map[string]string) (app.PaymentChannel, error)
Factories 返回三个方言的 AtomicRegistry 工厂(产品 main.go 的 DEV 接线 一行并入 channelFactories)。工厂恒返回可用渠道(见 resolveSecret), 永不因凭据缺失跳过——DEV 模式注册了就要能用。
func OverridePlanPrice ¶
func OverridePlanPrice(ctx context.Context, pool *pgxpool.Pool, planCode string, interval domain.BillingInterval, amountCents int, currency string) error
OverridePlanPrice 读-改-写 plan 行的价格键(保持其余 limits 不动)—— CheckoutOpts.AmountOverride/Currency 的落点,Harness 与 simhttp 共用。
func SetOrderExpiresAt ¶
func SetOrderExpiresAt(ctx context.Context, pool *pgxpool.Pool, orderID string, expiresAt time.Time) error
SetOrderExpiresAt 改写订单 expires_at(CheckoutOpts.ExpiresAt 的落点: 模拟渠道报告的会话过期时刻)。零值时间清除为 NULL(manual 形态)。
Types ¶
type AssembleDeps ¶
type AssembleDeps struct {
Pool *pgxpool.Pool
Repo app.Repo
Now app.Clock
Auditor app.Auditor
Log *slog.Logger
Hooks app.BillingHooks
Config app.Config // billing 服务配置(Currency/SuccessURL…);零值用缺省
ChannelCfg map[string]coreConfig
ExtraChans []app.PaymentChannel // 追加注册(默认已含 manual)
}
AssembleDeps 是 Assemble 的输入;零值字段走缺省(repo=billingpg.New(pool)、 now=UTC 真时钟、auditor/log 为 nil 安全)。ChannelCfg 可按名覆盖渠道 secret / 会话 TTL / approve 基址(如把 simhttp 的 URL 接进 approve 链接)。
type CheckoutOpts ¶
CheckoutOpts 是下单旋钮:
- AmountOverride/Currency:在 CreateCheckout **之前**改写 plan 行的价格/ 币种——订单金额/币种由真实管线从 plan 自然生成(不是事后改单)。
- ExpiresAt:下单**之后**把 order.expires_at 改写为该时刻——模拟渠道 报告的会话早已过期/尚未过期(测宽限与竞态的时钟快进旋钮)。
type CheckoutResult ¶
type CheckoutResult struct {
Session domain.CheckoutSession
Order domain.Order
}
CheckoutResult 返回会话与落库后的订单。
type DeliverResult ¶
DeliverResult 汇总投递结果(Repeat>1 时每个来回一行)。
type EventSpec ¶
type EventSpec struct {
Type string // 方言事件类型(如 subscription.activated / BILLING.SUBSCRIPTION.ACTIVATED / checkout.session.completed)
OrderID string // 本地订单 id:自动补 custom_id/metadata.order_id/channel_ref/金额
ID string // 渠道侧引用(waffo orderId / paypal 订阅 id / stripe 会话 id)——测「同 id 不同 eventId」时显式指定
EventID string // 事件级 id(waffo eventId / paypal WH- / stripe evt-);显式指定以测幂等/重复
Amount string // 金额字符串旋钮("4500"/"4500.00"/"4,500" 畸形)
Currency string
PeriodNumber int // waffo 期号(1=ignored,>1=renewed)
SaleID string // paypal sale id(退款锚:SALE.COMPLETED 与 REFUNDED 传同值)
PaymentStatus string // stripe checkout.session payment_status("unpaid" → ignored 路径)
DropAgreementID bool // paypal:不带 billing_agreement_id(个别载荷缺失形态)
DropCustomID bool // paypal:不带 custom_id(内核退化 SubscriptionRef 路径)
TotalRefundedShape bool // paypal 退款:用 total_refunded_amount 形态而非 amount
Repeat int // 同一签名信封重复投递次数(真重放:同 body 同签名)
}
EventSpec 是投递旋钮(方言无关;各字段按渠道方言落入对应信封位置)。 零值字段自动补全:渠道引用取订单 channel_ref、事件 id 自动生成、金额 按订单金额+币种格式化——只拧要测的那个旋钮。
type Harness ¶
type Harness struct {
Pool *pgxpool.Pool
Repo app.Repo
Svc *app.BillingService
Registry *app.ChannelRegistry
// contains filtered or unexported fields
}
Harness 是「模拟支付渠道测试接口」的核心:持有三个 sim 方言渠道 + manual 渠道 + 已装配的 BillingService,并把 webhook 投递挂到真实 HTTP 层 (billinghttp.Mount 的 POST /webhooks/billing/{channel},经 httptest server 进出)——raw body / 验签 / 路由语义全部保真。
func Assemble ¶
func Assemble(deps AssembleDeps) (*Harness, error)
Assemble 装配 Harness:三 sim 渠道 + manual 注册进 ChannelRegistry, BillingService 就绪,webhook 路由挂上 httptest server。调用方负责 Close。
func (*Harness) Checkout ¶
func (h *Harness) Checkout(ctx context.Context, channel, workspaceID, planCode string, interval domain.BillingInterval, opts CheckoutOpts) (CheckoutResult, error)
Checkout 走真实 svc.CreateCheckout(plan 解析 → 建单 → 渠道会话 → SetOrderChannelRefAndExpiry 全链路),principal 取 workspace 创建者。
func (*Harness) Deliver ¶
func (h *Harness) Deliver(ctx context.Context, channel string, spec EventSpec) (DeliverResult, error)
Deliver 构造方言信封 + X-Sim-Signature 签名,经真实 HTTP 层投递 (httptest server → billinghttp 的 POST /webhooks/billing/{channel}, raw body 保真)。返回每次投递的 HTTP 状态(200 = 管线接收并处理完)。
func (*Harness) EnsurePlan ¶
func (h *Harness) EnsurePlan(ctx context.Context, code, name, currency string, monthlyCents, yearlyCents int) error
EnsurePlan 幂等落一个可定价 plan(007 种子的 free/pro 无价格,测试需要 price_monthly_cents/price_yearly_cents 才能过 svc.CreateCheckout 的定价闸)。
type Paypal ¶
type Paypal struct {
// contains filtered or unexported fields
}
Paypal 是 simpaypal 渠道:镜像 billing/adapters/paypal 的事件信封与五律映射。
信封(与真 PayPal 同形):{id(WH-xxx,事件级唯一), event_type, resource_type, resource{id, status, custom_id, billing_agreement_id, amount{currency,total}, sale_id, total_refunded_amount{...}}}。订阅标识:custom_id = 本地订单号 (建订阅时塞入,BILLING.SUBSCRIPTION.* 原样回带);billing_agreement_id = 订阅 id(PAYMENT.SALE.* 的汇合点)。
事件映射(与真 paypal 一致):
BILLING.SUBSCRIPTION.ACTIVATED → checkout.completed(订阅对象不带金额 → AmountCents=0,amountMismatch 对 0 走忽略路径,首期金额对账交给 同拍的 SALE 事件) PAYMENT.SALE.COMPLETED → subscription.renewed(OrderID=custom_id, SubscriptionRef=billing_agreement_id,金额=resource.amount, PaymentIntentRef=sale id 供退款反查) BILLING.SUBSCRIPTION.CANCELLED → subscription.canceled PAYMENT.SALE.REFUNDED → refund.created(金额=amount,缺失退化 total_refunded_amount;订单反查优先 billing_agreement_id,不在载荷时 退化 sale_id(FindOrderByPaymentIntent)+resource.id) 其余 → ignored
验签差异见包注释:真 paypal 调 verify-webhook-signature API,sim 用 X-Sim-Signature HMAC——验签语义(对 raw body、失败拒收)一致。
func (*Paypal) Capabilities ¶
func (c *Paypal) Capabilities() app.ChannelCaps
func (*Paypal) ChannelConfig ¶
func (c *Paypal) ChannelConfig() app.ChannelConfigInfo
func (*Paypal) ConfigSchema ¶
func (*Paypal) CreateCheckout ¶
func (c *Paypal) CreateCheckout(_ context.Context, req app.CheckoutRequest) (domain.CheckoutSession, error)
CreateCheckout 返回本地 approve URL、SUB-SIM-* 会话引用(= 真渠道的 订阅 id SUB-xxx,也是 SALE 事件的 billing_agreement_id)、可配置 ExpiresAt (默认 1h)。
func (*Paypal) EnvProvidedKeys ¶
func (*Paypal) ParseWebhook ¶
func (c *Paypal) ParseWebhook(_ context.Context, req app.WebhookRequest) (domain.PaymentEvent, error)
ParseWebhook:验签 → 解码 → 五律映射。ChannelEventID = event_type + ":" + id (五律 4:PayPal 资源 id 在同一对象的不同事件间复用,不拼类型会吞事件)。
func (Paypal) PaymentChannelDialect ¶
func (c Paypal) PaymentChannelDialect()
PaymentChannelDialect 哨兵方法把 Signer 限定在本包三方言内。
func (Paypal) SigningSecret ¶
func (c Paypal) SigningSecret() string
SigningSecret 暴露当前验签密钥——Harness / simhttp 在投递时用它签名。 渠道经 AtomicRegistry 热重建后取的是新实例,投递方每次从注册表现取, 因此 DB 改密钥后新投递天然用新钥。
type Signer ¶
type Signer interface {
PaymentChannelDialect()
SigningSecret() string
}
Signer 是 Harness / simhttp 投递侧取验签密钥的口(见 core.SigningSecret)。
type Stripe ¶
type Stripe struct {
// contains filtered or unexported fields
}
Stripe 是 simstripe 渠道:镜像 billing/adapters/stripe 的事件信封与五律映射。
信封(与真 Stripe 同形):{id(evt_xxx), type, data{object{...}}},object 随 事件族异构:checkout.session / invoice / charge / subscription。订单反查靠 checkout 会话 metadata.order_id(本地订单 UUID),invoice 续期靠 lines.data[0].metadata.order_id 回带。
事件映射(与真 stripe 一致):
checkout.session.completed → checkout.completed(amount_total, metadata.order_id,payment_intent,subscription;payment_status 非 paid/no_payment_required → ignored) invoice.paid → subscription.renewed(amount_paid, subscription 引用,lines 的 order_id) charge.refunded → refund.created(payment_intent 反查锚, amount_refunded) customer.subscription.deleted → subscription.canceled(subscription id) 其余 → ignored
幂等键:ChannelEventID = evt.id(真 stripe 事件 id 本身全局唯一,不拼类型)。
func (*Stripe) Capabilities ¶
func (c *Stripe) Capabilities() app.ChannelCaps
func (*Stripe) ChannelConfig ¶
func (c *Stripe) ChannelConfig() app.ChannelConfigInfo
func (*Stripe) ConfigSchema ¶
func (*Stripe) CreateCheckout ¶
func (c *Stripe) CreateCheckout(_ context.Context, req app.CheckoutRequest) (domain.CheckoutSession, error)
CreateCheckout 返回本地 approve URL、cs_sim_* 会话引用、可配置 ExpiresAt (默认 1h)。订阅引用按会话确定性派生(sub_sim_* 同序号)——真 stripe 的 subscription 由会话创建,sim 用同源序号保持「会话→订阅」可对应。
func (*Stripe) EnvProvidedKeys ¶
func (*Stripe) ParseWebhook ¶
func (c *Stripe) ParseWebhook(_ context.Context, req app.WebhookRequest) (domain.PaymentEvent, error)
ParseWebhook:验签 → 解码 → 五律映射。
func (Stripe) PaymentChannelDialect ¶
func (c Stripe) PaymentChannelDialect()
PaymentChannelDialect 哨兵方法把 Signer 限定在本包三方言内。
func (Stripe) SigningSecret ¶
func (c Stripe) SigningSecret() string
SigningSecret 暴露当前验签密钥——Harness / simhttp 在投递时用它签名。 渠道经 AtomicRegistry 热重建后取的是新实例,投递方每次从注册表现取, 因此 DB 改密钥后新投递天然用新钥。
type Waffo ¶
type Waffo struct {
// contains filtered or unexported fields
}
Waffo 是 simwaffo 渠道:镜像 billing/adapters/waffo 的事件信封与五律映射。
信封(与真 waffo 同形):{id(订单级,跨期相同!), eventId(期级唯一), eventType, mode, timestamp, data{orderId, chargedAmount, currency, periodNumber, refundedAmount, orderMetadata{order_id}}}。订单反查靠 checkout 会话 metadata.order_id 透传回来的 data.orderMetadata.order_id(本地订单 UUID)。
事件映射(与真 waffo 一字不差):
subscription.activated → checkout.completed(带金额,落订阅引用=orderId)
subscription.payment_succeeded → periodNumber>1: subscription.renewed
periodNumber==1: ignored(activated 已覆盖)
subscription.canceled → subscription.canceled
refund.succeeded → refund.created(refundedAmount;订阅退款带订阅引用)
其余 → ignored
幂等键(五律 4,与真 waffo 同语义):ChannelEventID = eventType + ":" + eventId(eventId 缺失回退顶层 id)。同一订阅订单各期顶层 id 相同、只有 eventId 互异——回退顶层 id 会把第 2 期起的续费当重复吞掉。
func (*Waffo) Capabilities ¶
func (c *Waffo) Capabilities() app.ChannelCaps
func (*Waffo) ChannelConfig ¶
func (c *Waffo) ChannelConfig() app.ChannelConfigInfo
func (*Waffo) ConfigSchema ¶
func (*Waffo) CreateCheckout ¶
func (c *Waffo) CreateCheckout(_ context.Context, req app.CheckoutRequest) (domain.CheckoutSession, error)
CreateCheckout 返回本地 approve URL、ORD-SIM-* 会话引用(= 真渠道的稳定 订阅引用 ORD_xxx,激活/续费/取消全程不变)、可配置 ExpiresAt(默认 1h)。
func (*Waffo) EnvProvidedKeys ¶
func (*Waffo) ParseWebhook ¶
func (c *Waffo) ParseWebhook(_ context.Context, req app.WebhookRequest) (domain.PaymentEvent, error)
ParseWebhook:验签(X-Sim-Signature,对 raw body)→ 解码 → 五律映射。
func (Waffo) PaymentChannelDialect ¶
func (c Waffo) PaymentChannelDialect()
PaymentChannelDialect 哨兵方法把 Signer 限定在本包三方言内。
func (Waffo) SigningSecret ¶
func (c Waffo) SigningSecret() string
SigningSecret 暴露当前验签密钥——Harness / simhttp 在投递时用它签名。 渠道经 AtomicRegistry 热重建后取的是新实例,投递方每次从注册表现取, 因此 DB 改密钥后新投递天然用新钥。