feat(billing): 订阅制后端 —— 手动购买 + 周期发放积分 + 到期失效
规格(按需求):用户扫码买一个订阅周期,有效期内每 N 天发一次积分,到期即失效, 不自动续费。N 与每次发放额度都在套餐里配,后台可改。 为什么不做自动续费:微信 Native 扫码支付没有代扣能力,真自动续费要走「委托代扣」 ——另一套产品与资质。与其假装有,不如把"到期即失效"这个语义做扎实。 两个决定,都写进了代码注释: - **发放语义是累加而非重置**。每次刷新写一条 grant 分录、余额累加。重置型 (月度配额清零)会让「余额 = SUM(ledger)」这条对账不变量变复杂,且有误清 用户自费积分的风险。 - **订阅开通放在 store.MarkOrderPaid 内**,而不是各调用方。回调与掉单补偿两条 路都经过它,放这一处才没人能漏掉;按 orderID 幂等,重复调用无害。 复用而非另造:订阅单与积分包单走同一条支付链路(下单/回调/查单/掉单补偿), 只是 kind=sub 且 credits_micro=0——积分不在付款时给,由订阅按周期发。 定时器每 10 分钟扫一轮,语义与幂等都在 store.TickSubscription 里,与手动触发 共用,不会两处漂移。停机期间欠下的发放会一次性补齐。 8 组测试。其中一条当场抓到真 bug:开通时原本无条件发一笔,同一订单重复开通 (回调重推/查单赛跑)会因序号自增绕过幂等索引,白送积分。改为开通也走与定时器 同一套排期判断——排期天然幂等。教训:幂等键要锚在业务时间轴上,不能靠自增序号。 Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
@@ -39,10 +39,11 @@ const orderTTL = 30 * time.Minute
|
||||
func (h *Handler) BillingCreateOrder(c *gin.Context) {
|
||||
var b struct {
|
||||
PackID string `json:"pack_id"`
|
||||
PlanID string `json:"plan_id"` // 传它=买订阅周期;与 pack_id 二选一
|
||||
Channel string `json:"channel"`
|
||||
}
|
||||
if err := c.ShouldBindJSON(&b); err != nil || strings.TrimSpace(b.PackID) == "" {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "pack_id 必填"})
|
||||
if err := c.ShouldBindJSON(&b); err != nil || (strings.TrimSpace(b.PackID) == "" && strings.TrimSpace(b.PlanID) == "") {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "pack_id 或 plan_id 必填"})
|
||||
return
|
||||
}
|
||||
channel := strings.TrimSpace(b.Channel)
|
||||
@@ -61,21 +62,40 @@ func (h *Handler) BillingCreateOrder(c *gin.Context) {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "无计费租户上下文"})
|
||||
return
|
||||
}
|
||||
pk, err := h.db.GetPack(ctx, b.PackID)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "积分包不存在或已下架"})
|
||||
return
|
||||
}
|
||||
o := &store.PaymentOrder{
|
||||
TenantID: billing, UserID: uid, PackID: pk.ID,
|
||||
AmountFen: pk.PriceFen, CreditsMicro: pk.CreditsMicro,
|
||||
Channel: channel, Status: store.OrderPending,
|
||||
// 订阅单与积分包单走同一条支付链路:只有订单内容不同,下单/回调/查单/掉单补偿全复用。
|
||||
var o *store.PaymentOrder
|
||||
var desc string
|
||||
if pid := strings.TrimSpace(b.PlanID); pid != "" {
|
||||
pl := h.db.GetSubPlan(ctx, pid)
|
||||
if pl == nil || !pl.Active {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "订阅套餐不存在或已下架"})
|
||||
return
|
||||
}
|
||||
// 订阅单 credits_micro 恒为 0:积分不在付款时一次给,而是订阅期内按周期发放。
|
||||
o = &store.PaymentOrder{
|
||||
TenantID: billing, UserID: uid, Kind: store.OrderKindSub, PlanID: pl.ID,
|
||||
AmountFen: pl.PriceFen, CreditsMicro: 0,
|
||||
Channel: channel, Status: store.OrderPending,
|
||||
}
|
||||
desc = "sundynix 订阅 · " + pl.Name
|
||||
} else {
|
||||
pk, err := h.db.GetPack(ctx, b.PackID)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "积分包不存在或已下架"})
|
||||
return
|
||||
}
|
||||
o = &store.PaymentOrder{
|
||||
TenantID: billing, UserID: uid, PackID: pk.ID, Kind: store.OrderKindPack,
|
||||
AmountFen: pk.PriceFen, CreditsMicro: pk.CreditsMicro,
|
||||
Channel: channel, Status: store.OrderPending,
|
||||
}
|
||||
desc = "sundynix 积分充值 · " + pk.Name
|
||||
}
|
||||
if err := h.db.CreateOrder(ctx, o); err != nil {
|
||||
c.JSON(http.StatusBadGateway, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
intent, err := ch.CreatePay(ctx, o.ID, "sundynix 积分充值 · "+pk.Name, pk.PriceFen)
|
||||
intent, err := ch.CreatePay(ctx, o.ID, desc, o.AmountFen)
|
||||
if err != nil {
|
||||
// 渠道下单失败的单直接作废,不留一堆永远付不了的 pending。
|
||||
_ = h.db.ExpireOrder(ctx, o.ID)
|
||||
|
||||
@@ -0,0 +1,83 @@
|
||||
package handler
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"strings"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
|
||||
"github.com/sundynix/sundynix-gateway/internal/store"
|
||||
)
|
||||
|
||||
// 订阅 API。用户面只有「看套餐 / 看我的订阅」,下单复用现有 /billing/orders
|
||||
// (多传 plan_id 即可),因为支付链路、幂等、掉单补偿都已经在那条路上验过了,
|
||||
// 没必要为订阅再造一条支付路径。
|
||||
|
||||
// ---- 用户面 ----
|
||||
|
||||
// BillingSubPlans: GET /api/v1/billing/sub-plans —— 在售订阅套餐。
|
||||
func (h *Handler) BillingSubPlans(c *gin.Context) {
|
||||
c.JSON(http.StatusOK, gin.H{"plans": h.db.ListSubPlans(c.Request.Context(), true)})
|
||||
}
|
||||
|
||||
// MySubscription: GET /api/v1/billing/subscription —— 我的当前订阅(无则 null)。
|
||||
func (h *Handler) MySubscription(c *gin.Context) {
|
||||
ctx := c.Request.Context()
|
||||
billing := h.db.ResolveBillingTenantID(ctx, userID(c), tenantID(c))
|
||||
if billing == "" {
|
||||
c.JSON(http.StatusOK, gin.H{"subscription": nil})
|
||||
return
|
||||
}
|
||||
sub := h.db.ActiveSubscription(ctx, billing)
|
||||
if sub == nil {
|
||||
c.JSON(http.StatusOK, gin.H{"subscription": nil})
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, gin.H{"subscription": sub, "plan": h.db.GetSubPlan(ctx, sub.PlanID)})
|
||||
}
|
||||
|
||||
// ---- 管理端 ----
|
||||
|
||||
// AdminSubPlans: GET /api/v1/admin/sub-plans —— 全部套餐(含下架)。
|
||||
func (h *Handler) AdminSubPlans(c *gin.Context) {
|
||||
c.JSON(http.StatusOK, gin.H{"plans": h.db.ListSubPlans(c.Request.Context(), false)})
|
||||
}
|
||||
|
||||
// AdminSaveSubPlan: PUT /api/v1/admin/sub-plans —— 新增/改套餐(id 空=新增)。
|
||||
// 积分以「积分」为单位收(面向人),服务端转 micro。
|
||||
func (h *Handler) AdminSaveSubPlan(c *gin.Context) {
|
||||
var b struct {
|
||||
ID string `json:"id"`
|
||||
Name string `json:"name"`
|
||||
PriceFen int64 `json:"price_fen"`
|
||||
DurationDays int `json:"duration_days"`
|
||||
RefillCredits float64 `json:"refill_credits"`
|
||||
RefillInterval int `json:"refill_interval_days"`
|
||||
Active bool `json:"active"`
|
||||
Sort int `json:"sort"`
|
||||
}
|
||||
if err := c.ShouldBindJSON(&b); err != nil || strings.TrimSpace(b.Name) == "" {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "name 必填"})
|
||||
return
|
||||
}
|
||||
pl := &store.SubscriptionPlan{
|
||||
BaseModel: store.BaseModel{ID: b.ID},
|
||||
Name: strings.TrimSpace(b.Name),
|
||||
PriceFen: b.PriceFen,
|
||||
DurationDays: b.DurationDays,
|
||||
RefillCreditsMicro: int64(b.RefillCredits * 1e6),
|
||||
RefillIntervalDays: b.RefillInterval,
|
||||
Active: b.Active,
|
||||
Sort: b.Sort,
|
||||
}
|
||||
if err := h.db.SaveSubPlan(c.Request.Context(), pl); err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, gin.H{"id": pl.ID})
|
||||
}
|
||||
|
||||
// AdminSubscriptions: GET /api/v1/admin/subscriptions —— 全平台订阅观测。
|
||||
func (h *Handler) AdminSubscriptions(c *gin.Context) {
|
||||
c.JSON(http.StatusOK, gin.H{"subscriptions": h.db.AllSubscriptions(c.Request.Context(), 200)})
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
package handler
|
||||
|
||||
import (
|
||||
"context"
|
||||
"log"
|
||||
"time"
|
||||
)
|
||||
|
||||
// 订阅推进定时器:周期扫 active 订阅 → 该发的发、该过期的置过期。
|
||||
// 与掉单补偿(payment_reconcile.go)同一范式:定时器只是"兜底触发器",
|
||||
// 真正的语义与幂等都在 store.TickSubscription 里,两处不会漂移。
|
||||
//
|
||||
// 为什么需要它:订阅是"有效期内每 N 天发一次积分",没有用户请求来驱动这个节拍。
|
||||
// 进程停机期间欠下的发放,由 TickSubscription 的补发逻辑一次性补齐。
|
||||
const subTickInterval = 10 * time.Minute
|
||||
|
||||
// StartSubscriptionTicker 随进程生命周期运行;多实例并发也安全(发放靠 ledger 唯一索引幂等)。
|
||||
func (h *Handler) StartSubscriptionTicker(ctx context.Context) {
|
||||
go func() {
|
||||
t := time.NewTicker(subTickInterval)
|
||||
defer t.Stop()
|
||||
h.tickSubscriptions(ctx) // 启动即跑一次,把停机期间欠的补上
|
||||
for {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return
|
||||
case <-t.C:
|
||||
h.tickSubscriptions(ctx)
|
||||
}
|
||||
}
|
||||
}()
|
||||
log.Printf("[sub] 订阅推进定时器已启动(每 %s 扫一次)", subTickInterval)
|
||||
}
|
||||
|
||||
func (h *Handler) tickSubscriptions(ctx context.Context) {
|
||||
subs := h.db.DueSubscriptions(ctx, 200)
|
||||
if len(subs) == 0 {
|
||||
return
|
||||
}
|
||||
now := time.Now()
|
||||
var granted, expired int
|
||||
for i := range subs {
|
||||
g, exp, err := h.db.TickSubscription(ctx, &subs[i], now)
|
||||
if err != nil {
|
||||
// 单条失败不影响其它订阅;下一轮会重试(幂等,不会重复发)
|
||||
log.Printf("[sub] ⚠️ 推进订阅 %s 失败: %v", subs[i].ID, err)
|
||||
continue
|
||||
}
|
||||
granted += g
|
||||
if exp {
|
||||
expired++
|
||||
}
|
||||
}
|
||||
// 只在有变化时记一行,避免空转刷屏
|
||||
if granted+expired > 0 {
|
||||
log.Printf("[sub] 推进:发放 %d 笔、过期 %d 条(本轮 %d 条订阅)", granted, expired, len(subs))
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user