package httpapi import ( "bytes" "context" "crypto/rand" "crypto/sha256" "database/sql" "encoding/hex" "encoding/json" "errors" "fmt" "io" "log/slog" "net/http" "strconv" "time" "github.com/gin-gonic/gin" "license-platform/backend/internal/payments" ) func randomPaymentToken(n int) (string, error) { b := make([]byte, n) _, err := rand.Read(b) return hex.EncodeToString(b), err } // Providers authenticate official channel messages; no client claim can grant a license. func (a *BusinessAPI) paymentNotify(c *gin.Context) { channel := c.Param("channel") c.Request.Body = http.MaxBytesReader(c.Writer, c.Request.Body, 1<<20) body, err := io.ReadAll(c.Request.Body) if err != nil { apiError(c, 400, "invalid_notification", "支付通知无效") return } versions := []sql.NullInt64{} if a.paymentProviders[channel] != nil { versions = append(versions, sql.NullInt64{}) } if a.db != nil { rows, e := a.db.QueryContext(c.Request.Context(), "SELECT DISTINCT provider_config_version FROM payment_orders WHERE channel=? AND provider_config_version IS NOT NULL", channel) if e != nil { apiError(c, 503, "configuration_unavailable", "支付配置不可用") return } for rows.Next() { var v sql.NullInt64 if e = rows.Scan(&v); e != nil { break } versions = append(versions, v) } rowErr := rows.Err() rows.Close() if e != nil || rowErr != nil { apiError(c, 503, "configuration_unavailable", "支付配置不可用") return } } if len(versions) == 0 { apiError(c, 503, "channel_unavailable", "支付渠道未启用") return } verified := false for _, version := range versions { provider, e := a.providerForPaymentVersion(c.Request.Context(), channel, version) if e != nil { continue } request := c.Request.Clone(c.Request.Context()) request.Body = io.NopCloser(bytes.NewReader(body)) request.PostForm = nil request.Form = nil notification, e := provider.Verify(request) if e != nil { continue } if a.db == nil { continue } var bound sql.NullInt64 if e = a.db.QueryRowContext(c.Request.Context(), "SELECT provider_config_version FROM payment_orders WHERE channel=? AND merchant_order_no=?", channel, notification.MerchantOrderNo).Scan(&bound); e != nil || bound != version { continue } if notification.Paid { if e = a.applyPayment(c.Request.Context(), channel, notification, version); e != nil { apiError(c, 500, "payment_processing_failed", "支付确认处理中,请渠道重试") return } } verified = true break } if !verified { apiError(c, 400, "invalid_notification", "支付通知验签失败") return } if channel == "alipay" { c.String(200, "success") } else { c.JSON(200, gin.H{"code": "SUCCESS", "message": "成功"}) } } func (a *BusinessAPI) createOnlinePayment(c *gin.Context) { key, ok := parseOperationKey(c) if !ok { return } for _, r := range key { if r < 33 || r > 126 { apiError(c, 400, "invalid_idempotency_key", "幂等键仅允许可见ASCII字符") return } } id, err := strconv.ParseUint(c.Param("id"), 10, 64) if err != nil || id == 0 { apiError(c, 400, "invalid_request", "订单ID无效") return } var in struct { Channel string `json:"channel"` LicenseDays int `json:"license_days"` } c.Request.Body = http.MaxBytesReader(c.Writer, c.Request.Body, 4096) if c.ShouldBindJSON(&in) != nil || in.LicenseDays < 1 || in.LicenseDays > 3650 || !time.Now().UTC().AddDate(0, 0, in.LicenseDays).Before(time.Date(2038, 1, 19, 3, 14, 7, 0, time.UTC)) { apiError(c, 400, "invalid_request", "授权天数须为1至3650") return } if len(payments.RequiredSettings(in.Channel)) == 0 { apiError(c, 503, "channel_unavailable", "支付渠道未启用") return } payload, _ := json.Marshal(in) fingerprint := sha256.Sum256(append([]byte(fmt.Sprint(id)+":"), payload...)) tx, err := a.db.BeginTx(c.Request.Context(), nil) if err != nil { apiError(c, 500, "internal_error", "下单失败") return } defer tx.Rollback() actor := c.MustGet("admin_id") var locked uint64 if err = tx.QueryRowContext(c.Request.Context(), "SELECT id FROM admins WHERE id=? AND active=1 AND role='admin' FOR UPDATE", actor).Scan(&locked); err != nil { apiError(c, 403, "forbidden", "无权操作") return } var oldFP, oldResponse []byte err = tx.QueryRowContext(c.Request.Context(), "SELECT request_fingerprint,response FROM order_operations WHERE actor_admin_id=? AND operation='online-payment' AND idempotency_key=?", actor, key).Scan(&oldFP, &oldResponse) if err == nil { if !bytesEqual(oldFP, fingerprint[:]) { apiError(c, 409, "idempotency_conflict", "幂等键请求冲突") return } } else if !errors.Is(err, sql.ErrNoRows) { apiError(c, 500, "internal_error", "下单失败") return } var amount uint64 var state, currency, title string if err = tx.QueryRowContext(c.Request.Context(), "SELECT o.amount_cents,o.status,o.currency,p.name FROM offline_orders o JOIN products p ON p.id=o.product_id WHERE o.id=? FOR UPDATE", id).Scan(&amount, &state, ¤cy, &title); err != nil { apiError(c, 404, "not_found", "订单不存在") return } var merchant, token, channel, paymentState string var code sql.NullString var version sql.NullInt64 var provider payments.Provider var days int var expires time.Time err = tx.QueryRowContext(c.Request.Context(), "SELECT merchant_order_no,checkout_token,channel,status,code_url,license_days,expires_at,provider_config_version FROM payment_orders WHERE order_id=?", id).Scan(&merchant, &token, &channel, &paymentState, &code, &days, &expires, &version) if errors.Is(err, sql.ErrNoRows) { // Serialize new orders with publication: a disable cannot race past this check. if err = tx.QueryRowContext(c.Request.Context(), "SELECT active_version FROM payment_channel_configs WHERE channel=? FOR UPDATE", in.Channel).Scan(&version); err != nil { apiError(c, 503, "configuration_unavailable", "配置不可用") return } if version.Valid { var encrypted []byte var enabled bool e := tx.QueryRowContext(c.Request.Context(), "SELECT config_encrypted,enabled FROM payment_channel_config_versions WHERE channel=? AND version=?", in.Channel, version.Int64).Scan(&encrypted, &enabled) var config payments.Config if e == nil { config, e = decryptPaymentConfig(a.paymentConfigEncryptionKey, in.Channel, version.Int64, encrypted) } if e != nil || !enabled { apiError(c, 503, "channel_unavailable", "支付渠道未启用") return } provider, err = payments.NewProvider(in.Channel, config) } else { if len(a.paymentConfigEncryptionKey) != 32 { apiError(c, 409, "encryption_key_unavailable", "尚未配置支付配置加密密钥") return } config := a.environmentPaymentConfig(in.Channel) provider, err = payments.NewProvider(in.Channel, config) if err != nil || a.paymentProviders[in.Channel] == nil { apiError(c, 503, "channel_unavailable", "支付渠道未启用") return } version = sql.NullInt64{Int64: 1, Valid: true} encrypted, e := encryptPaymentConfig(a.paymentConfigEncryptionKey, in.Channel, version.Int64, config) if e == nil { _, e = tx.ExecContext(c.Request.Context(), "INSERT INTO payment_channel_config_versions(channel,version,enabled,config_encrypted,created_by) VALUES(?,?,1,?,?)", in.Channel, version.Int64, encrypted, actor) } if e == nil { _, e = tx.ExecContext(c.Request.Context(), "UPDATE payment_channel_configs SET active_version=? WHERE channel=?", version.Int64, in.Channel) } if e == nil { details, _ := json.Marshal(gin.H{"version": version.Int64}) _, e = tx.ExecContext(c.Request.Context(), "INSERT INTO audit_events(actor_admin_id,action,resource_type,resource_id,details) VALUES(?,'payment.channel_config_snapshotted','payment_channel',?,?)", actor, version.Int64, details) } if e != nil { apiError(c, 503, "configuration_unavailable", "配置快照保存失败") return } } if err != nil || provider == nil { apiError(c, 503, "channel_unavailable", "支付渠道未启用") return } if state != "pending_payment" || currency != "CNY" || amount == 0 || amount > 100000000000 { apiError(c, 409, "invalid_state", "订单不可在线付款") return } merchant, err = randomPaymentToken(16) if err == nil { token, err = randomPaymentToken(32) } if err != nil { apiError(c, 500, "internal_error", "下单失败") return } expires = time.Now().UTC().Add(30 * time.Minute) paymentState = "created" _, err = tx.ExecContext(c.Request.Context(), "INSERT INTO payment_orders(order_id,merchant_order_no,channel,amount_cents,currency,license_days,checkout_token,expires_at,provider_config_version) VALUES(?,?,?,?,?,?,?,?,?)", id, merchant, in.Channel, amount, currency, in.LicenseDays, token, expires, version) if err == nil { _, err = tx.ExecContext(c.Request.Context(), "UPDATE offline_orders SET payment_channel=?,payment_expires_at=? WHERE id=?", in.Channel, expires, id) } } else if err == nil && (channel != in.Channel || days != in.LicenseDays) { apiError(c, 409, "payment_conflict", "订单已有不同渠道或期限的支付单") return } if err != nil { apiError(c, 500, "internal_error", "支付单保存失败") return } response, _ := json.Marshal(gin.H{"merchant_order_no": merchant}) if oldResponse == nil { _, err = tx.ExecContext(c.Request.Context(), "INSERT INTO order_operations(order_id,actor_admin_id,operation,idempotency_key,request_fingerprint,response) VALUES(?,?,'online-payment',?,?,?)", id, actor, key, fingerprint[:], response) } if err == nil && oldResponse == nil { details, _ := json.Marshal(gin.H{"channel": in.Channel, "license_days": in.LicenseDays, "merchant_order_no": merchant}) _, err = tx.ExecContext(c.Request.Context(), "INSERT INTO audit_events(actor_admin_id,action,resource_type,resource_id,details) VALUES(?,'payment.created','order',?,?)", actor, id, details) } if err != nil || tx.Commit() != nil { apiError(c, 500, "internal_error", "支付单提交失败") return } if !code.Valid && paymentState == "created" { if time.Now().After(expires) { apiError(c, 409, "payment_expired", "支付单已过期,请关闭渠道订单后人工核查") return } if provider == nil { provider, err = a.providerForPaymentVersion(c.Request.Context(), in.Channel, version) if err != nil { apiError(c, 503, "channel_unavailable", "历史支付配置不可用") return } } url, e := provider.Create(c.Request.Context(), merchant, int64(amount), title) if e != nil { apiError(c, 502, "channel_error", "渠道下单未完成,请使用相同参数和幂等键重试") return } if url == "" { apiError(c, 502, "channel_error", "渠道未返回付款二维码") return } if _, err = a.db.ExecContext(c.Request.Context(), "UPDATE payment_orders SET code_url=? WHERE merchant_order_no=? AND status='created'", url, merchant); err != nil { apiError(c, 500, "internal_error", "二维码保存失败,请重试") return } code = sql.NullString{String: url, Valid: true} } c.Header("Cache-Control", "no-store") c.JSON(200, gin.H{"data": gin.H{"merchant_order_no": merchant, "checkout_token": token, "checkout_url": "/checkout#token=" + token, "code_url": code.String, "status": paymentState}}) } func (a *BusinessAPI) paymentCheckout(c *gin.Context) { c.Header("Cache-Control", "no-store") c.Header("Cache-Control", "private, no-store") c.Request.Body = http.MaxBytesReader(c.Writer, c.Request.Body, 4096) var in struct { Token string `json:"token"` } if c.ShouldBindJSON(&in) != nil || len(in.Token) != 64 { apiError(c, 400, "invalid_request", "付款凭证无效") return } if b, e := hex.DecodeString(in.Token); e != nil || len(b) != 32 { apiError(c, 400, "invalid_request", "付款凭证无效") return } var merchant, channel, status, orderState, currency string var amount uint64 var code sql.NullString var license sql.NullInt64 var version sql.NullInt64 var expires time.Time err := a.db.QueryRowContext(c.Request.Context(), "SELECT p.merchant_order_no,p.channel,p.status,o.status,p.currency,p.amount_cents,p.code_url,o.issued_license_id,p.expires_at,p.provider_config_version FROM payment_orders p JOIN offline_orders o ON o.id=p.order_id WHERE p.checkout_token=?", in.Token).Scan(&merchant, &channel, &status, &orderState, ¤cy, &amount, &code, &license, &expires, &version) if err != nil { apiError(c, 404, "not_found", "付款链接不存在") return } if status != "paid" { claim, e := a.db.ExecContext(c.Request.Context(), "UPDATE payment_orders SET last_queried_at=? WHERE merchant_order_no=? AND (last_queried_at IS NULL OR last_queried_at 0 { expectedVersion = verifiedVersions[0] } if !n.Paid || n.AmountCents <= 0 || n.Currency != "CNY" || n.TradeNo == "" || len(n.TradeNo) > 128 || n.EventID == "" || len(n.EventID) > 190 { return errors.New("invalid payment") } // Resolve without locking, then use the same order-first lock as manual issue. var orderID uint64 if err := a.db.QueryRowContext(ctx, "SELECT order_id FROM payment_orders WHERE merchant_order_no=? AND channel=?", n.MerchantOrderNo, channel).Scan(&orderID); err != nil { return err } tx, err := a.db.BeginTx(ctx, nil) if err != nil { return err } defer tx.Rollback() var owner, product, actor uint64 var state, currency string var orderAmount uint64 var issued sql.NullInt64 if err = tx.QueryRowContext(ctx, "SELECT customer_id,product_id,created_by,status,currency,amount_cents,issued_license_id FROM offline_orders WHERE id=? FOR UPDATE", orderID).Scan(&owner, &product, &actor, &state, ¤cy, &orderAmount, &issued); err != nil { return err } var paymentID, amount uint64 var pstate string var days int var trade sql.NullString var boundVersion sql.NullInt64 if err = tx.QueryRowContext(ctx, "SELECT id,amount_cents,status,license_days,channel_trade_no,provider_config_version FROM payment_orders WHERE order_id=? AND merchant_order_no=? AND channel=? FOR UPDATE", orderID, n.MerchantOrderNo, channel).Scan(&paymentID, &amount, &pstate, &days, &trade, &boundVersion); err != nil { return err } if boundVersion != expectedVersion { return errors.New("payment config version mismatch") } if amount != uint64(n.AmountCents) || orderAmount != amount || currency != n.Currency { return errors.New("amount mismatch") } if pstate == "paid" && (!trade.Valid || trade.String != n.TradeNo) { return errors.New("trade conflict") } if pstate != "paid" && state != "pending_payment" { return errors.New("order state conflict") } fingerprint, _ := json.Marshal(n) digest := sha256.Sum256(fingerprint) var existingMerchant, existingTrade string err = tx.QueryRowContext(ctx, "SELECT merchant_order_no,channel_trade_no FROM payment_notifications WHERE channel=? AND event_id=?", channel, n.EventID).Scan(&existingMerchant, &existingTrade) if err == nil { if existingMerchant != n.MerchantOrderNo || existingTrade != n.TradeNo { return errors.New("event conflict") } } else if errors.Is(err, sql.ErrNoRows) { _, err = tx.ExecContext(ctx, "INSERT INTO payment_notifications(channel,event_id,merchant_order_no,channel_trade_no,payload_digest) VALUES(?,?,?,?,?)", channel, n.EventID, n.MerchantOrderNo, n.TradeNo, digest[:]) } if err != nil { return err } if pstate == "paid" { if _, err = tx.ExecContext(ctx, "UPDATE payment_notifications SET processed=1,processed_at=? WHERE channel=? AND event_id=?", time.Now().UTC(), channel, n.EventID); err != nil { return err } return tx.Commit() } now := time.Now().UTC() expires := now.AddDate(0, 0, days) if days < 1 || days > 3650 || !expires.Before(time.Date(2038, 1, 19, 3, 14, 7, 0, time.UTC)) { return errors.New("invalid license duration") } var customerState string var productActive bool if err = tx.QueryRowContext(ctx, "SELECT status FROM customers WHERE id=? FOR UPDATE", owner).Scan(&customerState); err != nil { return err } if err = tx.QueryRowContext(ctx, "SELECT active FROM products WHERE id=? FOR UPDATE", product).Scan(&productActive); err != nil { return err } if customerState != "active" || !productActive { return errors.New("inactive master data") } // Payment confirmation and issuance commit together; provider retries recover failure. raw, err := randomPaymentToken(16) if err != nil { return err } grantKey := fmt.Sprintf("online-order-%d", orderID) res, err := tx.ExecContext(ctx, "INSERT INTO licenses(license_key,customer_id,product_id,status,starts_at,expires_at,idempotency_key,issued_by) VALUES(?,?,?,'active',?,?,?,?)", raw, owner, product, now, expires, grantKey, actor) if err != nil { return err } licenseID, err := res.LastInsertId() if err != nil { return err } if _, err = tx.ExecContext(ctx, "UPDATE payment_orders SET status='paid',channel_trade_no=?,paid_at=?,last_error=NULL WHERE id=?", n.TradeNo, now, paymentID); err != nil { return err } if _, err = tx.ExecContext(ctx, "UPDATE offline_orders SET status='issued',payment_status='paid',payment_channel=?,payment_reference=?,paid_at=?,issued_license_id=? WHERE id=?", channel, n.TradeNo, now, licenseID, orderID); err != nil { return err } if _, err = tx.ExecContext(ctx, "INSERT INTO authorization_grant_logs(order_id,license_id,idempotency_key,status) VALUES(?,?,?,'succeeded')", orderID, licenseID, grantKey); err != nil { return err } if _, err = tx.ExecContext(ctx, "UPDATE payment_notifications SET processed=1,processed_at=? WHERE channel=? AND event_id=?", now, channel, n.EventID); err != nil { return err } details, _ := json.Marshal(gin.H{"actor_type": "payment_channel", "channel": channel, "order_id": orderID, "license_id": licenseID}) if _, err = tx.ExecContext(ctx, "INSERT INTO audit_events(actor_admin_id,action,resource_type,resource_id,details) VALUES(?,'payment.auto_issued','order',?,?)", actor, orderID, details); err != nil { return err } return tx.Commit() } func (a *BusinessAPI) listPaymentChannels(c *gin.Context) { c.Header("Cache-Control", "no-store") out := []gin.H{} for _, channel := range []string{"alipay", "wechat"} { view, e := a.paymentChannelView(c.Request.Context(), channel) if e != nil { apiError(c, 503, "configuration_unavailable", "渠道配置加载失败") return } out = append(out, view) } c.JSON(http.StatusOK, gin.H{"data": out}) } func (a *BusinessAPI) listPaymentOrders(c *gin.Context) { c.Header("Cache-Control", "no-store") rows, err := a.db.QueryContext(c.Request.Context(), "SELECT p.id,p.order_id,p.merchant_order_no,p.channel,p.channel_trade_no,p.amount_cents,p.currency,p.status,p.paid_at,p.created_at,o.status,o.issued_license_id,p.last_error,p.expires_at FROM payment_orders p JOIN offline_orders o ON o.id=p.order_id ORDER BY p.id DESC LIMIT 100") if err != nil { apiError(c, 500, "internal_error", "支付订单加载失败") return } defer rows.Close() out := []gin.H{} for rows.Next() { var id, order, amount uint64 var merchant, channel, currency, status string var trade sql.NullString var paid sql.NullTime var created, expires time.Time var orderStatus string var license sql.NullInt64 var lastError sql.NullString if err = rows.Scan(&id, &order, &merchant, &channel, &trade, &amount, ¤cy, &status, &paid, &created, &orderStatus, &license, &lastError, &expires); err != nil { apiError(c, 500, "internal_error", "支付订单加载失败") return } var tv, pv any if trade.Valid { tv = trade.String } if paid.Valid { pv = paid.Time } var licenseID, errorCode any if license.Valid { licenseID = license.Int64 } else if orderStatus == "issued" { orderStatus = "authorization_removed" } if lastError.Valid && lastError.String != "" { errorCode = "authorization_transaction_failed" } out = append(out, gin.H{"id": id, "order_id": order, "merchant_order_no": merchant, "channel": channel, "channel_trade_no": tv, "amount_cents": amount, "currency": currency, "status": status, "paid_at": pv, "created_at": created, "order_status": orderStatus, "license_id": licenseID, "last_error": errorCode, "expires_at": expires}) } if rows.Err() != nil { apiError(c, 500, "internal_error", "支付订单加载失败") return } c.JSON(200, gin.H{"data": out}) } // ReconcilePayments repairs callbacks lost while clients are offline. Queries are bounded. func (a *BusinessAPI) ReconcilePayments(ctx context.Context) { rows, err := a.db.QueryContext(ctx, "SELECT channel,merchant_order_no,provider_config_version FROM payment_orders WHERE status='created' ORDER BY updated_at LIMIT 100") if err != nil { return } type candidate struct { channel, no string version sql.NullInt64 } var pending []candidate for rows.Next() { var v candidate if rows.Scan(&v.channel, &v.no, &v.version) == nil { pending = append(pending, v) } } rows.Close() for _, v := range pending { if ctx.Err() != nil { return } p, pe := a.providerForPaymentVersion(ctx, v.channel, v.version) if pe != nil { continue } n, e := p.Query(ctx, v.no) if e == nil && n.Paid && n.MerchantOrderNo == v.no { if err := a.applyPayment(ctx, v.channel, n, v.version); err != nil { slog.Warn("payment_reconcile_failed", "channel", v.channel, "merchant_order_no", v.no, "error_code", "authorization_transaction_failed") _, _ = a.db.ExecContext(ctx, "UPDATE payment_orders SET last_error='authorization_transaction_failed' WHERE merchant_order_no=?", v.no) } } else if e != nil { slog.Warn("payment_query_failed", "channel", v.channel, "merchant_order_no", v.no, "error_code", "channel_query_failed") } _, _ = a.db.ExecContext(ctx, "UPDATE payment_orders SET updated_at=? WHERE merchant_order_no=?", time.Now().UTC(), v.no) } }