feat: add online payment management and checkout
Co-Authored-By: Craft Agent <agents-noreply@craft.do>
This commit is contained in:
@@ -13,13 +13,17 @@ import (
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"golang.org/x/crypto/bcrypt"
|
||||
"license-platform/backend/internal/payments"
|
||||
)
|
||||
|
||||
type BusinessAPI struct {
|
||||
db *sql.DB
|
||||
signingPrivateKeyPEM string
|
||||
keyring *Keyring
|
||||
credentialEncryptionKey []byte
|
||||
paymentProviders map[string]payments.Provider
|
||||
paymentEnvConfigs map[string]payments.Config
|
||||
db *sql.DB
|
||||
signingPrivateKeyPEM string
|
||||
keyring *Keyring
|
||||
credentialEncryptionKey []byte
|
||||
paymentConfigEncryptionKey []byte
|
||||
}
|
||||
|
||||
func secureSessionCookie(c *gin.Context) bool {
|
||||
@@ -46,6 +50,23 @@ func RegisterBusinessWithKeyring(r *gin.Engine, db *sql.DB, private string, ring
|
||||
}
|
||||
registerBusinessRoutes(r, a)
|
||||
}
|
||||
func RegisterBusinessWithPayments(r *gin.Engine, db *sql.DB, private string, ring *Keyring, credentialKey []byte, providers map[string]payments.Provider, paymentConfigKey ...[]byte) *BusinessAPI {
|
||||
envConfigs := map[string]payments.Config{}
|
||||
for _, channel := range []string{"alipay", "wechat"} {
|
||||
envConfigs[channel] = payments.ConfigFromEnv(channel)
|
||||
}
|
||||
startupProviders := map[string]payments.Provider{}
|
||||
for channel, provider := range providers {
|
||||
startupProviders[channel] = provider
|
||||
}
|
||||
a := &BusinessAPI{db: db, signingPrivateKeyPEM: private, keyring: ring, credentialEncryptionKey: credentialKey, paymentProviders: startupProviders, paymentEnvConfigs: envConfigs}
|
||||
if len(paymentConfigKey) > 0 {
|
||||
a.paymentConfigEncryptionKey = paymentConfigKey[0]
|
||||
}
|
||||
registerBusinessRoutes(r, a)
|
||||
return a
|
||||
}
|
||||
|
||||
func registerBusinessRoutes(r *gin.Engine, a *BusinessAPI) {
|
||||
api := r.Group("/api/v1")
|
||||
api.POST("/auth/login", a.login)
|
||||
@@ -62,6 +83,8 @@ func registerBusinessRoutes(r *gin.Engine, a *BusinessAPI) {
|
||||
api.POST("/instances/:instance_id/heartbeat", a.heartbeat)
|
||||
api.POST("/instances/:instance_id/updates/check", a.checkUpdate)
|
||||
api.POST("/auth/logout", a.authenticated, a.logout)
|
||||
api.POST("/payments/:channel/notify", a.paymentNotify)
|
||||
api.POST("/payments/checkout", a.paymentCheckout)
|
||||
secured := api.Group("", a.authenticated)
|
||||
secured.GET("/me", a.me)
|
||||
secured.GET("/admins", a.listAdmins)
|
||||
@@ -90,6 +113,11 @@ func registerBusinessRoutes(r *gin.Engine, a *BusinessAPI) {
|
||||
secured.POST("/orders", func(c *gin.Context) { a.writeOrder(c, "create") })
|
||||
secured.POST("/orders/:id/confirm-payment", func(c *gin.Context) { a.writeOrder(c, "confirm-payment") })
|
||||
secured.POST("/orders/:id/issue", func(c *gin.Context) { a.writeOrder(c, "issue") })
|
||||
secured.GET("/payment-channels", a.listPaymentChannels)
|
||||
secured.GET("/payment-channels/:channel", a.getPaymentChannel)
|
||||
secured.PUT("/payment-channels/:channel", a.updatePaymentChannel)
|
||||
secured.GET("/payment-orders", a.listPaymentOrders)
|
||||
secured.POST("/orders/:id/payment", a.createOnlinePayment)
|
||||
secured.GET("/licenses", a.listLicenses)
|
||||
secured.GET("/licenses/:id", a.getLicense)
|
||||
secured.GET("/licenses/:id/instances", a.listInstances)
|
||||
|
||||
@@ -28,7 +28,7 @@ func TestBusinessMySQLIntegration(t *testing.T) {
|
||||
if err = db.Ping(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, table := range []string{"instance_state_operations", "heartbeat_operations", "activation_operations", "license_instances", "order_operations", "offline_orders"} {
|
||||
for _, table := range []string{"instance_state_operations", "heartbeat_operations", "activation_operations", "license_instances", "authorization_grant_logs", "payment_notifications", "payment_orders", "order_operations", "offline_orders"} {
|
||||
if _, err = db.Exec("DELETE FROM " + table); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
@@ -38,6 +38,10 @@ func NewOperations(logger *slog.Logger) *Operations {
|
||||
}
|
||||
func operation(path string) string {
|
||||
switch path {
|
||||
case "/api/v1/payments/checkout":
|
||||
return "payment_checkout"
|
||||
case "/api/v1/payments/:channel/notify":
|
||||
return "payment_notify"
|
||||
case "/api/v1/portal/snapshot":
|
||||
return "login"
|
||||
case "/api/v1/auth/login":
|
||||
@@ -117,8 +121,11 @@ func (o *Operations) Middleware() gin.HandlerFunc {
|
||||
c.Abort()
|
||||
}
|
||||
}()
|
||||
if op == "login" || op == "activation" || op == "heartbeat" || op == "download" {
|
||||
if op == "login" || op == "activation" || op == "heartbeat" || op == "download" || op == "payment_checkout" || op == "payment_notify" {
|
||||
limit := 60
|
||||
if op == "payment_notify" {
|
||||
limit = 600
|
||||
}
|
||||
if op == "login" {
|
||||
limit = 10
|
||||
}
|
||||
|
||||
@@ -24,6 +24,8 @@ type orderRecord struct {
|
||||
ProductName string `json:"product_name"`
|
||||
AmountCents uint64 `json:"amount_cents"`
|
||||
Currency string `json:"currency"`
|
||||
PaymentChannel *string `json:"payment_channel"`
|
||||
PaymentStatus string `json:"payment_status"`
|
||||
Status string `json:"status"`
|
||||
PaymentReference *string `json:"payment_reference"`
|
||||
PaidAt *time.Time `json:"paid_at"`
|
||||
@@ -32,12 +34,12 @@ type orderRecord struct {
|
||||
UpdatedAt time.Time `json:"updated_at"`
|
||||
}
|
||||
|
||||
const orderSelect = `SELECT o.id,o.order_no,o.customer_id,c.name,o.product_id,p.name,o.amount_cents,o.currency,o.status,o.payment_reference,o.paid_at,o.issued_license_id,o.created_at,o.updated_at FROM offline_orders o JOIN customers c ON c.id=o.customer_id JOIN products p ON p.id=o.product_id`
|
||||
const orderSelect = `SELECT o.id,o.order_no,o.customer_id,c.name,o.product_id,p.name,o.amount_cents,o.currency,o.payment_channel,o.payment_status,o.status,o.payment_reference,o.paid_at,o.issued_license_id,o.created_at,o.updated_at FROM offline_orders o JOIN customers c ON c.id=o.customer_id JOIN products p ON p.id=o.product_id`
|
||||
|
||||
type orderScanner interface{ Scan(...any) error }
|
||||
|
||||
func scanOrder(s orderScanner) (o orderRecord, err error) {
|
||||
err = s.Scan(&o.ID, &o.OrderNo, &o.CustomerID, &o.CustomerName, &o.ProductID, &o.ProductName, &o.AmountCents, &o.Currency, &o.Status, &o.PaymentReference, &o.PaidAt, &o.LicenseID, &o.CreatedAt, &o.UpdatedAt)
|
||||
err = s.Scan(&o.ID, &o.OrderNo, &o.CustomerID, &o.CustomerName, &o.ProductID, &o.ProductName, &o.AmountCents, &o.Currency, &o.PaymentChannel, &o.PaymentStatus, &o.Status, &o.PaymentReference, &o.PaidAt, &o.LicenseID, &o.CreatedAt, &o.UpdatedAt)
|
||||
return
|
||||
}
|
||||
func (a *BusinessAPI) listOrders(c *gin.Context) {
|
||||
@@ -256,7 +258,7 @@ func (a *BusinessAPI) writeOrder(c *gin.Context, operation string) {
|
||||
}
|
||||
id = uint64(n)
|
||||
case "confirm-payment":
|
||||
if o.Status != "pending_payment" {
|
||||
if o.Status != "pending_payment" || o.PaymentChannel != nil {
|
||||
apiError(c, 409, "invalid_state", "只有待收款订单可确认收款")
|
||||
return
|
||||
}
|
||||
@@ -264,7 +266,7 @@ func (a *BusinessAPI) writeOrder(c *gin.Context, operation string) {
|
||||
apiError(c, 400, "amount_mismatch", "实际收款必须等于订单金额")
|
||||
return
|
||||
}
|
||||
_, err = tx.ExecContext(c, "UPDATE offline_orders SET status='paid',payment_reference=?,paid_at=?,paid_by=? WHERE id=?", in.PaymentReference, time.Now().UTC(), actor, id)
|
||||
_, err = tx.ExecContext(c, "UPDATE offline_orders SET status='paid',payment_status='paid',payment_reference=?,paid_at=?,paid_by=? WHERE id=?", in.PaymentReference, time.Now().UTC(), actor, id)
|
||||
if err != nil {
|
||||
fail()
|
||||
return
|
||||
|
||||
333
backend/internal/httpapi/payment_config.go
Normal file
333
backend/internal/httpapi/payment_config.go
Normal file
@@ -0,0 +1,333 @@
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/aes"
|
||||
"crypto/cipher"
|
||||
"crypto/rand"
|
||||
"database/sql"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"strings"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"license-platform/backend/internal/payments"
|
||||
)
|
||||
|
||||
var errPaymentChannelDisabled = errors.New("payment channel disabled")
|
||||
|
||||
func paymentFieldNames(channel string) (fields, secrets []string) {
|
||||
switch channel {
|
||||
case "alipay":
|
||||
return []string{"app_id", "seller_id", "notify_url"}, []string{"private_key", "public_key"}
|
||||
case "wechat":
|
||||
return []string{"app_id", "mch_id", "serial_no", "public_key_id", "platform_serial", "notify_url"}, []string{"private_key", "public_key", "platform_public_key", "api_v3_key"}
|
||||
}
|
||||
return nil, nil
|
||||
}
|
||||
func paymentSettingKey(channel, name string) string { return strings.ToUpper(channel + "_" + name) }
|
||||
func paymentConfigAAD(channel string, version int64) []byte {
|
||||
return []byte(fmt.Sprintf("payment-channel/%s/%d", channel, version))
|
||||
}
|
||||
func paymentConfigCipher(key []byte) (cipher.AEAD, error) {
|
||||
if len(key) != 32 {
|
||||
return nil, errors.New("payment encryption key unavailable")
|
||||
}
|
||||
b, e := aes.NewCipher(key)
|
||||
if e != nil {
|
||||
return nil, e
|
||||
}
|
||||
return cipher.NewGCM(b)
|
||||
}
|
||||
func encryptPaymentConfig(key []byte, channel string, version int64, config payments.Config) ([]byte, error) {
|
||||
a, e := paymentConfigCipher(key)
|
||||
if e != nil {
|
||||
return nil, e
|
||||
}
|
||||
plain, e := json.Marshal(config)
|
||||
if e != nil {
|
||||
return nil, e
|
||||
}
|
||||
nonce := make([]byte, a.NonceSize())
|
||||
if _, e = rand.Read(nonce); e != nil {
|
||||
return nil, e
|
||||
}
|
||||
return a.Seal(nonce, nonce, plain, paymentConfigAAD(channel, version)), nil
|
||||
}
|
||||
func decryptPaymentConfig(key []byte, channel string, version int64, data []byte) (payments.Config, error) {
|
||||
a, e := paymentConfigCipher(key)
|
||||
if e != nil {
|
||||
return nil, e
|
||||
}
|
||||
if len(data) < a.NonceSize() {
|
||||
return nil, errors.New("invalid encrypted config")
|
||||
}
|
||||
plain, e := a.Open(nil, data[:a.NonceSize()], data[a.NonceSize():], paymentConfigAAD(channel, version))
|
||||
if e != nil {
|
||||
return nil, e
|
||||
}
|
||||
var config payments.Config
|
||||
e = json.Unmarshal(plain, &config)
|
||||
return config, e
|
||||
}
|
||||
func (a *BusinessAPI) environmentPaymentConfig(channel string) payments.Config {
|
||||
config := payments.Config{}
|
||||
for k, v := range a.paymentEnvConfigs[channel] {
|
||||
config[k] = v
|
||||
}
|
||||
return config
|
||||
}
|
||||
func (a *BusinessAPI) paymentConfigVersion(ctx context.Context, channel string, version int64) (payments.Config, bool, error) {
|
||||
var encrypted []byte
|
||||
var enabled bool
|
||||
e := a.db.QueryRowContext(ctx, "SELECT config_encrypted,enabled FROM payment_channel_config_versions WHERE channel=? AND version=?", channel, version).Scan(&encrypted, &enabled)
|
||||
if e != nil {
|
||||
return nil, false, e
|
||||
}
|
||||
config, e := decryptPaymentConfig(a.paymentConfigEncryptionKey, channel, version, encrypted)
|
||||
return config, enabled, e
|
||||
}
|
||||
func (a *BusinessAPI) activePaymentConfig(ctx context.Context, channel string) (payments.Config, bool, sql.NullInt64, error) {
|
||||
var version sql.NullInt64
|
||||
if a.db != nil {
|
||||
if e := a.db.QueryRowContext(ctx, "SELECT active_version FROM payment_channel_configs WHERE channel=?", channel).Scan(&version); e != nil {
|
||||
return nil, false, version, e
|
||||
}
|
||||
}
|
||||
if !version.Valid {
|
||||
return a.environmentPaymentConfig(channel), a.paymentProviders[channel] != nil, version, nil
|
||||
}
|
||||
config, enabled, e := a.paymentConfigVersion(ctx, channel, version.Int64)
|
||||
return config, enabled, version, e
|
||||
}
|
||||
func (a *BusinessAPI) providerForPaymentVersion(ctx context.Context, channel string, version sql.NullInt64) (payments.Provider, error) {
|
||||
if !version.Valid {
|
||||
p := a.paymentProviders[channel]
|
||||
if p == nil {
|
||||
return nil, errPaymentChannelDisabled
|
||||
}
|
||||
return p, nil
|
||||
}
|
||||
config, _, e := a.paymentConfigVersion(ctx, channel, version.Int64)
|
||||
if e != nil {
|
||||
return nil, e
|
||||
}
|
||||
return payments.NewProvider(channel, config)
|
||||
}
|
||||
func (a *BusinessAPI) currentPaymentProvider(ctx context.Context, channel string) (payments.Provider, sql.NullInt64, error) {
|
||||
if len(payments.RequiredSettings(channel)) == 0 {
|
||||
return nil, sql.NullInt64{}, errPaymentChannelDisabled
|
||||
}
|
||||
config, enabled, v, e := a.activePaymentConfig(ctx, channel)
|
||||
if e != nil {
|
||||
return nil, v, e
|
||||
}
|
||||
if !enabled {
|
||||
return nil, v, errPaymentChannelDisabled
|
||||
}
|
||||
if !v.Valid {
|
||||
return a.paymentProviders[channel], v, nil
|
||||
}
|
||||
p, e := payments.NewProvider(channel, config)
|
||||
return p, v, e
|
||||
}
|
||||
func (a *BusinessAPI) paymentChannelView(ctx context.Context, channel string) (gin.H, error) {
|
||||
config, enabled, v, e := a.activePaymentConfig(ctx, channel)
|
||||
if e != nil {
|
||||
return nil, e
|
||||
}
|
||||
fields, secrets := paymentFieldNames(channel)
|
||||
ordinary := map[string]string{}
|
||||
flags := []gin.H{}
|
||||
for _, name := range fields {
|
||||
ordinary[name] = config[paymentSettingKey(channel, name)]
|
||||
}
|
||||
for _, name := range secrets {
|
||||
flags = append(flags, gin.H{"name": name, "configured": strings.TrimSpace(config[paymentSettingKey(channel, name)]) != ""})
|
||||
}
|
||||
source := "none"
|
||||
for _, value := range config {
|
||||
if strings.TrimSpace(value) != "" {
|
||||
source = "environment"
|
||||
break
|
||||
}
|
||||
}
|
||||
var version any
|
||||
if v.Valid {
|
||||
source = "database"
|
||||
version = v.Int64
|
||||
}
|
||||
effective := enabled
|
||||
if enabled && v.Valid {
|
||||
_, e := payments.NewProvider(channel, config)
|
||||
effective = e == nil
|
||||
}
|
||||
return gin.H{"channel": channel, "enabled": enabled, "effective": effective, "configuration_source": source, "version": version, "can_save": len(a.paymentConfigEncryptionKey) == 32, "required_settings": payments.RequiredSettings(channel), "fields": ordinary, "secret_fields": flags}, nil
|
||||
}
|
||||
func paymentConfigError(c *gin.Context, err error, fallback string) {
|
||||
if strings.Contains(err.Error(), "payment encryption key unavailable") {
|
||||
apiError(c, 503, "configuration_key_unavailable", "支付配置加密主密钥不可用")
|
||||
return
|
||||
}
|
||||
apiError(c, 503, "payment_schema_unavailable", fallback)
|
||||
}
|
||||
|
||||
func (a *BusinessAPI) getPaymentChannel(c *gin.Context) {
|
||||
c.Header("Cache-Control", "no-store")
|
||||
if c.GetString("admin_role") != "admin" {
|
||||
apiError(c, 403, "forbidden", "无权操作")
|
||||
return
|
||||
}
|
||||
if f, _ := paymentFieldNames(c.Param("channel")); len(f) == 0 {
|
||||
apiError(c, 404, "not_found", "支付渠道不存在")
|
||||
return
|
||||
}
|
||||
view, e := a.paymentChannelView(c.Request.Context(), c.Param("channel"))
|
||||
if e != nil {
|
||||
paymentConfigError(c, e, "支付配置数据库结构未就绪")
|
||||
return
|
||||
}
|
||||
c.JSON(200, gin.H{"data": view})
|
||||
}
|
||||
func paymentConfigOriginAllowed(c *gin.Context) bool {
|
||||
site := c.GetHeader("Sec-Fetch-Site")
|
||||
if site != "" && site != "same-origin" && site != "none" {
|
||||
return false
|
||||
}
|
||||
if origin := c.GetHeader("Origin"); origin != "" {
|
||||
u, e := url.Parse(origin)
|
||||
scheme := "http"
|
||||
if secureSessionCookie(c) {
|
||||
scheme = "https"
|
||||
}
|
||||
return e == nil && u.Scheme == scheme && u.Host == c.Request.Host && u.User == nil && u.RawQuery == "" && u.Fragment == "" && (u.Path == "" || u.Path == "/")
|
||||
}
|
||||
return true
|
||||
}
|
||||
func (a *BusinessAPI) updatePaymentChannel(c *gin.Context) {
|
||||
c.Header("Cache-Control", "no-store")
|
||||
if c.GetString("admin_role") != "admin" {
|
||||
apiError(c, 403, "forbidden", "无权操作")
|
||||
return
|
||||
}
|
||||
if !paymentConfigOriginAllowed(c) {
|
||||
apiError(c, 403, "origin_forbidden", "请求来源不允许")
|
||||
return
|
||||
}
|
||||
channel := c.Param("channel")
|
||||
fields, secrets := paymentFieldNames(channel)
|
||||
if len(fields) == 0 {
|
||||
apiError(c, 404, "not_found", "支付渠道不存在")
|
||||
return
|
||||
}
|
||||
if len(a.paymentConfigEncryptionKey) != 32 {
|
||||
apiError(c, 409, "encryption_key_unavailable", "尚未配置支付配置加密密钥")
|
||||
return
|
||||
}
|
||||
var in struct {
|
||||
Enabled *bool `json:"enabled"`
|
||||
Fields map[string]string `json:"fields"`
|
||||
Secrets map[string]string `json:"secrets"`
|
||||
}
|
||||
c.Request.Body = http.MaxBytesReader(c.Writer, c.Request.Body, 64<<10)
|
||||
dec := json.NewDecoder(c.Request.Body)
|
||||
dec.DisallowUnknownFields()
|
||||
if dec.Decode(&in) != nil || in.Enabled == nil {
|
||||
apiError(c, 400, "invalid_request", "配置格式无效")
|
||||
return
|
||||
}
|
||||
var extra any
|
||||
if dec.Decode(&extra) != io.EOF {
|
||||
apiError(c, 400, "invalid_request", "配置格式无效")
|
||||
return
|
||||
}
|
||||
allowed := func(values map[string]string, names []string) bool {
|
||||
for k := range values {
|
||||
found := false
|
||||
for _, n := range names {
|
||||
if k == n {
|
||||
found = true
|
||||
break
|
||||
}
|
||||
}
|
||||
if !found {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
if !allowed(in.Fields, fields) || !allowed(in.Secrets, secrets) {
|
||||
apiError(c, 400, "invalid_request", "配置包含不支持字段")
|
||||
return
|
||||
}
|
||||
ctx := c.Request.Context()
|
||||
tx, e := a.db.BeginTx(ctx, nil)
|
||||
if e != nil {
|
||||
apiError(c, 503, "configuration_unavailable", "保存失败")
|
||||
return
|
||||
}
|
||||
defer tx.Rollback()
|
||||
var actor uint64
|
||||
if e = tx.QueryRowContext(ctx, "SELECT id FROM admins WHERE id=? AND active=1 AND role='admin' FOR UPDATE", c.MustGet("admin_id")).Scan(&actor); e != nil {
|
||||
apiError(c, 403, "forbidden", "无权操作")
|
||||
return
|
||||
}
|
||||
var old sql.NullInt64
|
||||
if e = tx.QueryRowContext(ctx, "SELECT active_version FROM payment_channel_configs WHERE channel=? FOR UPDATE", channel).Scan(&old); e != nil {
|
||||
apiError(c, 503, "configuration_unavailable", "保存失败")
|
||||
return
|
||||
}
|
||||
config := a.environmentPaymentConfig(channel)
|
||||
if old.Valid {
|
||||
var encrypted []byte
|
||||
e = tx.QueryRowContext(ctx, "SELECT config_encrypted FROM payment_channel_config_versions WHERE channel=? AND version=?", channel, old.Int64).Scan(&encrypted)
|
||||
if e == nil {
|
||||
config, e = decryptPaymentConfig(a.paymentConfigEncryptionKey, channel, old.Int64, encrypted)
|
||||
}
|
||||
if e != nil {
|
||||
apiError(c, 503, "configuration_unavailable", "历史配置不可用")
|
||||
return
|
||||
}
|
||||
}
|
||||
for _, name := range fields {
|
||||
config[paymentSettingKey(channel, name)] = strings.TrimSpace(in.Fields[name])
|
||||
}
|
||||
for _, name := range secrets {
|
||||
if value := strings.TrimSpace(in.Secrets[name]); value != "" {
|
||||
config[paymentSettingKey(channel, name)] = value
|
||||
}
|
||||
}
|
||||
delete(config, paymentSettingKey(channel, "endpoint"))
|
||||
if *in.Enabled {
|
||||
if _, e = payments.NewProvider(channel, config); e != nil {
|
||||
apiError(c, 400, "invalid_configuration", "支付配置不完整或格式无效,请检查必填字段、HTTPS通知地址和密钥格式")
|
||||
return
|
||||
}
|
||||
}
|
||||
version := old.Int64 + 1
|
||||
encrypted, e := encryptPaymentConfig(a.paymentConfigEncryptionKey, channel, version, config)
|
||||
if e == nil {
|
||||
_, e = tx.ExecContext(ctx, "INSERT INTO payment_channel_config_versions(channel,version,enabled,config_encrypted,created_by) VALUES(?,?,?,?,?)", channel, version, *in.Enabled, encrypted, actor)
|
||||
}
|
||||
if e == nil {
|
||||
_, e = tx.ExecContext(ctx, "UPDATE payment_channel_configs SET active_version=? WHERE channel=?", version, channel)
|
||||
}
|
||||
if e == nil {
|
||||
details, _ := json.Marshal(gin.H{"version": version})
|
||||
_, e = tx.ExecContext(ctx, "INSERT INTO audit_events(actor_admin_id,action,resource_type,resource_id,details) VALUES(?,'payment.channel_config_updated','payment_channel',?,?)", actor, version, details)
|
||||
}
|
||||
if e != nil || tx.Commit() != nil {
|
||||
apiError(c, 503, "configuration_unavailable", "保存失败")
|
||||
return
|
||||
}
|
||||
view, e := a.paymentChannelView(ctx, channel)
|
||||
if e != nil {
|
||||
paymentConfigError(c, e, "支付配置数据库结构未就绪")
|
||||
return
|
||||
}
|
||||
c.JSON(200, gin.H{"data": view})
|
||||
}
|
||||
341
backend/internal/httpapi/payment_config_test.go
Normal file
341
backend/internal/httpapi/payment_config_test.go
Normal file
@@ -0,0 +1,341 @@
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"crypto"
|
||||
"crypto/rand"
|
||||
"crypto/rsa"
|
||||
"crypto/sha256"
|
||||
"crypto/x509"
|
||||
"database/sql"
|
||||
"encoding/base64"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"encoding/pem"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"net/url"
|
||||
"sort"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"license-platform/backend/internal/payments"
|
||||
)
|
||||
|
||||
func TestPaymentConfigEncryption(t *testing.T) {
|
||||
key := bytes.Repeat([]byte{0x42}, 32)
|
||||
config := payments.Config{"ALIPAY_PRIVATE_KEY": "private-value-that-must-stay-secret", "ALIPAY_APP_ID": "test-app"}
|
||||
encrypted, err := encryptPaymentConfig(key, "alipay", 1, config)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if bytes.Contains(encrypted, []byte(config["ALIPAY_PRIVATE_KEY"])) || bytes.Contains(encrypted, []byte("ALIPAY_PRIVATE_KEY")) {
|
||||
t.Fatal("plaintext stored")
|
||||
}
|
||||
repeated, err := encryptPaymentConfig(key, "alipay", 1, config)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if bytes.Equal(encrypted, repeated) {
|
||||
t.Fatal("nonce reused")
|
||||
}
|
||||
restored, err := decryptPaymentConfig(key, "alipay", 1, encrypted)
|
||||
if err != nil || restored["ALIPAY_PRIVATE_KEY"] != config["ALIPAY_PRIVATE_KEY"] {
|
||||
t.Fatal("round trip failed")
|
||||
}
|
||||
for _, tc := range []struct {
|
||||
name, channel string
|
||||
version int64
|
||||
key, data []byte
|
||||
}{
|
||||
{"wrong channel", "wechat", 1, key, encrypted}, {"wrong version", "alipay", 2, key, encrypted}, {"wrong key", "alipay", 1, bytes.Repeat([]byte{0x43}, 32), encrypted}, {"truncated", "alipay", 1, key, encrypted[:4]},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
if _, err := decryptPaymentConfig(tc.key, tc.channel, tc.version, tc.data); err == nil {
|
||||
t.Fatal("invalid context accepted")
|
||||
}
|
||||
})
|
||||
}
|
||||
tampered := append([]byte(nil), encrypted...)
|
||||
tampered[len(tampered)-1] ^= 1
|
||||
if _, err = decryptPaymentConfig(key, "alipay", 1, tampered); err == nil {
|
||||
t.Fatal("tampering accepted")
|
||||
}
|
||||
for _, length := range []int{0, 16, 31, 33} {
|
||||
if _, err = encryptPaymentConfig(make([]byte, length), "alipay", 1, config); err == nil {
|
||||
t.Fatalf("key length %d accepted", length)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestPaymentConfigAccessGuards(t *testing.T) {
|
||||
gin.SetMode(gin.TestMode)
|
||||
t.Setenv("SESSION_COOKIE_SECURE", "false")
|
||||
for _, tc := range []struct {
|
||||
name, role, origin, site string
|
||||
status int
|
||||
}{
|
||||
{"not admin", "viewer", "", "", 403}, {"foreign origin", "admin", "http://attacker.invalid", "", 403}, {"wrong scheme", "admin", "https://example.com", "", 403}, {"cross site", "admin", "", "cross-site", 403}, {"same site", "admin", "", "same-site", 403}, {"same origin missing key", "admin", "http://example.com", "same-origin", 409}, {"non browser missing key", "admin", "", "", 409},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
a := &BusinessAPI{}
|
||||
r := gin.New()
|
||||
r.Use(func(c *gin.Context) { c.Set("admin_role", tc.role) })
|
||||
r.PUT("/channels/:channel", a.updatePaymentChannel)
|
||||
w := httptest.NewRecorder()
|
||||
req := httptest.NewRequest(http.MethodPut, "http://example.com/channels/alipay", strings.NewReader(`{"enabled":false}`))
|
||||
req.Header.Set("Origin", tc.origin)
|
||||
req.Header.Set("Sec-Fetch-Site", tc.site)
|
||||
r.ServeHTTP(w, req)
|
||||
if w.Code != tc.status {
|
||||
t.Fatalf("status=%d body=%s", w.Code, w.Body.String())
|
||||
}
|
||||
})
|
||||
}
|
||||
r := paymentTestEngine(nil, nil)
|
||||
for _, method := range []string{http.MethodGet, http.MethodPut} {
|
||||
w := httptest.NewRecorder()
|
||||
r.ServeHTTP(w, httptest.NewRequest(method, "/api/v1/payment-channels/alipay", strings.NewReader(`{"enabled":false}`)))
|
||||
if w.Code != 401 {
|
||||
t.Fatalf("anonymous %s status=%d", method, w.Code)
|
||||
}
|
||||
}
|
||||
a := &BusinessAPI{}
|
||||
r = gin.New()
|
||||
r.GET("/channels/:channel", a.getPaymentChannel)
|
||||
w := httptest.NewRecorder()
|
||||
r.ServeHTTP(w, httptest.NewRequest(http.MethodGet, "/channels/alipay", nil))
|
||||
if w.Code != 403 {
|
||||
t.Fatalf("nonadmin GET=%d", w.Code)
|
||||
}
|
||||
view, err := a.paymentChannelView(context.Background(), "alipay")
|
||||
if err != nil || view["configuration_source"] != "none" || view["can_save"] != false {
|
||||
t.Fatalf("empty view=%v err=%v", view, err)
|
||||
}
|
||||
}
|
||||
|
||||
func paymentConfigTestValues(t *testing.T) (map[string]string, map[string]string) {
|
||||
t.Helper()
|
||||
priv, err := rsa.GenerateKey(rand.Reader, 2048)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
pk, err := x509.MarshalPKCS8PrivateKey(priv)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
pub, err := x509.MarshalPKIXPublicKey(&priv.PublicKey)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return map[string]string{"app_id": "config-test-app", "seller_id": "config-test-seller", "notify_url": "https://example.invalid/payment-notify"}, map[string]string{"private_key": string(pem.EncodeToMemory(&pem.Block{Type: "PRIVATE KEY", Bytes: pk})), "public_key": string(pem.EncodeToMemory(&pem.Block{Type: "PUBLIC KEY", Bytes: pub}))}
|
||||
}
|
||||
|
||||
func TestPaymentConfigMySQL(t *testing.T) {
|
||||
db, err := sql.Open("mysql", paymentIntegrationDSN(t))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer db.Close()
|
||||
f := newPaymentFixture(t, db, "config")
|
||||
defer func() { cleanPaymentFixture(t, db, f) }()
|
||||
var prior sql.NullInt64
|
||||
if err = db.QueryRow("SELECT active_version FROM payment_channel_configs WHERE channel='alipay'").Scan(&prior); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if prior.Valid {
|
||||
t.Fatal("isolated fixture requires no existing alipay config")
|
||||
}
|
||||
defer func() {
|
||||
for _, q := range []string{"UPDATE payment_orders SET provider_config_version=NULL WHERE order_id=?", "UPDATE payment_channel_configs SET active_version=NULL WHERE channel='alipay'", "DELETE FROM payment_channel_config_versions WHERE channel='alipay' AND created_by=?", "DELETE FROM audit_events WHERE actor_admin_id=? AND resource_type='payment_channel'", "DELETE FROM sessions WHERE admin_id=?"} {
|
||||
var args []any
|
||||
if strings.Contains(q, "order_id=?") {
|
||||
args = []any{f.order}
|
||||
} else if strings.Contains(q, "=?") {
|
||||
args = []any{f.admin}
|
||||
}
|
||||
if _, e := db.Exec(q, args...); e != nil {
|
||||
t.Error(e)
|
||||
}
|
||||
}
|
||||
}()
|
||||
key := bytes.Repeat([]byte{0x57}, 32)
|
||||
r := gin.New()
|
||||
a := RegisterBusinessWithPayments(r, db, "", nil, nil, map[string]payments.Provider{"alipay": paymentTestProvider{}}, key)
|
||||
token, err := randomPaymentToken(32)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
decoded, err := hex.DecodeString(token)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
hash := sha256.Sum256(decoded)
|
||||
if _, err = db.Exec("INSERT INTO sessions(admin_id,token_hash,expires_at) VALUES(?,?,?)", f.admin, hash[:], time.Now().Add(time.Hour)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
fields, secrets := paymentConfigTestValues(t)
|
||||
request := func(method string, body any, origin string, status int) map[string]any {
|
||||
t.Helper()
|
||||
raw, _ := json.Marshal(body)
|
||||
req := httptest.NewRequest(method, "http://example.com/api/v1/payment-channels/alipay", bytes.NewReader(raw))
|
||||
req.AddCookie(&http.Cookie{Name: "lp_session", Value: token})
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
req.Header.Set("Origin", origin)
|
||||
w := httptest.NewRecorder()
|
||||
r.ServeHTTP(w, req)
|
||||
if w.Code != status {
|
||||
t.Fatalf("%s status=%d body=%s", method, w.Code, w.Body.String())
|
||||
}
|
||||
if status == http.StatusOK && w.Header().Get("Cache-Control") != "no-store" {
|
||||
t.Fatal("missing no-store")
|
||||
}
|
||||
for _, secret := range secrets {
|
||||
if strings.Contains(w.Body.String(), strings.TrimSpace(secret)) || strings.Contains(w.Body.String(), "BEGIN PRIVATE KEY") || strings.Contains(w.Body.String(), "BEGIN PUBLIC KEY") {
|
||||
t.Fatal("secret exposed")
|
||||
}
|
||||
}
|
||||
var out struct{ Data map[string]any }
|
||||
if err := json.Unmarshal(w.Body.Bytes(), &out); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return out.Data
|
||||
}
|
||||
payload := func(enabled bool, s map[string]string) map[string]any {
|
||||
return map[string]any{"enabled": enabled, "fields": fields, "secrets": s}
|
||||
}
|
||||
request(http.MethodPut, payload(true, secrets), "http://foreign.invalid", 403)
|
||||
if _, err = db.Exec("UPDATE admins SET role='viewer' WHERE id=?", f.admin); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
request(http.MethodPut, payload(true, secrets), "", 403)
|
||||
if _, err = db.Exec("UPDATE admins SET role='admin' WHERE id=?", f.admin); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
view := request(http.MethodPut, payload(true, secrets), "http://example.com", 200)
|
||||
if view["version"] != float64(1) || view["effective"] != true || view["configuration_source"] != "database" {
|
||||
t.Fatalf("published view=%v", view)
|
||||
}
|
||||
var encrypted []byte
|
||||
if err = db.QueryRow("SELECT config_encrypted FROM payment_channel_config_versions WHERE channel='alipay' AND version=1").Scan(&encrypted); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, secret := range secrets {
|
||||
if bytes.Contains(encrypted, []byte(secret)) {
|
||||
t.Fatal("plaintext secret in database")
|
||||
}
|
||||
}
|
||||
if _, err = db.Exec("UPDATE payment_orders SET provider_config_version=1 WHERE id=?", f.payment); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
view = request(http.MethodPut, payload(false, map[string]string{"private_key": "", "public_key": ""}), "", 200)
|
||||
if view["version"] != float64(2) || view["enabled"] != false || view["effective"] != false {
|
||||
t.Fatalf("disabled view=%v", view)
|
||||
}
|
||||
one, _, err := a.paymentConfigVersion(context.Background(), "alipay", 1)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
two, enabled, err := a.paymentConfigVersion(context.Background(), "alipay", 2)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if enabled || one["ALIPAY_PRIVATE_KEY"] != two["ALIPAY_PRIVATE_KEY"] || two["ALIPAY_PUBLIC_KEY"] != strings.TrimSpace(secrets["public_key"]) {
|
||||
t.Fatal("blank secret did not preserve value")
|
||||
}
|
||||
view = request(http.MethodPut, payload(false, nil), "", 200)
|
||||
if view["version"] != float64(3) {
|
||||
t.Fatal("missing immutable new version")
|
||||
}
|
||||
three, _, err := a.paymentConfigVersion(context.Background(), "alipay", 3)
|
||||
if err != nil || three["ALIPAY_PRIVATE_KEY"] != one["ALIPAY_PRIVATE_KEY"] {
|
||||
t.Fatal("omitted secret not preserved")
|
||||
}
|
||||
request(http.MethodGet, nil, "", 200)
|
||||
if _, _, err = a.currentPaymentProvider(context.Background(), "alipay"); err != errPaymentChannelDisabled {
|
||||
t.Fatalf("disabled channel accepts new payments: %v", err)
|
||||
}
|
||||
if _, err = a.providerForPaymentVersion(context.Background(), "alipay", sql.NullInt64{Int64: 1, Valid: true}); err != nil {
|
||||
t.Fatalf("historical provider unavailable: %v", err)
|
||||
}
|
||||
n := paymentNotification(f, "config-version-event", "config-version-trade", 12800)
|
||||
for _, version := range []sql.NullInt64{{}, {Int64: 2, Valid: true}} {
|
||||
if err = a.applyPayment(context.Background(), "alipay", n, version); err == nil {
|
||||
t.Fatal("wrong config version accepted")
|
||||
}
|
||||
}
|
||||
assertPaymentCounts(t, db, f, 0)
|
||||
|
||||
// A fresh order is rejected after disable; the previously bound order remains confirmable.
|
||||
fresh := newPaymentFixture(t, db, "disabled")
|
||||
defer func() { cleanPaymentFixture(t, db, fresh) }()
|
||||
if _, err = db.Exec("DELETE FROM payment_orders WHERE order_id=?", fresh.order); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
newReq := httptest.NewRequest(http.MethodPost, fmt.Sprintf("http://example.com/api/v1/orders/%d/payment", fresh.order), strings.NewReader(`{"channel":"alipay","license_days":30}`))
|
||||
newReq.AddCookie(&http.Cookie{Name: "lp_session", Value: token})
|
||||
newReq.Header.Set("Content-Type", "application/json")
|
||||
newReq.Header.Set("Idempotency-Key", "config-disabled-new")
|
||||
newResponse := httptest.NewRecorder()
|
||||
r.ServeHTTP(newResponse, newReq)
|
||||
if newResponse.Code != 503 {
|
||||
t.Fatalf("disabled new payment status=%d body=%s", newResponse.Code, newResponse.Body.String())
|
||||
}
|
||||
var pending int
|
||||
if err = db.QueryRow("SELECT COUNT(*) FROM payment_orders WHERE order_id=?", fresh.order).Scan(&pending); err != nil || pending != 0 {
|
||||
t.Fatal("disabled channel created payment")
|
||||
}
|
||||
block, _ := pem.Decode([]byte(secrets["private_key"]))
|
||||
rawKey, e := x509.ParsePKCS8PrivateKey(block.Bytes)
|
||||
if e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
form := url.Values{"app_id": {fields["app_id"]}, "seller_id": {fields["seller_id"]}, "notify_id": {n.EventID}, "out_trade_no": {n.MerchantOrderNo}, "trade_no": {n.TradeNo}, "trade_status": {"TRADE_SUCCESS"}, "total_amount": {"128.00"}}
|
||||
keys := []string{}
|
||||
for k := range form {
|
||||
keys = append(keys, k)
|
||||
}
|
||||
sort.Strings(keys)
|
||||
parts := []string{}
|
||||
for _, k := range keys {
|
||||
parts = append(parts, k+"="+form.Get(k))
|
||||
}
|
||||
digest := sha256.Sum256([]byte(strings.Join(parts, "&")))
|
||||
sig, e := rsa.SignPKCS1v15(rand.Reader, rawKey.(*rsa.PrivateKey), crypto.SHA256, digest[:])
|
||||
if e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
form.Set("sign", base64.StdEncoding.EncodeToString(sig))
|
||||
form.Set("sign_type", "RSA2")
|
||||
callback := httptest.NewRequest(http.MethodPost, "/api/v1/payments/alipay/notify", strings.NewReader(form.Encode()))
|
||||
callback.Header.Set("Content-Type", "application/x-www-form-urlencoded")
|
||||
callbackResponse := httptest.NewRecorder()
|
||||
r.ServeHTTP(callbackResponse, callback)
|
||||
if callbackResponse.Code != 200 || callbackResponse.Body.String() != "success" {
|
||||
t.Fatalf("historical callback status=%d body=%s", callbackResponse.Code, callbackResponse.Body.String())
|
||||
}
|
||||
if err = a.applyPayment(context.Background(), "alipay", n, sql.NullInt64{Int64: 1, Valid: true}); err != nil {
|
||||
t.Fatalf("disabled historical payment failed: %v", err)
|
||||
}
|
||||
assertPaymentCounts(t, db, f, 1)
|
||||
var stored []byte
|
||||
if err = db.QueryRow("SELECT config_encrypted FROM payment_channel_config_versions WHERE channel='alipay' AND version=1").Scan(&stored); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !bytes.Equal(stored, encrypted) {
|
||||
t.Fatal("old version changed")
|
||||
}
|
||||
var details string
|
||||
if err = db.QueryRow("SELECT CAST(details AS CHAR) FROM audit_events WHERE actor_admin_id=? AND action='payment.channel_config_updated' ORDER BY id DESC LIMIT 1", f.admin).Scan(&details); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, secret := range secrets {
|
||||
if strings.Contains(details, secret) {
|
||||
t.Fatal("secret exposed in audit")
|
||||
}
|
||||
}
|
||||
}
|
||||
573
backend/internal/httpapi/payments.go
Normal file
573
backend/internal/httpapi/payments.go
Normal file
@@ -0,0 +1,573 @@
|
||||
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<?)", time.Now().UTC(), merchant, time.Now().UTC().Add(-15*time.Second))
|
||||
claimed := false
|
||||
if e == nil {
|
||||
affected, _ := claim.RowsAffected()
|
||||
claimed = affected == 1
|
||||
}
|
||||
if provider, pe := a.providerForPaymentVersion(c.Request.Context(), channel, version); pe == nil && claimed {
|
||||
notification, e := provider.Query(c.Request.Context(), merchant)
|
||||
if e == nil && notification.Paid && notification.MerchantOrderNo == merchant {
|
||||
if e = a.applyPayment(c.Request.Context(), channel, notification, version); e != nil {
|
||||
apiError(c, 503, "authorization_pending", "支付已完成,授权处理中")
|
||||
return
|
||||
}
|
||||
status = "paid"
|
||||
}
|
||||
}
|
||||
}
|
||||
if err = a.db.QueryRowContext(c.Request.Context(), "SELECT status,issued_license_id FROM offline_orders WHERE id=(SELECT order_id FROM payment_orders WHERE merchant_order_no=?)", merchant).Scan(&orderState, &license); err != nil {
|
||||
apiError(c, 500, "internal_error", "订单状态加载失败")
|
||||
return
|
||||
}
|
||||
if orderState == "issued" && !license.Valid {
|
||||
orderState = "authorization_removed"
|
||||
}
|
||||
if orderState != "issued" && time.Now().After(expires) {
|
||||
status = "expired"
|
||||
code.String = ""
|
||||
}
|
||||
var licenseValue any
|
||||
var licenseKey string
|
||||
if license.Valid {
|
||||
licenseValue = license.Int64
|
||||
if err = a.db.QueryRowContext(c.Request.Context(), "SELECT license_key FROM licenses WHERE id=?", license.Int64).Scan(&licenseKey); err != nil {
|
||||
apiError(c, 500, "internal_error", "授权加载失败")
|
||||
return
|
||||
}
|
||||
}
|
||||
c.JSON(200, gin.H{"data": gin.H{"code_url": code.String, "status": status, "order_status": orderState, "license_id": licenseValue, "license_key": licenseKey, "amount_cents": amount, "currency": currency, "channel": channel}})
|
||||
}
|
||||
|
||||
func (a *BusinessAPI) applyPayment(ctx context.Context, channel string, n payments.Notification, verifiedVersions ...sql.NullInt64) error {
|
||||
expectedVersion := sql.NullInt64{}
|
||||
if len(verifiedVersions) > 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)
|
||||
}
|
||||
}
|
||||
556
backend/internal/httpapi/payments_integration_test.go
Normal file
556
backend/internal/httpapi/payments_integration_test.go
Normal file
@@ -0,0 +1,556 @@
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"database/sql"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"github.com/gin-gonic/gin"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"net/url"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/go-sql-driver/mysql"
|
||||
migrate "github.com/golang-migrate/migrate/v4"
|
||||
_ "github.com/golang-migrate/migrate/v4/database/mysql"
|
||||
_ "github.com/golang-migrate/migrate/v4/source/file"
|
||||
"license-platform/backend/internal/payments"
|
||||
)
|
||||
|
||||
func paymentIntegrationDSN(t *testing.T) string {
|
||||
t.Helper()
|
||||
if dsn := os.Getenv("TEST_MYSQL_DSN"); dsn != "" {
|
||||
return dsn
|
||||
}
|
||||
if dsn := os.Getenv("MYSQL_TEST_DSN"); dsn != "" {
|
||||
return dsn
|
||||
}
|
||||
t.Skip("TEST_MYSQL_DSN or MYSQL_TEST_DSN is not set; payment MySQL integration skipped")
|
||||
return ""
|
||||
}
|
||||
|
||||
func TestPaymentsMySQLMigration13RoundTrip(t *testing.T) {
|
||||
if os.Getenv("PAYMENT_MIGRATION_ROUNDTRIP") != "1" {
|
||||
t.Skip("set PAYMENT_MIGRATION_ROUNDTRIP=1 for an explicitly isolated migration database")
|
||||
}
|
||||
dsn := paymentIntegrationDSN(t)
|
||||
cfg, err := mysql.ParseDSN(dsn)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
cfg.MultiStatements = true
|
||||
migrationDSN := cfg.FormatDSN()
|
||||
dir, err := filepath.Abs("../../migrations")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
m, err := migrate.New((&url.URL{Scheme: "file", Path: filepath.ToSlash(dir)}).String(), "mysql://"+migrationDSN)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer m.Close()
|
||||
v, _, err := m.Version()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if v != 13 && v != 14 {
|
||||
t.Fatalf("expected version 13 or 14, got %d", v)
|
||||
}
|
||||
original := v
|
||||
if v == 14 {
|
||||
if err = m.Steps(-1); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
if err = m.Steps(-1); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err = m.Steps(1); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if original == 14 {
|
||||
if err = m.Steps(1); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
v, dirty, err := m.Version()
|
||||
if err != nil || dirty || v != original {
|
||||
t.Fatalf("version=%d dirty=%v err=%v", v, dirty, err)
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
type paymentFixture struct {
|
||||
db *sql.DB
|
||||
admin, customer, product, order, payment uint64
|
||||
merchant string
|
||||
}
|
||||
|
||||
func newPaymentFixture(t *testing.T, db *sql.DB, suffix string) paymentFixture {
|
||||
t.Helper()
|
||||
var f paymentFixture
|
||||
unique, err := randomPaymentToken(6)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
suffix += "-" + unique
|
||||
mustExec := func(q string, args ...any) {
|
||||
if _, err := db.Exec(q, args...); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
email := "payment-" + suffix + "@example.invalid"
|
||||
username := "pay" + suffix
|
||||
mustExec("INSERT INTO admins(username,email,password_hash) VALUES(?,?,?)", username, email, "test")
|
||||
if err := db.QueryRow("SELECT id FROM admins WHERE username=?", username).Scan(&f.admin); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
mustExec("INSERT INTO customers(name,contact_email) VALUES(?,?)", "Payment "+suffix, email)
|
||||
if err := db.QueryRow("SELECT id FROM customers WHERE contact_email=?", email).Scan(&f.customer); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
mustExec("INSERT INTO products(code,name,description) VALUES(?,?,?)", "payment-"+suffix, "Payment Product", "test")
|
||||
if err := db.QueryRow("SELECT id FROM products WHERE code=?", "payment-"+suffix).Scan(&f.product); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
orderNo := "pay-order-" + unique
|
||||
mustExec("INSERT INTO offline_orders(order_no,customer_id,product_id,amount_cents,currency,status,created_by) VALUES(?,?,?,?,?,?,?)", orderNo, f.customer, f.product, 12800, "CNY", "pending_payment", f.admin)
|
||||
if err := db.QueryRow("SELECT id FROM offline_orders WHERE order_no=?", orderNo).Scan(&f.order); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
f.merchant = "pay-merchant-" + unique
|
||||
token, err := randomPaymentToken(32)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
mustExec("INSERT INTO payment_orders(order_id,merchant_order_no,channel,amount_cents,currency,license_days,checkout_token,expires_at) VALUES(?,?,?,?,?,?,?,?)", f.order, f.merchant, "alipay", 12800, "CNY", 30, token, time.Now().Add(time.Hour))
|
||||
if err := db.QueryRow("SELECT id FROM payment_orders WHERE merchant_order_no=?", f.merchant).Scan(&f.payment); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return f
|
||||
}
|
||||
|
||||
func cleanPaymentFixture(t *testing.T, db *sql.DB, f paymentFixture) {
|
||||
t.Helper()
|
||||
for _, q := range []string{
|
||||
"DELETE FROM payment_notifications WHERE merchant_order_no=?",
|
||||
"DELETE FROM authorization_grant_logs WHERE order_id=?",
|
||||
"DELETE FROM payment_orders WHERE order_id=?",
|
||||
"UPDATE offline_orders SET issued_license_id=NULL WHERE id=?",
|
||||
"DELETE FROM audit_events WHERE resource_id=? AND resource_type='order'",
|
||||
"DELETE FROM licenses WHERE idempotency_key=?",
|
||||
"DELETE FROM offline_orders WHERE id=?",
|
||||
"DELETE FROM products WHERE id=?",
|
||||
"DELETE FROM customers WHERE id=?",
|
||||
"DELETE FROM admins WHERE id=?",
|
||||
} {
|
||||
var arg any = f.order
|
||||
if strings.Contains(q, "merchant_order_no") {
|
||||
arg = f.merchant
|
||||
}
|
||||
if strings.Contains(q, "products") {
|
||||
arg = f.product
|
||||
}
|
||||
if strings.Contains(q, "customers") {
|
||||
arg = f.customer
|
||||
}
|
||||
if strings.Contains(q, "admins") {
|
||||
arg = f.admin
|
||||
}
|
||||
if strings.Contains(q, "licenses") {
|
||||
arg = fmt.Sprintf("online-order-%d", f.order)
|
||||
}
|
||||
if _, err := db.Exec(q, arg); err != nil {
|
||||
t.Errorf("cleanup %s: %v", q, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func paymentNotification(f paymentFixture, event, trade string, amount int64) payments.Notification {
|
||||
return payments.Notification{Paid: true, EventID: event, MerchantOrderNo: f.merchant, TradeNo: trade, Currency: "CNY", AmountCents: amount}
|
||||
}
|
||||
|
||||
func TestApplyPaymentMySQLTransactions(t *testing.T) {
|
||||
dsn := paymentIntegrationDSN(t)
|
||||
db, err := sql.Open("mysql", dsn)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer db.Close()
|
||||
if err = db.Ping(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, suffix := range []string{"amt", "dup", "conc", "audit", "offline", "event"} {
|
||||
t.Run(suffix, func(t *testing.T) {
|
||||
f := newPaymentFixture(t, db, suffix)
|
||||
defer func() { cleanPaymentFixture(t, db, f) }()
|
||||
a := &BusinessAPI{db: db}
|
||||
switch suffix {
|
||||
case "amt":
|
||||
if err := a.applyPayment(context.Background(), "alipay", paymentNotification(f, "evt-amt", "trade-amt", 12799)); err == nil {
|
||||
t.Fatal("amount mismatch was accepted")
|
||||
}
|
||||
var n int
|
||||
db.QueryRow("SELECT COUNT(*) FROM licenses WHERE idempotency_key=?", fmt.Sprintf("online-order-%d", f.order)).Scan(&n)
|
||||
if n != 0 {
|
||||
t.Fatalf("licenses=%d", n)
|
||||
}
|
||||
case "dup":
|
||||
n := paymentNotification(f, "evt-dup-1", "trade-dup", 12800)
|
||||
if err := a.applyPayment(context.Background(), "alipay", n); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := a.applyPayment(context.Background(), "alipay", n); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := a.applyPayment(context.Background(), "alipay", paymentNotification(f, "evt-dup-2", "trade-dup", 12800)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
assertPaymentCounts(t, db, f, 1)
|
||||
case "conc":
|
||||
n := paymentNotification(f, "evt-concurrent", "trade-concurrent", 12800)
|
||||
errs := make(chan error, 2)
|
||||
var wg sync.WaitGroup
|
||||
wg.Add(2)
|
||||
for i := 0; i < 2; i++ {
|
||||
go func() { defer wg.Done(); errs <- a.applyPayment(context.Background(), "alipay", n) }()
|
||||
}
|
||||
wg.Wait()
|
||||
close(errs)
|
||||
successes := 0
|
||||
for e := range errs {
|
||||
if e == nil {
|
||||
successes++
|
||||
}
|
||||
}
|
||||
if successes != 2 {
|
||||
t.Fatalf("successful concurrent applies=%d", successes)
|
||||
}
|
||||
assertPaymentCounts(t, db, f, 1)
|
||||
case "audit":
|
||||
trigger := "payment_audit_fail_" + suffix
|
||||
if _, err := db.Exec("CREATE TRIGGER `" + trigger + "` BEFORE INSERT ON audit_events FOR EACH ROW SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT='payment audit failure'"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
err := a.applyPayment(context.Background(), "alipay", paymentNotification(f, "evt-audit", "trade-audit", 12800))
|
||||
_, dropErr := db.Exec("DROP TRIGGER `" + trigger + "`")
|
||||
if dropErr != nil {
|
||||
t.Fatal(dropErr)
|
||||
}
|
||||
if err == nil {
|
||||
t.Fatal("audit failure was accepted")
|
||||
}
|
||||
assertPaymentCounts(t, db, f, 0)
|
||||
if err := a.applyPayment(context.Background(), "alipay", paymentNotification(f, "evt-audit", "trade-audit", 12800)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
assertPaymentCounts(t, db, f, 1)
|
||||
case "offline":
|
||||
if _, err := db.Exec("UPDATE offline_orders SET status='paid',payment_status='paid' WHERE id=?", f.order); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := a.applyPayment(context.Background(), "alipay", paymentNotification(f, "evt-offline", "trade-offline", 12800)); err == nil {
|
||||
t.Fatal("offline-paid order was accepted")
|
||||
}
|
||||
assertPaymentCounts(t, db, f, 0)
|
||||
case "event":
|
||||
if err := a.applyPayment(context.Background(), "alipay", paymentNotification(f, "evt-conflict", "trade-one", 12800)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := a.applyPayment(context.Background(), "alipay", paymentNotification(f, "evt-conflict", "trade-two", 12800)); err == nil {
|
||||
t.Fatal("notification event conflict was accepted")
|
||||
}
|
||||
assertPaymentCounts(t, db, f, 1)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func assertPaymentCounts(t *testing.T, db *sql.DB, f paymentFixture, licenses int) {
|
||||
t.Helper()
|
||||
var n int
|
||||
if err := db.QueryRow("SELECT COUNT(*) FROM licenses WHERE idempotency_key=?", fmt.Sprintf("online-order-%d", f.order)).Scan(&n); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if n != licenses {
|
||||
t.Fatalf("licenses=%d want=%d", n, licenses)
|
||||
}
|
||||
if err := db.QueryRow("SELECT COUNT(*) FROM authorization_grant_logs WHERE order_id=?", f.order).Scan(&n); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if n != licenses {
|
||||
t.Fatalf("grant logs=%d want=%d", n, licenses)
|
||||
}
|
||||
var status string
|
||||
if err := db.QueryRow("SELECT status FROM payment_orders WHERE order_id=?", f.order).Scan(&status); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
want := "created"
|
||||
if licenses == 1 {
|
||||
want = "paid"
|
||||
}
|
||||
if status != want {
|
||||
t.Fatalf("payment state=%s want=%s", status, want)
|
||||
}
|
||||
if err := db.QueryRow("SELECT COUNT(*) FROM payment_notifications WHERE merchant_order_no=?", f.merchant).Scan(&n); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if licenses == 0 && n != 0 {
|
||||
t.Fatalf("rolled back notifications=%d", n)
|
||||
}
|
||||
if licenses == 1 {
|
||||
var issuer uint64
|
||||
if err := db.QueryRow("SELECT issued_by FROM licenses WHERE idempotency_key=?", fmt.Sprintf("online-order-%d", f.order)).Scan(&issuer); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if issuer != f.admin {
|
||||
t.Fatalf("issuer=%d want=%d", issuer, f.admin)
|
||||
}
|
||||
var actorType string
|
||||
if err := db.QueryRow("SELECT JSON_UNQUOTE(JSON_EXTRACT(details,'$.actor_type')) FROM audit_events WHERE resource_id=? AND action='payment.auto_issued'", f.order).Scan(&actorType); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if actorType != "payment_channel" {
|
||||
t.Fatalf("actor_type=%s", actorType)
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
func TestPaymentNotifyVerificationFailureWithMySQL(t *testing.T) {
|
||||
dsn := paymentIntegrationDSN(t)
|
||||
db, err := sql.Open("mysql", dsn)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer db.Close()
|
||||
if err = db.Ping(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
before := 0
|
||||
if err = db.QueryRow("SELECT COUNT(*) FROM payment_notifications").Scan(&before); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
provider := paymentTestProvider{verifyErr: errors.New("invalid signature")}
|
||||
r := paymentTestEngine(db, map[string]payments.Provider{"alipay": provider})
|
||||
req := httptest.NewRequest(http.MethodPost, "/api/v1/payments/alipay/notify", strings.NewReader("bad"))
|
||||
w := httptest.NewRecorder()
|
||||
r.ServeHTTP(w, req)
|
||||
if w.Code != http.StatusBadRequest {
|
||||
t.Fatalf("code=%d body=%s", w.Code, w.Body.String())
|
||||
}
|
||||
var after int
|
||||
if err = db.QueryRow("SELECT COUNT(*) FROM payment_notifications").Scan(&after); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if before != after {
|
||||
t.Fatalf("notifications changed %d -> %d", before, after)
|
||||
}
|
||||
}
|
||||
|
||||
func TestPaymentOnlineCheckoutMySQL(t *testing.T) {
|
||||
db, err := sql.Open("mysql", paymentIntegrationDSN(t))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer db.Close()
|
||||
f := newPaymentFixture(t, db, "http")
|
||||
defer func() { cleanPaymentFixture(t, db, f) }()
|
||||
// This fixture is a legacy NULL-version payment; new payments require a real encrypted provider snapshot.
|
||||
if _, err = db.Exec("UPDATE offline_orders SET payment_channel='alipay',payment_expires_at=(SELECT expires_at FROM payment_orders WHERE order_id=?) WHERE id=?", f.order, f.order); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer func() {
|
||||
if _, e := db.Exec("DELETE FROM order_operations WHERE order_id=?", f.order); e != nil {
|
||||
t.Error(e)
|
||||
}
|
||||
}()
|
||||
provider := &paymentTestProvider{}
|
||||
a := &BusinessAPI{db: db, paymentProviders: map[string]payments.Provider{"alipay": provider}}
|
||||
gin.SetMode(gin.TestMode)
|
||||
r := gin.New()
|
||||
r.Use(func(c *gin.Context) { c.Set("admin_id", f.admin); c.Next() })
|
||||
r.POST("/orders/:id/payment", a.createOnlinePayment)
|
||||
r.POST("/orders/:id/confirm-payment", func(c *gin.Context) { a.writeOrder(c, "confirm-payment") })
|
||||
r.POST("/checkout", a.paymentCheckout)
|
||||
request := func(path, body, key string) *httptest.ResponseRecorder {
|
||||
t.Helper()
|
||||
w := httptest.NewRecorder()
|
||||
req := httptest.NewRequest("POST", path, strings.NewReader(body))
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
req.Header.Set("Idempotency-Key", key)
|
||||
r.ServeHTTP(w, req)
|
||||
return w
|
||||
}
|
||||
path := fmt.Sprintf("/orders/%d/payment", f.order)
|
||||
w := request(path, `{"channel":"alipay","license_days":30}`, "online-http")
|
||||
if w.Code != 200 {
|
||||
t.Fatalf("create=%d %s", w.Code, w.Body.String())
|
||||
}
|
||||
var response struct {
|
||||
Data struct {
|
||||
Merchant string `json:"merchant_order_no"`
|
||||
Token string `json:"checkout_token"`
|
||||
}
|
||||
}
|
||||
if err = json.Unmarshal(w.Body.Bytes(), &response); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
f.merchant = response.Data.Merchant
|
||||
repeat := request(path, `{"channel":"alipay","license_days":30}`, "online-http")
|
||||
if repeat.Code != 200 || repeat.Body.String() != w.Body.String() {
|
||||
t.Fatalf("idempotent response %d %s", repeat.Code, repeat.Body.String())
|
||||
}
|
||||
conflict := request(path, `{"channel":"alipay","license_days":31}`, "online-http")
|
||||
if conflict.Code != 409 {
|
||||
t.Fatalf("idempotency conflict=%d", conflict.Code)
|
||||
}
|
||||
conflict = request(path, `{"channel":"alipay","license_days":31}`, "other-key")
|
||||
if conflict.Code != 409 {
|
||||
t.Fatalf("duration conflict=%d", conflict.Code)
|
||||
}
|
||||
var amount int64
|
||||
var days int
|
||||
var expires time.Time
|
||||
if err = db.QueryRow("SELECT amount_cents,license_days,expires_at FROM payment_orders WHERE order_id=?", f.order).Scan(&amount, &days, &expires); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if amount != 12800 || days != 30 || time.Until(expires) < 59*time.Minute || time.Until(expires) > 61*time.Minute {
|
||||
t.Fatalf("frozen amount=%d days=%d", amount, days)
|
||||
}
|
||||
manual := request(fmt.Sprintf("/orders/%d/confirm-payment", f.order), `{"payment_reference":"manual","amount_cents":12800}`, "manual-http")
|
||||
if manual.Code != 409 {
|
||||
t.Fatalf("manual confirm=%d %s", manual.Code, manual.Body.String())
|
||||
}
|
||||
provider.notification = paymentNotification(f, "http-event", "http-trade", 12800)
|
||||
checkout := request("/checkout", fmt.Sprintf(`{"token":%q}`, response.Data.Token), "")
|
||||
if checkout.Code != 200 {
|
||||
t.Fatalf("checkout=%d %s", checkout.Code, checkout.Body.String())
|
||||
}
|
||||
var result struct {
|
||||
Data struct {
|
||||
Key string `json:"license_key"`
|
||||
}
|
||||
}
|
||||
if err = json.Unmarshal(checkout.Body.Bytes(), &result); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(result.Data.Key) != 32 {
|
||||
t.Fatalf("missing license key: %s", checkout.Body.String())
|
||||
}
|
||||
assertPaymentCounts(t, db, f, 1)
|
||||
}
|
||||
|
||||
func TestPaymentManagementMySQL(t *testing.T) {
|
||||
db, err := sql.Open("mysql", paymentIntegrationDSN(t))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer db.Close()
|
||||
f := newPaymentFixture(t, db, "management")
|
||||
defer func() { cleanPaymentFixture(t, db, f) }()
|
||||
token, err := randomPaymentToken(32)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
decoded, err := hex.DecodeString(token)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
sum := sha256.Sum256(decoded)
|
||||
if _, err = db.Exec("INSERT INTO sessions(admin_id,token_hash,expires_at) VALUES(?,?,?)", f.admin, sum[:], time.Now().Add(time.Hour)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer func() {
|
||||
if _, e := db.Exec("DELETE FROM sessions WHERE admin_id=?", f.admin); e != nil {
|
||||
t.Error(e)
|
||||
}
|
||||
}()
|
||||
r := paymentTestEngine(db, map[string]payments.Provider{"alipay": paymentTestProvider{}})
|
||||
request := func(method, path string) *httptest.ResponseRecorder {
|
||||
t.Helper()
|
||||
w := httptest.NewRecorder()
|
||||
req := httptest.NewRequest(method, path, nil)
|
||||
req.AddCookie(&http.Cookie{Name: "lp_session", Value: token})
|
||||
r.ServeHTTP(w, req)
|
||||
if w.Code != 200 && !(method == http.MethodDelete && w.Code == http.StatusNoContent) {
|
||||
t.Fatalf("%s %s status=%d body=%s", method, path, w.Code, w.Body.String())
|
||||
}
|
||||
return w
|
||||
}
|
||||
channels := request(http.MethodGet, "/api/v1/payment-channels")
|
||||
if !strings.Contains(channels.Body.String(), `"enabled":true`) || !strings.Contains(channels.Body.String(), `"enabled":false`) {
|
||||
t.Fatal("missing enabled/disabled channel")
|
||||
}
|
||||
a := &BusinessAPI{db: db}
|
||||
if err = a.applyPayment(context.Background(), "alipay", paymentNotification(f, "management-event", "management-trade", 12800)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var licenseID uint64
|
||||
var licenseKey, checkoutToken string
|
||||
if err = db.QueryRow("SELECT l.id,l.license_key,p.checkout_token FROM licenses l JOIN offline_orders o ON o.issued_license_id=l.id JOIN payment_orders p ON p.order_id=o.id WHERE o.id=?", f.order).Scan(&licenseID, &licenseKey, &checkoutToken); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
getOrder := func() map[string]any {
|
||||
t.Helper()
|
||||
w := request(http.MethodGet, "/api/v1/payment-orders")
|
||||
if w.Header().Get("Cache-Control") != "no-store" {
|
||||
t.Fatal("missing no-store")
|
||||
}
|
||||
body := w.Body.String()
|
||||
for _, secret := range []string{token, licenseKey, checkoutToken, `"checkout_token"`, `"license_key"`, "sensitive provider failure test-value"} {
|
||||
if strings.Contains(body, secret) {
|
||||
t.Fatal("management response exposes secret")
|
||||
}
|
||||
}
|
||||
var response struct{ Data []map[string]any }
|
||||
if err := json.Unmarshal(w.Body.Bytes(), &response); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, row := range response.Data {
|
||||
if row["merchant_order_no"] == f.merchant {
|
||||
return row
|
||||
}
|
||||
}
|
||||
t.Fatal("payment order missing")
|
||||
return nil
|
||||
}
|
||||
row := getOrder()
|
||||
if row["amount_cents"] != float64(12800) || row["channel_trade_no"] != "management-trade" || row["status"] != "paid" || row["order_status"] != "issued" || row["license_id"] != float64(licenseID) || row["paid_at"] == nil || row["expires_at"] == nil || row["last_error"] != nil {
|
||||
t.Fatalf("unexpected paid order: %v", row)
|
||||
}
|
||||
const rawError = "sensitive provider failure test-value"
|
||||
if _, err = db.Exec("UPDATE payment_orders SET last_error=? WHERE id=?", rawError, f.payment); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
row = getOrder()
|
||||
if row["last_error"] != "authorization_transaction_failed" {
|
||||
t.Fatalf("error not sanitized: %v", row["last_error"])
|
||||
}
|
||||
defer func() {
|
||||
if _, e := db.Exec("DELETE FROM audit_events WHERE action='license.deleted' AND resource_type='license' AND resource_id=? AND actor_admin_id=?", licenseID, f.admin); e != nil {
|
||||
t.Error(e)
|
||||
}
|
||||
}()
|
||||
request(http.MethodDelete, fmt.Sprintf("/api/v1/licenses/%d", licenseID))
|
||||
row = getOrder()
|
||||
if row["order_status"] != "authorization_removed" || row["license_id"] != nil || row["channel_trade_no"] != "management-trade" || row["status"] != "paid" {
|
||||
t.Fatalf("unexpected removed authorization: %v", row)
|
||||
}
|
||||
var retained int
|
||||
if err = db.QueryRow("SELECT COUNT(*) FROM authorization_grant_logs WHERE order_id=? AND license_id IS NULL", f.order).Scan(&retained); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if retained != 1 {
|
||||
t.Fatalf("grant audit retention=%d", retained)
|
||||
}
|
||||
}
|
||||
140
backend/internal/httpapi/payments_test.go
Normal file
140
backend/internal/httpapi/payments_test.go
Normal file
@@ -0,0 +1,140 @@
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"context"
|
||||
"database/sql"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"license-platform/backend/internal/payments"
|
||||
)
|
||||
|
||||
type paymentTestProvider struct {
|
||||
notification payments.Notification
|
||||
verifyErr error
|
||||
}
|
||||
|
||||
func (p paymentTestProvider) Create(context.Context, string, int64, string) (string, error) {
|
||||
return "https://example.invalid/code", nil
|
||||
}
|
||||
func (p paymentTestProvider) Query(context.Context, string) (payments.Notification, error) {
|
||||
return p.notification, nil
|
||||
}
|
||||
func (p paymentTestProvider) Verify(*http.Request) (payments.Notification, error) {
|
||||
return p.notification, p.verifyErr
|
||||
}
|
||||
func (p paymentTestProvider) Close(context.Context, string) error { return nil }
|
||||
func (p paymentTestProvider) Refund(context.Context, string, string, int64) error { return nil }
|
||||
|
||||
func paymentTestEngine(db *sql.DB, providers map[string]payments.Provider) *gin.Engine {
|
||||
gin.SetMode(gin.TestMode)
|
||||
r := gin.New()
|
||||
RegisterBusinessWithPayments(r, db, "", nil, nil, providers)
|
||||
return r
|
||||
}
|
||||
|
||||
func TestPaymentNotifyWithoutConfiguredProvider(t *testing.T) {
|
||||
r := paymentTestEngine(nil, map[string]payments.Provider{})
|
||||
req := httptest.NewRequest(http.MethodPost, "/api/v1/payments/alipay/notify", strings.NewReader("{}"))
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
w := httptest.NewRecorder()
|
||||
r.ServeHTTP(w, req)
|
||||
if w.Code != http.StatusServiceUnavailable || !strings.Contains(w.Body.String(), "channel_unavailable") {
|
||||
t.Fatalf("code=%d body=%s", w.Code, w.Body.String())
|
||||
}
|
||||
}
|
||||
|
||||
func TestPaymentNotifyVerificationFailureDoesNotTouchDB(t *testing.T) {
|
||||
provider := paymentTestProvider{verifyErr: errors.New("bad signature")}
|
||||
r := paymentTestEngine(nil, map[string]payments.Provider{"alipay": provider})
|
||||
req := httptest.NewRequest(http.MethodPost, "/api/v1/payments/alipay/notify", strings.NewReader(`{"trade_no":"should-not-be-used"}`))
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
w := httptest.NewRecorder()
|
||||
r.ServeHTTP(w, req)
|
||||
if w.Code != http.StatusBadRequest || !strings.Contains(w.Body.String(), "invalid_notification") {
|
||||
t.Fatalf("code=%d body=%s", w.Code, w.Body.String())
|
||||
}
|
||||
}
|
||||
|
||||
func TestPaymentCheckoutRequiresToken(t *testing.T) {
|
||||
r := paymentTestEngine(nil, nil)
|
||||
req := httptest.NewRequest(http.MethodPost, "/api/v1/payments/checkout", strings.NewReader(`{}`))
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
w := httptest.NewRecorder()
|
||||
r.ServeHTTP(w, req)
|
||||
if w.Code != http.StatusBadRequest || !strings.Contains(w.Body.String(), "invalid_request") {
|
||||
t.Fatalf("code=%d body=%s", w.Code, w.Body.String())
|
||||
}
|
||||
}
|
||||
|
||||
func TestPaymentManagementRequiresAuthentication(t *testing.T) {
|
||||
r := paymentTestEngine(nil, nil)
|
||||
for _, path := range []string{"/api/v1/payment-channels", "/api/v1/payment-orders"} {
|
||||
t.Run(path, func(t *testing.T) {
|
||||
w := httptest.NewRecorder()
|
||||
r.ServeHTTP(w, httptest.NewRequest(http.MethodGet, path, nil))
|
||||
if w.Code != 401 || !strings.Contains(w.Body.String(), "unauthorized") {
|
||||
t.Fatalf("status=%d body=%s", w.Code, w.Body.String())
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestPaymentChannelConfiguration(t *testing.T) {
|
||||
for _, enabled := range []string{"none", "alipay", "wechat", "both"} {
|
||||
t.Run(enabled, func(t *testing.T) {
|
||||
providers := map[string]payments.Provider{}
|
||||
for _, channel := range []string{"alipay", "wechat"} {
|
||||
if enabled == channel || enabled == "both" {
|
||||
providers[channel] = paymentTestProvider{}
|
||||
}
|
||||
}
|
||||
t.Setenv("ALIPAY_PRIVATE_KEY", "secret-alipay-test-value")
|
||||
t.Setenv("WECHAT_API_V3_KEY", "secret-wechat-test-value")
|
||||
a := &BusinessAPI{paymentProviders: providers, paymentEnvConfigs: map[string]payments.Config{
|
||||
"alipay": payments.ConfigFromEnv("alipay"),
|
||||
"wechat": payments.ConfigFromEnv("wechat"),
|
||||
}}
|
||||
r := gin.New()
|
||||
r.GET("/channels", a.listPaymentChannels)
|
||||
w := httptest.NewRecorder()
|
||||
r.ServeHTTP(w, httptest.NewRequest(http.MethodGet, "/channels", nil))
|
||||
if w.Code != 200 || w.Header().Get("Cache-Control") != "no-store" {
|
||||
t.Fatalf("status=%d headers=%v", w.Code, w.Header())
|
||||
}
|
||||
var response struct {
|
||||
Data []struct {
|
||||
Channel string `json:"channel"`
|
||||
Enabled bool `json:"enabled"`
|
||||
Source string `json:"configuration_source"`
|
||||
Settings []string `json:"required_settings"`
|
||||
}
|
||||
}
|
||||
if err := json.Unmarshal(w.Body.Bytes(), &response); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(response.Data) != 2 {
|
||||
t.Fatalf("channel count=%d", len(response.Data))
|
||||
}
|
||||
seen := map[string]bool{}
|
||||
for _, row := range response.Data {
|
||||
want := providers[row.Channel] != nil
|
||||
if row.Enabled != want || row.Source != "environment" || len(row.Settings) == 0 {
|
||||
t.Fatalf("unexpected channel: %+v", row)
|
||||
}
|
||||
seen[row.Channel] = true
|
||||
}
|
||||
if !seen["alipay"] || !seen["wechat"] {
|
||||
t.Fatal("missing payment channel")
|
||||
}
|
||||
if strings.Contains(w.Body.String(), "secret-alipay-test-value") || strings.Contains(w.Body.String(), "secret-wechat-test-value") {
|
||||
t.Fatal("configuration values exposed")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -9,7 +9,7 @@ import (
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
const RequiredSchemaVersion = 12
|
||||
const RequiredSchemaVersion = 15
|
||||
|
||||
func RegisterReadiness(r *gin.Engine, db *sql.DB) {
|
||||
r.GET("/api/v1/health/ready", func(c *gin.Context) {
|
||||
|
||||
Reference in New Issue
Block a user