feat(billing): 微信支付配置进 DB —— admin 控制面保存即热生效
用户定的形态:配置存数据库、密钥文件放服务器磁盘(库里只存路径)。 env 降级为兜底(DB 优先 → env → 隐藏,与 tokens_per_credit 同一约定)。 - payment 包重构:Config(6 字段)+ Manager(RWMutex 热重载,学 prompt 控制面 改完即生效不重启);未启用原因人话化(未配置/缺哪些字段/初始化失败具体错)。 - APIv3 密钥入库前 AES-GCM 加密(shared/secrets,与模型 API Key 同一把 SUNDYNIX_SECRET_KEY);GET 只回 has_apiv3_key 不回显;PUT 留空=沿用旧密钥 (只写不回显语义,同模型 Key)。 - admin GET/PUT /admin/payment/wechat;业务路径全部改经 Manager.Current() 取快照(BillingPacks/下单/查单/回调)。 - admin 计费页「微信支付配置」卡片:状态徽章(已启用/未启用+原因)+六字段 +保存并热生效。 live:无配置→「未配置」;存假配置→热重载报「私钥加载失败:decode err」; 去掉 appid→「配置不全,缺: appid」;密钥留空沿用(has_apiv3_key 保持 true); psql 复核库内密文 enc:1: 前缀、不含明文子串。go/tsc/41 vitest 全绿。 Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
@@ -226,6 +226,38 @@ export async function listRedeemCodes(): Promise<RedeemCodeRow[]> {
|
||||
return d.codes ?? [];
|
||||
}
|
||||
|
||||
// ---- 微信支付配置(DB 存储、热生效;APIv3 密钥密文入库、不回显)----
|
||||
export interface WechatPayConfig {
|
||||
mchid: string;
|
||||
cert_serial: string;
|
||||
private_key_path: string;
|
||||
appid: string;
|
||||
notify_url: string;
|
||||
has_apiv3_key: boolean;
|
||||
}
|
||||
|
||||
export async function getWechatPay(): Promise<{ config: WechatPayConfig; enabled: boolean; reason: string }> {
|
||||
const res = guard(await fetch(`${ADMIN}/payment/wechat`, { headers: authHeaders() }));
|
||||
const d = (await res.json().catch(() => ({}))) as { config?: WechatPayConfig; enabled?: boolean; reason?: string; error?: string };
|
||||
if (!res.ok) throw new Error(d.error ?? `load failed: ${res.status}`);
|
||||
return { config: d.config!, enabled: !!d.enabled, reason: d.reason ?? "" };
|
||||
}
|
||||
|
||||
// saveWechatPay:apiv3_key 传空串 = 沿用已保存的密钥。返回热重载后的渠道状态。
|
||||
export async function saveWechatPay(body: {
|
||||
mchid: string;
|
||||
cert_serial: string;
|
||||
private_key_path: string;
|
||||
apiv3_key: string;
|
||||
appid: string;
|
||||
notify_url: string;
|
||||
}): Promise<{ enabled: boolean; reason: string }> {
|
||||
const res = guard(await fetch(`${ADMIN}/payment/wechat`, { method: "PUT", headers: authHeaders(true), body: JSON.stringify(body) }));
|
||||
const d = (await res.json().catch(() => ({}))) as { enabled?: boolean; reason?: string; error?: string };
|
||||
if (!res.ok) throw new Error(d.error ?? `save failed: ${res.status}`);
|
||||
return { enabled: !!d.enabled, reason: d.reason ?? "" };
|
||||
}
|
||||
|
||||
// gatewayOnline 用公开的 /healthz 探活(不受鉴权影响)。
|
||||
export async function gatewayOnline(): Promise<boolean> {
|
||||
try {
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { useEffect, useState } from "react";
|
||||
import { adminPacks, savePack, genRedeemCodes, listRedeemCodes, type CreditPack, type RedeemCodeRow } from "../api";
|
||||
import { adminPacks, savePack, genRedeemCodes, listRedeemCodes, getWechatPay, saveWechatPay, type CreditPack, type RedeemCodeRow, type WechatPayConfig } from "../api";
|
||||
|
||||
// 充值渠道(P5.1,设计见 PAYMENT_DESIGN.md):
|
||||
// - 积分包:钱→积分的第一层汇率(第二层 积分→token 在上方「计费规则」里,两层解耦)。
|
||||
@@ -14,12 +14,114 @@ export function TopupChannels() {
|
||||
<div className="space-y-4">
|
||||
<div className="flex items-center gap-2 pt-1">
|
||||
<h3 className="text-sm font-semibold text-gray-700">充值渠道</h3>
|
||||
<span className="text-[11px] text-gray-400">兑换码即刻可用;微信扫码支付(P5.2)待商户号</span>
|
||||
<span className="text-[11px] text-gray-400">兑换码即刻可用;微信扫码支付在下方配好商户号即点亮</span>
|
||||
</div>
|
||||
<div className="grid grid-cols-1 gap-4 xl:grid-cols-2">
|
||||
<RedeemBlock />
|
||||
<PacksBlock />
|
||||
</div>
|
||||
<WechatConfigBlock />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// ---- 微信支付配置:DB 存储、保存即热生效(不重启 gateway)。
|
||||
// APIv3 密钥只写不回显(密文入库,与模型 API Key 同一把密钥加密);
|
||||
// 商户证书私钥文件放服务器磁盘,这里只填路径。
|
||||
function WechatConfigBlock() {
|
||||
const empty: WechatPayConfig = { mchid: "", cert_serial: "", private_key_path: "", appid: "", notify_url: "", has_apiv3_key: false };
|
||||
const [cfg, setCfg] = useState<WechatPayConfig>(empty);
|
||||
const [apiv3, setApiv3] = useState(""); // 留空=沿用已存
|
||||
const [enabled, setEnabled] = useState(false);
|
||||
const [reason, setReason] = useState("");
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [err, setErr] = useState("");
|
||||
|
||||
useEffect(() => {
|
||||
getWechatPay()
|
||||
.then((r) => {
|
||||
setCfg(r.config);
|
||||
setEnabled(r.enabled);
|
||||
setReason(r.reason);
|
||||
})
|
||||
.catch((e) => setErr((e as Error).message));
|
||||
}, []);
|
||||
|
||||
const save = async () => {
|
||||
if (busy) return;
|
||||
setBusy(true);
|
||||
setErr("");
|
||||
try {
|
||||
const r = await saveWechatPay({
|
||||
mchid: cfg.mchid,
|
||||
cert_serial: cfg.cert_serial,
|
||||
private_key_path: cfg.private_key_path,
|
||||
apiv3_key: apiv3, // 空串=后端沿用旧密钥
|
||||
appid: cfg.appid,
|
||||
notify_url: cfg.notify_url,
|
||||
});
|
||||
setEnabled(r.enabled);
|
||||
setReason(r.reason);
|
||||
setApiv3("");
|
||||
if (apiv3) setCfg((c) => ({ ...c, has_apiv3_key: true }));
|
||||
} catch (e) {
|
||||
setErr((e as Error).message);
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
};
|
||||
|
||||
const field = (label: string, key: keyof WechatPayConfig, placeholder: string, cls = "") => (
|
||||
<label className={`text-xs text-gray-500 ${cls}`}>
|
||||
{label}
|
||||
<input
|
||||
value={String(cfg[key] ?? "")}
|
||||
onChange={(e) => setCfg((c) => ({ ...c, [key]: e.target.value }))}
|
||||
placeholder={placeholder}
|
||||
className="mt-1 block w-full rounded-lg border border-gray-200 px-2.5 py-1.5 font-mono text-sm text-gray-800 focus:border-violet-400 focus:outline-none"
|
||||
/>
|
||||
</label>
|
||||
);
|
||||
|
||||
return (
|
||||
<div className="rounded-xl border border-gray-100 bg-white p-5 shadow-sm">
|
||||
<div className="mb-3 flex items-center justify-between">
|
||||
<div className="flex items-center gap-2">
|
||||
<h4 className="text-sm font-semibold text-gray-700">微信支付配置</h4>
|
||||
{enabled ? (
|
||||
<span className="rounded bg-emerald-50 px-2 py-0.5 text-[10px] font-medium text-emerald-600">渠道已启用</span>
|
||||
) : (
|
||||
<span className="rounded bg-gray-100 px-2 py-0.5 text-[10px] text-gray-500" title={reason}>未启用{reason ? ` · ${reason}` : ""}</span>
|
||||
)}
|
||||
</div>
|
||||
<span className="text-[11px] text-gray-400">保存即热生效;私钥文件放服务器磁盘,此处只填路径</span>
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-1 gap-3 md:grid-cols-3">
|
||||
{field("商户号 (mchid)", "mchid", "190000****")}
|
||||
{field("API 证书序列号", "cert_serial", "5157F09E…")}
|
||||
{field("appid(公众号/小程序)", "appid", "wx88888888")}
|
||||
{field("商户私钥文件路径(服务器磁盘)", "private_key_path", "/etc/sundynix/wechat/apiclient_key.pem", "md:col-span-2")}
|
||||
<label className="text-xs text-gray-500">
|
||||
APIv3 密钥{cfg.has_apiv3_key && <span className="ml-1 text-emerald-600">已保存</span>}
|
||||
<input
|
||||
type="password"
|
||||
value={apiv3}
|
||||
onChange={(e) => setApiv3(e.target.value)}
|
||||
placeholder={cfg.has_apiv3_key ? "留空则沿用已保存的" : "32 字节"}
|
||||
className="mt-1 block w-full rounded-lg border border-gray-200 px-2.5 py-1.5 font-mono text-sm text-gray-800 focus:border-violet-400 focus:outline-none"
|
||||
/>
|
||||
</label>
|
||||
{field("支付回调地址(公网 https)", "notify_url", "https://api.example.com/api/v1/billing/callback/wechat", "md:col-span-3")}
|
||||
</div>
|
||||
{err && <p className="mt-2 text-xs text-rose-500">{err}</p>}
|
||||
<div className="mt-3 flex items-center gap-3">
|
||||
<button onClick={() => void save()} disabled={busy}
|
||||
className="rounded-lg bg-violet-600 px-3.5 py-1.5 text-sm text-white hover:bg-violet-700 disabled:opacity-40">
|
||||
{busy ? "保存中…" : "保存并热生效"}
|
||||
</button>
|
||||
<span className="text-[11px] text-gray-400">收不到公网回调也能到账(用户端轮询会主动查单),回调只是更快的通道。</span>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -21,7 +21,7 @@ func (h *Handler) BillingPacks(c *gin.Context) {
|
||||
return
|
||||
}
|
||||
channels := []string{store.ChannelRedeem}
|
||||
if h.wechat != nil {
|
||||
if h.pay.Current() != nil {
|
||||
channels = append(channels, store.ChannelWechat)
|
||||
}
|
||||
c.JSON(http.StatusOK, gin.H{"packs": packs, "channels": channels})
|
||||
@@ -35,7 +35,8 @@ const orderTTL = 30 * time.Minute
|
||||
// BillingCreateOrder: POST /api/v1/billing/orders {pack_id} —— 微信 Native 下单,返回 code_url。
|
||||
// 金额/积分由服务端按在售包锁定进订单行,前端只传包 id,不信任任何客户端金额。
|
||||
func (h *Handler) BillingCreateOrder(c *gin.Context) {
|
||||
if h.wechat == nil {
|
||||
wc := h.pay.Current()
|
||||
if wc == nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "微信支付未配置,请用兑换码充值"})
|
||||
return
|
||||
}
|
||||
@@ -67,7 +68,7 @@ func (h *Handler) BillingCreateOrder(c *gin.Context) {
|
||||
c.JSON(http.StatusBadGateway, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
codeURL, err := h.wechat.CreatePay(ctx, o.ID, "sundynix 积分充值 · "+pk.Name, pk.PriceFen)
|
||||
codeURL, err := wc.CreatePay(ctx, o.ID, "sundynix 积分充值 · "+pk.Name, pk.PriceFen)
|
||||
if err != nil {
|
||||
// 渠道下单失败的单直接作废,不留一堆永远付不了的 pending。
|
||||
_ = h.db.ExpireOrder(ctx, o.ID)
|
||||
@@ -92,8 +93,8 @@ func (h *Handler) BillingOrderStatus(c *gin.Context) {
|
||||
c.JSON(http.StatusNotFound, gin.H{"error": "订单不存在"})
|
||||
return
|
||||
}
|
||||
if o.Status == store.OrderPending && h.wechat != nil {
|
||||
if r, err := h.wechat.QueryOrder(ctx, o.ID); err == nil {
|
||||
if wc := h.pay.Current(); o.Status == store.OrderPending && wc != nil {
|
||||
if r, err := wc.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 {
|
||||
@@ -118,11 +119,12 @@ func (h *Handler) BillingOrderStatus(c *gin.Context) {
|
||||
// WechatCallback: POST /api/v1/billing/callback/wechat —— 微信支付回调(公开路由,验签是唯一的门)。
|
||||
// 应答契约:入账成功/重复推送都回 200 {code:SUCCESS};验签失败 4xx;处理失败 5xx 让微信重试。
|
||||
func (h *Handler) WechatCallback(c *gin.Context) {
|
||||
if h.wechat == nil {
|
||||
wc := h.pay.Current()
|
||||
if wc == nil {
|
||||
c.JSON(http.StatusServiceUnavailable, gin.H{"code": "FAIL", "message": "渠道未配置"})
|
||||
return
|
||||
}
|
||||
r, err := h.wechat.VerifyCallback(c.Request)
|
||||
r, err := wc.VerifyCallback(c.Request)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusUnauthorized, gin.H{"code": "FAIL", "message": "验签失败"})
|
||||
return
|
||||
|
||||
@@ -0,0 +1,108 @@
|
||||
package handler
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"strings"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/sundynix/sundynix-gateway/internal/payment"
|
||||
"github.com/sundynix/sundynix-shared/secrets"
|
||||
)
|
||||
|
||||
// 微信支付配置控制面:配置进 DB(sundynix_setting)、改完热生效不重启;
|
||||
// APIv3 密钥入库前 AES-GCM 加密(与模型 API Key 同一把 SUNDYNIX_SECRET_KEY),
|
||||
// 私钥文件留在服务器磁盘,库里只存路径。env 仍作兜底(DB 优先 → env → 隐藏)。
|
||||
|
||||
// SettingWechatPay 是 settings KV 里的键,值为 payment.Config 的 JSON(apiv3_key 为密文)。
|
||||
const SettingWechatPay = "payment_wechat"
|
||||
|
||||
// loadWechatConfig 读支付配置:DB 优先(解密 apiv3),空则回退 env。
|
||||
func (h *Handler) loadWechatConfig(ctx context.Context) payment.Config {
|
||||
raw := h.db.GetSetting(ctx, SettingWechatPay)
|
||||
if raw == "" {
|
||||
return payment.ConfigFromEnv()
|
||||
}
|
||||
var c payment.Config
|
||||
if err := json.Unmarshal([]byte(raw), &c); err != nil {
|
||||
return payment.ConfigFromEnv()
|
||||
}
|
||||
if c.APIv3Key != "" {
|
||||
if plain, err := secrets.Decrypt(c.APIv3Key); err == nil {
|
||||
c.APIv3Key = plain
|
||||
}
|
||||
}
|
||||
return c
|
||||
}
|
||||
|
||||
// InitWechat 启动时装配微信渠道(DB 优先 → env)。失败只降级隐藏,不阻断启动。
|
||||
func (h *Handler) InitWechat(ctx context.Context) {
|
||||
_ = h.pay.Reload(ctx, h.loadWechatConfig(ctx))
|
||||
}
|
||||
|
||||
// AdminGetWechatPay: GET /api/v1/admin/payment/wechat —— 当前配置(密钥不回显)+ 渠道状态。
|
||||
func (h *Handler) AdminGetWechatPay(c *gin.Context) {
|
||||
cfg := h.loadWechatConfig(c.Request.Context())
|
||||
enabled, reason := h.pay.Status()
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
"config": gin.H{
|
||||
"mchid": cfg.MchID,
|
||||
"cert_serial": cfg.CertSerial,
|
||||
"private_key_path": cfg.PrivateKeyPath,
|
||||
"appid": cfg.AppID,
|
||||
"notify_url": cfg.NotifyURL,
|
||||
"has_apiv3_key": cfg.APIv3Key != "", // 密钥只报有无,明文永不回显
|
||||
},
|
||||
"enabled": enabled,
|
||||
"reason": reason,
|
||||
})
|
||||
}
|
||||
|
||||
// AdminSaveWechatPay: PUT /api/v1/admin/payment/wechat —— 保存配置并热重载渠道。
|
||||
// apiv3_key 留空 = 沿用已存的(只写不回显的编辑语义,同模型 Key)。
|
||||
func (h *Handler) AdminSaveWechatPay(c *gin.Context) {
|
||||
var b struct {
|
||||
MchID string `json:"mchid"`
|
||||
CertSerial string `json:"cert_serial"`
|
||||
PrivateKeyPath string `json:"private_key_path"`
|
||||
APIv3Key string `json:"apiv3_key"`
|
||||
AppID string `json:"appid"`
|
||||
NotifyURL string `json:"notify_url"`
|
||||
}
|
||||
if err := c.ShouldBindJSON(&b); err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "参数错误"})
|
||||
return
|
||||
}
|
||||
ctx := c.Request.Context()
|
||||
apiv3 := strings.TrimSpace(b.APIv3Key)
|
||||
if apiv3 == "" {
|
||||
apiv3 = h.loadWechatConfig(ctx).APIv3Key // 留空沿用旧密钥(此处为明文,稍后统一加密入库)
|
||||
}
|
||||
cfg := payment.Config{
|
||||
MchID: strings.TrimSpace(b.MchID),
|
||||
CertSerial: strings.TrimSpace(b.CertSerial),
|
||||
PrivateKeyPath: strings.TrimSpace(b.PrivateKeyPath),
|
||||
APIv3Key: apiv3,
|
||||
AppID: strings.TrimSpace(b.AppID),
|
||||
NotifyURL: strings.TrimSpace(b.NotifyURL),
|
||||
}
|
||||
stored := cfg
|
||||
if stored.APIv3Key != "" {
|
||||
enc, err := secrets.Encrypt(stored.APIv3Key)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": "密钥加密失败: " + err.Error()})
|
||||
return
|
||||
}
|
||||
stored.APIv3Key = enc
|
||||
}
|
||||
raw, _ := json.Marshal(stored)
|
||||
if err := h.db.SetSetting(ctx, SettingWechatPay, string(raw)); err != nil {
|
||||
c.JSON(http.StatusBadGateway, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
// 热重载:配置有毛病只会让渠道隐藏并给出原因,不影响其它功能。
|
||||
_ = h.pay.Reload(ctx, cfg)
|
||||
enabled, reason := h.pay.Status()
|
||||
c.JSON(http.StatusOK, gin.H{"status": "ok", "enabled": enabled, "reason": reason})
|
||||
}
|
||||
@@ -24,21 +24,15 @@ import (
|
||||
)
|
||||
|
||||
type Handler struct {
|
||||
db *store.Postgres
|
||||
cache *store.Redis
|
||||
bus *nats.Bus
|
||||
blob *blob.Store
|
||||
wechat *payment.Wechat // 微信支付渠道;nil=未配置(渠道隐藏)
|
||||
db *store.Postgres
|
||||
cache *store.Redis
|
||||
bus *nats.Bus
|
||||
blob *blob.Store
|
||||
pay *payment.Manager // 微信支付渠道管理器(DB 配置热重载;Current()==nil 即渠道隐藏)
|
||||
}
|
||||
|
||||
func New(db *store.Postgres, cache *store.Redis, bus *nats.Bus, blob *blob.Store) *Handler {
|
||||
return &Handler{db: db, cache: cache, bus: bus, blob: blob}
|
||||
}
|
||||
|
||||
// WithWechat 注入微信支付渠道(nil 安全:保持隐藏)。
|
||||
func (h *Handler) WithWechat(w *payment.Wechat) *Handler {
|
||||
h.wechat = w
|
||||
return h
|
||||
return &Handler{db: db, cache: cache, bus: bus, blob: blob, pay: payment.NewManager()}
|
||||
}
|
||||
|
||||
// preflight 是「会烧钱的执行」提交前的统一关卡:当日 token 预算 → 计费租户 → 积分硬拦截。
|
||||
|
||||
@@ -0,0 +1,112 @@
|
||||
package payment
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"log"
|
||||
"os"
|
||||
"strings"
|
||||
"sync"
|
||||
)
|
||||
|
||||
// Config 微信支付渠道配置。来源两级:DB 设置(admin 控制面,热生效)优先,env 兜底
|
||||
// ——与 TokensPerCredit 的「DB 优先 → env → 默认」同一约定。
|
||||
// APIv3Key 在库里是 AES-GCM 密文(与模型 API Key 同一把 SUNDYNIX_SECRET_KEY),
|
||||
// 这里拿到的是解密后的明文;PrivateKeyPath 只是服务器磁盘路径,私钥文件本身不进库。
|
||||
type Config struct {
|
||||
MchID string `json:"mchid"`
|
||||
CertSerial string `json:"cert_serial"`
|
||||
PrivateKeyPath string `json:"private_key_path"`
|
||||
APIv3Key string `json:"apiv3_key"`
|
||||
AppID string `json:"appid"`
|
||||
NotifyURL string `json:"notify_url"`
|
||||
}
|
||||
|
||||
// Empty 完全未配置(一个字段都没填)。
|
||||
func (c Config) Empty() bool {
|
||||
return c.MchID == "" && c.CertSerial == "" && c.PrivateKeyPath == "" &&
|
||||
c.APIv3Key == "" && c.AppID == "" && c.NotifyURL == ""
|
||||
}
|
||||
|
||||
// missing 返回缺失字段名(配置不全时给 admin 一句能看懂的原因)。
|
||||
func (c Config) missing() []string {
|
||||
var out []string
|
||||
for _, f := range []struct{ k, v string }{
|
||||
{"mchid", c.MchID}, {"cert_serial", c.CertSerial}, {"private_key_path", c.PrivateKeyPath},
|
||||
{"apiv3_key", c.APIv3Key}, {"appid", c.AppID}, {"notify_url", c.NotifyURL},
|
||||
} {
|
||||
if strings.TrimSpace(f.v) == "" {
|
||||
out = append(out, f.k)
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// ConfigFromEnv 从环境变量读配置(DB 未配置时的兜底,兼容 P5.2 的纯 env 用法)。
|
||||
func ConfigFromEnv() Config {
|
||||
return Config{
|
||||
MchID: os.Getenv("WECHAT_MCHID"),
|
||||
CertSerial: os.Getenv("WECHAT_MCH_CERT_SERIAL"),
|
||||
PrivateKeyPath: os.Getenv("WECHAT_MCH_PRIVATE_KEY"),
|
||||
APIv3Key: os.Getenv("WECHAT_APIV3_KEY"),
|
||||
AppID: os.Getenv("WECHAT_APPID"),
|
||||
NotifyURL: os.Getenv("WECHAT_NOTIFY_URL"),
|
||||
}
|
||||
}
|
||||
|
||||
// Manager 持有当前微信渠道实例,支持 admin 改配置后热重载(学 prompt 控制面:改完即生效,
|
||||
// 不重启 gateway)。所有业务路径经 Current() 取用——nil 即渠道隐藏。
|
||||
type Manager struct {
|
||||
mu sync.RWMutex
|
||||
w *Wechat
|
||||
reason string // 未启用原因(给 admin 状态面看)
|
||||
}
|
||||
|
||||
func NewManager() *Manager {
|
||||
return &Manager{reason: "未配置"}
|
||||
}
|
||||
|
||||
// Reload 按给定配置重建渠道实例。失败只降级为隐藏并记录原因,绝不 panic/拖垮服务。
|
||||
func (m *Manager) Reload(ctx context.Context, c Config) error {
|
||||
w, reason, err := build(ctx, c)
|
||||
m.mu.Lock()
|
||||
m.w = w
|
||||
m.reason = reason
|
||||
m.mu.Unlock()
|
||||
if w != nil {
|
||||
log.Printf("[payment] 微信支付 Native 渠道已启用 (mchid=%s)", c.MchID)
|
||||
} else if !c.Empty() {
|
||||
log.Printf("[payment] 微信支付渠道未启用: %s", reason)
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
// Current 当前渠道实例;nil = 未配置/配置失败(渠道隐藏)。
|
||||
func (m *Manager) Current() *Wechat {
|
||||
m.mu.RLock()
|
||||
defer m.mu.RUnlock()
|
||||
return m.w
|
||||
}
|
||||
|
||||
// Status 给 admin 状态面:是否启用 + 未启用原因。
|
||||
func (m *Manager) Status() (bool, string) {
|
||||
m.mu.RLock()
|
||||
defer m.mu.RUnlock()
|
||||
return m.w != nil, m.reason
|
||||
}
|
||||
|
||||
// build 装配渠道实例;返回 (实例, 未启用原因, 错误)。配置为空不算错。
|
||||
func build(ctx context.Context, c Config) (*Wechat, string, error) {
|
||||
if c.Empty() {
|
||||
return nil, "未配置", nil
|
||||
}
|
||||
if miss := c.missing(); len(miss) > 0 {
|
||||
reason := "配置不全,缺: " + strings.Join(miss, ", ")
|
||||
return nil, reason, errors.New(reason)
|
||||
}
|
||||
w, err := New(ctx, c)
|
||||
if err != nil {
|
||||
return nil, "初始化失败: " + err.Error(), err
|
||||
}
|
||||
return w, "", nil
|
||||
}
|
||||
@@ -7,9 +7,7 @@ import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"log"
|
||||
"net/http"
|
||||
"os"
|
||||
|
||||
"github.com/wechatpay-apiv3/wechatpay-go/core"
|
||||
"github.com/wechatpay-apiv3/wechatpay-go/core/auth/verifiers"
|
||||
@@ -21,16 +19,7 @@ import (
|
||||
"github.com/wechatpay-apiv3/wechatpay-go/utils"
|
||||
)
|
||||
|
||||
// Wechat 微信支付 Native(扫码)适配器。凭据一律 env 注入:
|
||||
//
|
||||
// WECHAT_MCHID 商户号
|
||||
// WECHAT_MCH_CERT_SERIAL 商户 API 证书序列号
|
||||
// WECHAT_MCH_PRIVATE_KEY 商户 API 私钥文件路径(apiclient_key.pem)
|
||||
// WECHAT_APIV3_KEY APIv3 密钥(32 字节)
|
||||
// WECHAT_APPID 关联的公众号/小程序/APP 的 appid
|
||||
// WECHAT_NOTIFY_URL 支付回调地址(须公网 https,如 https://api.example.com/api/v1/billing/callback/wechat)
|
||||
//
|
||||
// 任一缺失 → NewWechatFromEnv 返回 nil,渠道自动隐藏(半配置状态不许把下单路由搞出 5xx)。
|
||||
// Wechat 微信支付 Native(扫码)适配器。配置来源见 Config(DB 优先、env 兜底,由 Manager 装配)。
|
||||
// 本地开发收不到公网回调没关系:前端轮询的 GET /billing/orders/:id 会主动查单确认,
|
||||
// 回调只是生产环境更快的到账通道,两条路都汇入同一个幂等入账闸。
|
||||
type Wechat struct {
|
||||
@@ -42,36 +31,20 @@ type Wechat struct {
|
||||
svc native.NativeApiService
|
||||
}
|
||||
|
||||
// NewWechatFromEnv 依据环境变量装配微信渠道;未配置(或配置不全/私钥读不了)返回 nil。
|
||||
func NewWechatFromEnv(ctx context.Context) *Wechat {
|
||||
mchID := os.Getenv("WECHAT_MCHID")
|
||||
serial := os.Getenv("WECHAT_MCH_CERT_SERIAL")
|
||||
keyPath := os.Getenv("WECHAT_MCH_PRIVATE_KEY")
|
||||
apiv3 := os.Getenv("WECHAT_APIV3_KEY")
|
||||
appID := os.Getenv("WECHAT_APPID")
|
||||
notifyURL := os.Getenv("WECHAT_NOTIFY_URL")
|
||||
if mchID == "" && serial == "" && keyPath == "" && apiv3 == "" {
|
||||
return nil // 完全未配置:静默(大多数开发环境)
|
||||
}
|
||||
if mchID == "" || serial == "" || keyPath == "" || apiv3 == "" || appID == "" || notifyURL == "" {
|
||||
log.Printf("[payment] 微信支付配置不全(MCHID/CERT_SERIAL/PRIVATE_KEY/APIV3_KEY/APPID/NOTIFY_URL 缺一不可),渠道保持隐藏")
|
||||
return nil
|
||||
}
|
||||
priv, err := utils.LoadPrivateKeyWithPath(keyPath)
|
||||
// New 按完整配置装配微信渠道(私钥从磁盘路径加载;调用方保证字段齐全)。
|
||||
func New(ctx context.Context, c Config) (*Wechat, error) {
|
||||
priv, err := utils.LoadPrivateKeyWithPath(c.PrivateKeyPath)
|
||||
if err != nil {
|
||||
log.Printf("[payment] 微信商户私钥加载失败(%s),渠道保持隐藏: %v", keyPath, err)
|
||||
return nil
|
||||
return nil, fmt.Errorf("商户私钥加载失败(%s): %w", c.PrivateKeyPath, err)
|
||||
}
|
||||
client, err := core.NewClient(ctx, option.WithWechatPayAutoAuthCipher(mchID, serial, priv, apiv3))
|
||||
client, err := core.NewClient(ctx, option.WithWechatPayAutoAuthCipher(c.MchID, c.CertSerial, priv, c.APIv3Key))
|
||||
if err != nil {
|
||||
log.Printf("[payment] 微信支付客户端初始化失败,渠道保持隐藏: %v", err)
|
||||
return nil
|
||||
return nil, fmt.Errorf("客户端初始化失败: %w", err)
|
||||
}
|
||||
log.Printf("[payment] 微信支付 Native 渠道已启用 (mchid=%s)", mchID)
|
||||
return &Wechat{
|
||||
mchID: mchID, appID: appID, notifyURL: notifyURL, apiv3Key: apiv3,
|
||||
mchID: c.MchID, appID: c.AppID, notifyURL: c.NotifyURL, apiv3Key: c.APIv3Key,
|
||||
client: client, svc: native.NativeApiService{Client: client},
|
||||
}
|
||||
}, nil
|
||||
}
|
||||
|
||||
// CreatePay Native 下单:返回 code_url(前端渲染成二维码)。金额取订单锁定值。
|
||||
|
||||
@@ -15,7 +15,6 @@ import (
|
||||
"github.com/sundynix/sundynix-gateway/internal/handler"
|
||||
"github.com/sundynix/sundynix-gateway/internal/middleware"
|
||||
"github.com/sundynix/sundynix-gateway/internal/nats"
|
||||
"github.com/sundynix/sundynix-gateway/internal/payment"
|
||||
"github.com/sundynix/sundynix-gateway/internal/store"
|
||||
)
|
||||
|
||||
@@ -33,8 +32,9 @@ func New(db *store.Postgres, cache *store.Redis, bus *nats.Bus, blobStore *blob.
|
||||
r.Use(middleware.RateLimit(cache)) // 已认证按用户限流,否则按 IP(企业网多人共享 IP 不再互相拖累)
|
||||
r.Use(middleware.Guardrail(db)) // Harness: Input Guardrail(命中落库 guardrail_event)
|
||||
|
||||
// 微信支付渠道按 env 装配;未配置返回 nil → 渠道自动隐藏,下单路由 400 引导用兑换码。
|
||||
h := handler.New(db, cache, bus, blobStore).WithWechat(payment.NewWechatFromEnv(context.Background()))
|
||||
h := handler.New(db, cache, bus, blobStore)
|
||||
// 微信支付渠道装配:DB 配置优先(admin 控制面热重载)→ env 兜底 → 隐藏。失败不阻断启动。
|
||||
h.InitWechat(context.Background())
|
||||
|
||||
// 可观测性根端点:Prometheus 抓取 + k8s 存活/就绪探针(不挂业务中间件鉴权)。
|
||||
r.GET("/metrics", gin.WrapH(promhttp.Handler()))
|
||||
@@ -133,11 +133,13 @@ func New(db *store.Postgres, cache *store.Redis, bus *nats.Bus, blobStore *blob.
|
||||
admin.GET("/billing-config", h.BillingConfig) // 全局计费规则(token→积分汇率 + 硬拦截开关)
|
||||
admin.PUT("/billing-config", h.SaveBillingConfig)
|
||||
admin.POST("/credits/grant", h.GrantCredits) // 给租户充值/发放积分
|
||||
// 支付配置面(P5.1):兑换码生成/查看 + 积分包配置
|
||||
// 支付配置面(P5.1/P5.2):兑换码生成/查看 + 积分包配置 + 微信支付配置(DB 热生效)
|
||||
admin.POST("/redeem-codes", h.AdminGenRedeemCodes)
|
||||
admin.GET("/redeem-codes", h.AdminRedeemCodes)
|
||||
admin.GET("/packs", h.AdminPacks)
|
||||
admin.PUT("/packs", h.AdminSavePack)
|
||||
admin.GET("/payment/wechat", h.AdminGetWechatPay)
|
||||
admin.PUT("/payment/wechat", h.AdminSaveWechatPay)
|
||||
// 多租户成员管理(平台运维口径)
|
||||
admin.GET("/tenants", h.AdminTenants) // 租户目录(成员数+余额)
|
||||
admin.POST("/tenants", h.AdminCreateTenant) // 新建租户(可选指定 owner)
|
||||
|
||||
Reference in New Issue
Block a user