From 68608c15921246002d090e481af287b371522774 Mon Sep 17 00:00:00 2001 From: Blizzard Date: Tue, 21 Jul 2026 11:23:41 +0800 Subject: [PATCH] =?UTF-8?q?feat(wechat):=20=E6=94=AF=E4=BB=98=E6=88=90?= =?UTF-8?q?=E5=8A=9F=E5=90=8E=E5=BE=AE=E4=BF=A1=E5=AE=A2=E6=9C=8D=E6=B6=88?= =?UTF-8?q?=E6=81=AF=E6=8E=A8=E5=9B=9E=E6=89=A7=EF=BC=88=E7=A7=AF=E5=88=86?= =?UTF-8?q?=E5=8C=85/=E8=AE=A2=E9=98=85=E8=B4=AD=E4=B9=B0=EF=BC=89?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 用户扫码付款后(在 48h 互动窗口内),主动推一条客服消息回执: 到账积分/开通套餐 + 当前余额。只在 MarkOrderPaid changed=true 首次到账时推, 异步+超时隔离,失败只记日志、绝不影响入账。非微信用户自动跳过。 不做「周期刷新提醒」:客服消息受 48h 窗口限制,定时刷新那刻用户多半已超窗、 必然失败,那类隔天提醒须用模板消息(暂缓)。 Co-Authored-By: Claude Opus 4.8 --- .../internal/handler/billing_pay.go | 11 ++- .../internal/handler/wechat_notify.go | 72 +++++++++++++++++++ .../internal/handler/wechat_notify_test.go | 19 +++++ sundynix-gateway/internal/wechat/mp.go | 29 ++++++++ 4 files changed, 129 insertions(+), 2 deletions(-) create mode 100644 sundynix-gateway/internal/handler/wechat_notify.go create mode 100644 sundynix-gateway/internal/handler/wechat_notify_test.go diff --git a/sundynix-gateway/internal/handler/billing_pay.go b/sundynix-gateway/internal/handler/billing_pay.go index 0a8ecd2..9bce707 100644 --- a/sundynix-gateway/internal/handler/billing_pay.go +++ b/sundynix-gateway/internal/handler/billing_pay.go @@ -147,7 +147,10 @@ func (h *Handler) reconcileOrder(ctx context.Context, o *store.PaymentOrder) (*s if r, err := ch.QueryOrder(ctx, o.ID); err == nil { switch { case r.Paid && r.AmountFen == o.AmountFen: - if _, err := h.db.MarkOrderPaid(ctx, o.ID, r.ChannelTxn); err == nil { + if changed, err := h.db.MarkOrderPaid(ctx, o.ID, r.ChannelTxn); err == nil { + if changed { + h.notifyOrderPaid(o.ID) // 首次到账才推回执,避免重复查单重复推送 + } o, _ = h.db.GetOrder(ctx, o.ID) } case r.Paid: // 金额对不上:不入账,人工对账(比错账便宜) @@ -198,10 +201,14 @@ func (h *Handler) PaymentCallback(c *gin.Context) { c.JSON(http.StatusOK, gin.H{"code": "SUCCESS"}) return } - if _, err := h.db.MarkOrderPaid(ctx, o.ID, r.ChannelTxn); err != nil { + changed, err := h.db.MarkOrderPaid(ctx, o.ID, r.ChannelTxn) + if err != nil { c.JSON(http.StatusInternalServerError, gin.H{"code": "FAIL", "message": "入账失败"}) return } + if changed { + h.notifyOrderPaid(o.ID) // 首次到账才推回执(回调可能重复推送,靠 changed 去重) + } c.JSON(http.StatusOK, gin.H{"code": "SUCCESS"}) } diff --git a/sundynix-gateway/internal/handler/wechat_notify.go b/sundynix-gateway/internal/handler/wechat_notify.go new file mode 100644 index 0000000..7eae64d --- /dev/null +++ b/sundynix-gateway/internal/handler/wechat_notify.go @@ -0,0 +1,72 @@ +package handler + +import ( + "context" + "fmt" + "log" + "time" + + "github.com/sundynix/sundynix-gateway/internal/store" + "github.com/sundynix/sundynix-gateway/internal/wechat" +) + +// 支付到账后给下单人推一条微信客服消息(回执)。 +// +// 为什么只做「支付回执」不做「周期刷新提醒」:客服消息只能在用户 48h 内与公众号 +// 互动过时下发。支付回执时用户刚扫码付完款,稳在窗口内;而订阅的周期刷新由定时器 +// 触发,那一刻用户多半早已超出 48h → 客服消息必然失败。隔天的提醒须用模板消息(暂缓)。 + +const wxNotifyTimeout = 10 * time.Second + +// notifyOrderPaid 尽力而为地给下单人推支付回执:异步、超时隔离,任何失败只记日志, +// 绝不影响入账主流程(钱已收、账已记,通知发不发都不能回滚)。 +// 仅在 MarkOrderPaid 返回 changed=true(首次到账)时调用,避免重复回调重复推送。 +func (h *Handler) notifyOrderPaid(orderID string) { + go func() { + ctx, cancel := context.WithTimeout(context.Background(), wxNotifyTimeout) + defer cancel() + + o, err := h.db.GetOrder(ctx, orderID) + if err != nil || o == nil || o.UserID == "" { + return + } + u, err := h.db.GetUserByID(ctx, o.UserID) + if err != nil || u == nil || u.WechatOpenID == "" { + return // 非微信用户(邮箱注册等)无从推送,静默跳过 + } + cfg := h.loadWechatMP(ctx) + if !cfg.Enabled() { + return + } + token, err := h.accessToken(ctx, cfg) + if err != nil { + log.Printf("[wxnotify] 取 access_token 失败 order=%s: %v", orderID, err) + return + } + if err := wechat.SendCustomText(ctx, token, u.WechatOpenID, h.composePaidMessage(ctx, o)); err != nil { + log.Printf("[wxnotify] 支付回执推送失败 order=%s: %v", orderID, err) + } + }() +} + +// composePaidMessage 按订单类型拼回执文案,并带上当前积分余额。 +func (h *Handler) composePaidMessage(ctx context.Context, o *store.PaymentOrder) string { + bal := credits(h.db.TenantBalance(ctx, o.TenantID)) + if o.Kind == store.OrderKindSub { + name := "订阅" + if pl := h.db.GetSubPlan(ctx, o.PlanID); pl != nil && pl.Name != "" { + name = pl.Name + } + return fmt.Sprintf("✅ 订阅开通成功\n套餐:%s\n积分将在有效期内按周期自动发放。\n当前余额:%s 积分", name, bal) + } + return fmt.Sprintf("✅ 充值成功\n本次到账:%s 积分\n当前余额:%s 积分", credits(o.CreditsMicro), bal) +} + +// credits 把 micro 积分格式化成人类可读数(去掉多余小数)。 +func credits(micro int64) string { + const unit = 1_000_000 + if micro%unit == 0 { + return fmt.Sprintf("%d", micro/unit) + } + return fmt.Sprintf("%.2f", float64(micro)/float64(unit)) +} diff --git a/sundynix-gateway/internal/handler/wechat_notify_test.go b/sundynix-gateway/internal/handler/wechat_notify_test.go new file mode 100644 index 0000000..ff3ce15 --- /dev/null +++ b/sundynix-gateway/internal/handler/wechat_notify_test.go @@ -0,0 +1,19 @@ +package handler + +import "testing" + +// 回执里的积分数要给人看:整除去小数、非整留两位。 +func TestCreditsFormat(t *testing.T) { + cases := map[int64]string{ + 0: "0", + 1_000_000: "1", + 5_000_000: "5", + 1_500_000: "1.50", + 2_340_000: "2.34", + } + for micro, want := range cases { + if got := credits(micro); got != want { + t.Fatalf("credits(%d)=%q want %q", micro, got, want) + } + } +} diff --git a/sundynix-gateway/internal/wechat/mp.go b/sundynix-gateway/internal/wechat/mp.go index 76f73d7..0560b32 100644 --- a/sundynix-gateway/internal/wechat/mp.go +++ b/sundynix-gateway/internal/wechat/mp.go @@ -179,6 +179,35 @@ func (c Config) CreateLoginQR(ctx context.Context, accessToken, scene string, ex return "https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket=" + url.QueryEscape(r.Ticket), nil } +// SendCustomText 发一条「客服消息」文本给指定 openid(主动推送)。 +// 约束:微信只允许在用户 48 小时内与公众号有过互动时下发(否则 45015 errcode)。 +// 适合支付回执这类「用户刚操作完」的即时通知;隔天的提醒需改用模板消息。 +// 需 access_token(走中控/直连均可)。 +func SendCustomText(ctx context.Context, accessToken, openID, content string) error { + reqBody := map[string]any{ + "touser": openID, + "msgtype": "text", + "text": map[string]any{"content": content}, + } + raw, _ := json.Marshal(reqBody) + endpoint := "https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=" + url.QueryEscape(accessToken) + body, err := httpPost(ctx, endpoint, raw) + if err != nil { + return err + } + var r struct { + ErrCode int `json:"errcode"` + ErrMsg string `json:"errmsg"` + } + if err := json.Unmarshal(body, &r); err != nil { + return fmt.Errorf("解析客服消息响应失败: %s", strings.TrimSpace(string(body))) + } + if r.ErrCode != 0 { + return fmt.Errorf("发送客服消息失败: errcode=%d errmsg=%s", r.ErrCode, r.ErrMsg) + } + return nil +} + // Event 是微信推送的事件(明文 XML)。只取登录/回复需要的字段。 type Event struct { XMLName xml.Name `xml:"xml"`