feat: add online payment management and checkout
Co-Authored-By: Craft Agent <agents-noreply@craft.do>
This commit is contained in:
@@ -38,3 +38,6 @@ PACKAGE_STORAGE_ROOT=
|
|||||||
|
|
||||||
# Optional independent 32-byte raw AES-GCM key; absolute path, secure backup.
|
# Optional independent 32-byte raw AES-GCM key; absolute path, secure backup.
|
||||||
LICENSE_CREDENTIAL_ENCRYPTION_KEY_FILE=
|
LICENSE_CREDENTIAL_ENCRYPTION_KEY_FILE=
|
||||||
|
# Payment channel credentials are configured in the admin UI; encryption master key stays server-side.
|
||||||
|
# Absolute path to an independent 32-byte raw random key; mount read-only and back up securely.
|
||||||
|
PAYMENT_CONFIG_ENCRYPTION_KEY_FILE=
|
||||||
|
|||||||
1
.gitignore
vendored
1
.gitignore
vendored
@@ -2,6 +2,7 @@ frontend/node_modules/
|
|||||||
frontend/dist/
|
frontend/dist/
|
||||||
backend/*.exe
|
backend/*.exe
|
||||||
.env
|
.env
|
||||||
|
secrets/
|
||||||
|
|
||||||
# Craft Agent workspace/runtime data
|
# Craft Agent workspace/runtime data
|
||||||
sessions/
|
sessions/
|
||||||
|
|||||||
@@ -7,6 +7,7 @@ import (
|
|||||||
"log/slog"
|
"log/slog"
|
||||||
"net"
|
"net"
|
||||||
"net/http"
|
"net/http"
|
||||||
|
"time"
|
||||||
|
|
||||||
_ "github.com/go-sql-driver/mysql"
|
_ "github.com/go-sql-driver/mysql"
|
||||||
"os"
|
"os"
|
||||||
@@ -15,6 +16,7 @@ import (
|
|||||||
|
|
||||||
"license-platform/backend/internal/config"
|
"license-platform/backend/internal/config"
|
||||||
"license-platform/backend/internal/httpapi"
|
"license-platform/backend/internal/httpapi"
|
||||||
|
"license-platform/backend/internal/payments"
|
||||||
)
|
)
|
||||||
|
|
||||||
func run() error {
|
func run() error {
|
||||||
@@ -30,6 +32,11 @@ func run() error {
|
|||||||
}
|
}
|
||||||
defer closeLimiter()
|
defer closeLimiter()
|
||||||
router := httpapi.NewOperationalRouter(ops)
|
router := httpapi.NewOperationalRouter(ops)
|
||||||
|
providers, err := payments.LoadFromEnv()
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("payment configuration invalid: %w", err)
|
||||||
|
}
|
||||||
|
var paymentAPI *httpapi.BusinessAPI
|
||||||
var readinessDB *sql.DB
|
var readinessDB *sql.DB
|
||||||
if dsn := os.Getenv("MYSQL_DSN"); dsn != "" {
|
if dsn := os.Getenv("MYSQL_DSN"); dsn != "" {
|
||||||
db, err := sql.Open("mysql", dsn)
|
db, err := sql.Open("mysql", dsn)
|
||||||
@@ -48,7 +55,7 @@ func run() error {
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
httpapi.RegisterBusinessWithKeyring(router, db, cfg.SigningPrivateKeyPEM, ring, cfg.CredentialEncryptionKey)
|
paymentAPI = httpapi.RegisterBusinessWithPayments(router, db, cfg.SigningPrivateKeyPEM, ring, cfg.CredentialEncryptionKey, providers, cfg.PaymentConfigEncryptionKey)
|
||||||
}
|
}
|
||||||
// Readiness is registered only on the loopback operations listener.
|
// Readiness is registered only on the loopback operations listener.
|
||||||
if err := router.SetTrustedProxies(cfg.TrustedProxies); err != nil {
|
if err := router.SetTrustedProxies(cfg.TrustedProxies); err != nil {
|
||||||
@@ -61,6 +68,22 @@ func run() error {
|
|||||||
}
|
}
|
||||||
ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
|
ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
|
||||||
defer stop()
|
defer stop()
|
||||||
|
if paymentAPI != nil {
|
||||||
|
go func() {
|
||||||
|
ticker := time.NewTicker(time.Minute)
|
||||||
|
defer ticker.Stop()
|
||||||
|
for {
|
||||||
|
select {
|
||||||
|
case <-ctx.Done():
|
||||||
|
return
|
||||||
|
case <-ticker.C:
|
||||||
|
checkCtx, cancel := context.WithTimeout(ctx, 45*time.Second)
|
||||||
|
paymentAPI.ReconcilePayments(checkCtx)
|
||||||
|
cancel()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}()
|
||||||
|
}
|
||||||
if addr := os.Getenv("METRICS_ADDR"); addr != "" {
|
if addr := os.Getenv("METRICS_ADDR"); addr != "" {
|
||||||
host, _, err := net.SplitHostPort(addr)
|
host, _, err := net.SplitHostPort(addr)
|
||||||
if err != nil || net.ParseIP(host) == nil || !net.ParseIP(host).IsLoopback() {
|
if err != nil || net.ParseIP(host) == nil || !net.ParseIP(host).IsLoopback() {
|
||||||
|
|||||||
@@ -20,6 +20,7 @@ type Config struct {
|
|||||||
ShutdownTimeout time.Duration
|
ShutdownTimeout time.Duration
|
||||||
SigningPrivateKeyPEM string
|
SigningPrivateKeyPEM string
|
||||||
CredentialEncryptionKey []byte
|
CredentialEncryptionKey []byte
|
||||||
|
PaymentConfigEncryptionKey []byte
|
||||||
}
|
}
|
||||||
|
|
||||||
func Load(getenv func(string) string) (Config, error) {
|
func Load(getenv func(string) string) (Config, error) {
|
||||||
@@ -96,6 +97,16 @@ func Load(getenv func(string) string) (Config, error) {
|
|||||||
}
|
}
|
||||||
c.CredentialEncryptionKey = data
|
c.CredentialEncryptionKey = data
|
||||||
}
|
}
|
||||||
|
if path := getenv("PAYMENT_CONFIG_ENCRYPTION_KEY_FILE"); path != "" {
|
||||||
|
if !filepath.IsAbs(path) {
|
||||||
|
return Config{}, fmt.Errorf("PAYMENT_CONFIG_ENCRYPTION_KEY_FILE must be absolute")
|
||||||
|
}
|
||||||
|
data, err := os.ReadFile(path)
|
||||||
|
if err != nil || len(data) != 32 {
|
||||||
|
return Config{}, fmt.Errorf("payment config encryption key must be exactly 32 raw bytes")
|
||||||
|
}
|
||||||
|
c.PaymentConfigEncryptionKey = data
|
||||||
|
}
|
||||||
if root := getenv("PACKAGE_STORAGE_ROOT"); root != "" {
|
if root := getenv("PACKAGE_STORAGE_ROOT"); root != "" {
|
||||||
if !filepath.IsAbs(root) {
|
if !filepath.IsAbs(root) {
|
||||||
return Config{}, fmt.Errorf("PACKAGE_STORAGE_ROOT must be absolute")
|
return Config{}, fmt.Errorf("PACKAGE_STORAGE_ROOT must be absolute")
|
||||||
|
|||||||
@@ -63,6 +63,36 @@ func TestLoadRejectsInvalid(t *testing.T) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func TestPaymentConfigKeyFile(t *testing.T) {
|
||||||
|
path := filepath.Join(t.TempDir(), "payments.key")
|
||||||
|
for _, size := range []int{31, 32, 33} {
|
||||||
|
if err := os.WriteFile(path, make([]byte, size), 0600); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
c, err := Load(func(name string) string {
|
||||||
|
if name == "PAYMENT_CONFIG_ENCRYPTION_KEY_FILE" {
|
||||||
|
return path
|
||||||
|
}
|
||||||
|
return ""
|
||||||
|
})
|
||||||
|
if size == 32 {
|
||||||
|
if err != nil || len(c.PaymentConfigEncryptionKey) != 32 || len(c.CredentialEncryptionKey) != 0 {
|
||||||
|
t.Fatal("independent payment key loading failed")
|
||||||
|
}
|
||||||
|
} else if err == nil {
|
||||||
|
t.Fatal("invalid payment key length accepted")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if _, err := Load(func(name string) string {
|
||||||
|
if name == "PAYMENT_CONFIG_ENCRYPTION_KEY_FILE" {
|
||||||
|
return "relative/payments.key"
|
||||||
|
}
|
||||||
|
return ""
|
||||||
|
}); err == nil {
|
||||||
|
t.Fatal("relative payment key accepted")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
func TestCredentialKeyFile(t *testing.T) {
|
func TestCredentialKeyFile(t *testing.T) {
|
||||||
path := filepath.Join(t.TempDir(), "credentials.key")
|
path := filepath.Join(t.TempDir(), "credentials.key")
|
||||||
for _, size := range []int{31, 32, 33} {
|
for _, size := range []int{31, 32, 33} {
|
||||||
|
|||||||
@@ -13,13 +13,17 @@ import (
|
|||||||
|
|
||||||
"github.com/gin-gonic/gin"
|
"github.com/gin-gonic/gin"
|
||||||
"golang.org/x/crypto/bcrypt"
|
"golang.org/x/crypto/bcrypt"
|
||||||
|
"license-platform/backend/internal/payments"
|
||||||
)
|
)
|
||||||
|
|
||||||
type BusinessAPI struct {
|
type BusinessAPI struct {
|
||||||
|
paymentProviders map[string]payments.Provider
|
||||||
|
paymentEnvConfigs map[string]payments.Config
|
||||||
db *sql.DB
|
db *sql.DB
|
||||||
signingPrivateKeyPEM string
|
signingPrivateKeyPEM string
|
||||||
keyring *Keyring
|
keyring *Keyring
|
||||||
credentialEncryptionKey []byte
|
credentialEncryptionKey []byte
|
||||||
|
paymentConfigEncryptionKey []byte
|
||||||
}
|
}
|
||||||
|
|
||||||
func secureSessionCookie(c *gin.Context) bool {
|
func secureSessionCookie(c *gin.Context) bool {
|
||||||
@@ -46,6 +50,23 @@ func RegisterBusinessWithKeyring(r *gin.Engine, db *sql.DB, private string, ring
|
|||||||
}
|
}
|
||||||
registerBusinessRoutes(r, a)
|
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) {
|
func registerBusinessRoutes(r *gin.Engine, a *BusinessAPI) {
|
||||||
api := r.Group("/api/v1")
|
api := r.Group("/api/v1")
|
||||||
api.POST("/auth/login", a.login)
|
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/heartbeat", a.heartbeat)
|
||||||
api.POST("/instances/:instance_id/updates/check", a.checkUpdate)
|
api.POST("/instances/:instance_id/updates/check", a.checkUpdate)
|
||||||
api.POST("/auth/logout", a.authenticated, a.logout)
|
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 := api.Group("", a.authenticated)
|
||||||
secured.GET("/me", a.me)
|
secured.GET("/me", a.me)
|
||||||
secured.GET("/admins", a.listAdmins)
|
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", 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/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.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", a.listLicenses)
|
||||||
secured.GET("/licenses/:id", a.getLicense)
|
secured.GET("/licenses/:id", a.getLicense)
|
||||||
secured.GET("/licenses/:id/instances", a.listInstances)
|
secured.GET("/licenses/:id/instances", a.listInstances)
|
||||||
|
|||||||
@@ -28,7 +28,7 @@ func TestBusinessMySQLIntegration(t *testing.T) {
|
|||||||
if err = db.Ping(); err != nil {
|
if err = db.Ping(); err != nil {
|
||||||
t.Fatal(err)
|
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 {
|
if _, err = db.Exec("DELETE FROM " + table); err != nil {
|
||||||
t.Fatal(err)
|
t.Fatal(err)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -38,6 +38,10 @@ func NewOperations(logger *slog.Logger) *Operations {
|
|||||||
}
|
}
|
||||||
func operation(path string) string {
|
func operation(path string) string {
|
||||||
switch path {
|
switch path {
|
||||||
|
case "/api/v1/payments/checkout":
|
||||||
|
return "payment_checkout"
|
||||||
|
case "/api/v1/payments/:channel/notify":
|
||||||
|
return "payment_notify"
|
||||||
case "/api/v1/portal/snapshot":
|
case "/api/v1/portal/snapshot":
|
||||||
return "login"
|
return "login"
|
||||||
case "/api/v1/auth/login":
|
case "/api/v1/auth/login":
|
||||||
@@ -117,8 +121,11 @@ func (o *Operations) Middleware() gin.HandlerFunc {
|
|||||||
c.Abort()
|
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
|
limit := 60
|
||||||
|
if op == "payment_notify" {
|
||||||
|
limit = 600
|
||||||
|
}
|
||||||
if op == "login" {
|
if op == "login" {
|
||||||
limit = 10
|
limit = 10
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -24,6 +24,8 @@ type orderRecord struct {
|
|||||||
ProductName string `json:"product_name"`
|
ProductName string `json:"product_name"`
|
||||||
AmountCents uint64 `json:"amount_cents"`
|
AmountCents uint64 `json:"amount_cents"`
|
||||||
Currency string `json:"currency"`
|
Currency string `json:"currency"`
|
||||||
|
PaymentChannel *string `json:"payment_channel"`
|
||||||
|
PaymentStatus string `json:"payment_status"`
|
||||||
Status string `json:"status"`
|
Status string `json:"status"`
|
||||||
PaymentReference *string `json:"payment_reference"`
|
PaymentReference *string `json:"payment_reference"`
|
||||||
PaidAt *time.Time `json:"paid_at"`
|
PaidAt *time.Time `json:"paid_at"`
|
||||||
@@ -32,12 +34,12 @@ type orderRecord struct {
|
|||||||
UpdatedAt time.Time `json:"updated_at"`
|
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 }
|
type orderScanner interface{ Scan(...any) error }
|
||||||
|
|
||||||
func scanOrder(s orderScanner) (o orderRecord, err 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
|
return
|
||||||
}
|
}
|
||||||
func (a *BusinessAPI) listOrders(c *gin.Context) {
|
func (a *BusinessAPI) listOrders(c *gin.Context) {
|
||||||
@@ -256,7 +258,7 @@ func (a *BusinessAPI) writeOrder(c *gin.Context, operation string) {
|
|||||||
}
|
}
|
||||||
id = uint64(n)
|
id = uint64(n)
|
||||||
case "confirm-payment":
|
case "confirm-payment":
|
||||||
if o.Status != "pending_payment" {
|
if o.Status != "pending_payment" || o.PaymentChannel != nil {
|
||||||
apiError(c, 409, "invalid_state", "只有待收款订单可确认收款")
|
apiError(c, 409, "invalid_state", "只有待收款订单可确认收款")
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
@@ -264,7 +266,7 @@ func (a *BusinessAPI) writeOrder(c *gin.Context, operation string) {
|
|||||||
apiError(c, 400, "amount_mismatch", "实际收款必须等于订单金额")
|
apiError(c, 400, "amount_mismatch", "实际收款必须等于订单金额")
|
||||||
return
|
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 {
|
if err != nil {
|
||||||
fail()
|
fail()
|
||||||
return
|
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"
|
"github.com/gin-gonic/gin"
|
||||||
)
|
)
|
||||||
|
|
||||||
const RequiredSchemaVersion = 12
|
const RequiredSchemaVersion = 15
|
||||||
|
|
||||||
func RegisterReadiness(r *gin.Engine, db *sql.DB) {
|
func RegisterReadiness(r *gin.Engine, db *sql.DB) {
|
||||||
r.GET("/api/v1/health/ready", func(c *gin.Context) {
|
r.GET("/api/v1/health/ready", func(c *gin.Context) {
|
||||||
|
|||||||
24
backend/internal/payments/README.md
Normal file
24
backend/internal/payments/README.md
Normal file
@@ -0,0 +1,24 @@
|
|||||||
|
# Payments
|
||||||
|
|
||||||
|
Use `NewProvider(channel string, config Config) (Provider, error)` to construct a channel from explicit settings without reading or modifying the process environment. `Config` is `map[string]string`, keyed by the environment variable names below. Supported channel names are `alipay` and `wechat`. `RequiredSettings(channel)` returns a fresh slice of required keys; `ConfigFromEnv(channel)` returns a snapshot of nonempty environment values. Unknown channels are rejected by `NewProvider`.
|
||||||
|
|
||||||
|
`LoadFromEnv` remains a compatibility entry point: it builds providers from `ConfigFromEnv` when any setting for that channel is present, rejects partial/invalid configurations, and returns no provider when all its settings are absent. No constructor creates fake credentials or test payments. `NewProvider` makes no network request during validation.
|
||||||
|
|
||||||
|
## Alipay
|
||||||
|
|
||||||
|
Required: `ALIPAY_APP_ID`, `ALIPAY_SELLER_ID`, `ALIPAY_PRIVATE_KEY`, `ALIPAY_PUBLIC_KEY`, `ALIPAY_NOTIFY_URL`.
|
||||||
|
`ALIPAY_PRIVATE_KEY` and `ALIPAY_PUBLIC_KEY` accept PEM text or `@path/to/key.pem`. The notification URL must be HTTPS. `ALIPAY_ENDPOINT`, when present, must equal `https://openapi.alipay.com/gateway.do`; arbitrary gateway overrides are rejected.
|
||||||
|
|
||||||
|
The provider uses the official Alipay gateway protocol with RSA2 signing, precreate/query/close/refund, strict integer-cent parsing, merchant identity checks, and notification signature verification.
|
||||||
|
|
||||||
|
## WeChat Pay API v3
|
||||||
|
|
||||||
|
Required base settings: `WECHAT_MCH_ID`, `WECHAT_APP_ID`, `WECHAT_SERIAL_NO`, `WECHAT_PRIVATE_KEY`, `WECHAT_API_V3_KEY`, `WECHAT_NOTIFY_URL`. For new integrations, configure `WECHAT_PUBLIC_KEY_ID` (must start with `PUB_KEY_ID_`) and `WECHAT_PUBLIC_KEY`. During migration, configure `WECHAT_PLATFORM_SERIAL` and `WECHAT_PLATFORM_PUBLIC_KEY` as an additional trusted pair; both pairs may coexist and callbacks select the key by the incoming `Wechatpay-Serial` header. `WECHAT_SERIAL_NO` identifies the merchant API certificate used to sign requests, while `Wechatpay-Serial` identifies the platform verification key requested for responses. Keys accept PEM text or `@path/to/key.pem`; API v3 key is exactly 32 bytes. The notification URL must be HTTPS. `WECHAT_ENDPOINT`, when present, must equal `https://api.mch.weixin.qq.com`; arbitrary gateway overrides are rejected.
|
||||||
|
|
||||||
|
The provider uses API v3 Native endpoints and RSA-2048/SHA-256 request/response authentication, AES-256-GCM notification decryption, merchant/app/currency checks, and a five-minute notification timestamp window.
|
||||||
|
|
||||||
|
`Refund` requires an integer amount in cents. WeChat queries the original order total before refunding, so partial refunds use the correct total. Callers must provide the original merchant order number and a stable refund number; repeated calls with the same refund number are idempotent at the channel.
|
||||||
|
|
||||||
|
Notifications authenticate channel data, but the provider has no access to the order database. The business layer must compare MerchantOrderNo, AmountCents and Currency with the stored order before crediting it. Query event IDs use `query-` plus the channel transaction ID when available, otherwise the merchant order number for unpaid orders. Alipay retries reuse out_trade_no; refund retries reuse out_request_no/out_refund_no. Close returns success for an already closed order after an authenticated status query. Errors never imply a successful payment.
|
||||||
|
|
||||||
|
Run `go test ./internal/payments` and `go vet ./internal/payments` from backend. Offline tests use local RSA keys and signed HTTP fixtures; real merchant credentials and channel connectivity are still required for live acceptance.
|
||||||
330
backend/internal/payments/alipay.go
Normal file
330
backend/internal/payments/alipay.go
Normal file
@@ -0,0 +1,330 @@
|
|||||||
|
package payments
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"crypto"
|
||||||
|
"crypto/rsa"
|
||||||
|
"crypto/sha256"
|
||||||
|
"encoding/base64"
|
||||||
|
"encoding/json"
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
"math"
|
||||||
|
"net"
|
||||||
|
"net/http"
|
||||||
|
"net/url"
|
||||||
|
"sort"
|
||||||
|
"strconv"
|
||||||
|
"strings"
|
||||||
|
"time"
|
||||||
|
)
|
||||||
|
|
||||||
|
type alipay struct {
|
||||||
|
app, seller, notify string
|
||||||
|
priv *rsa.PrivateKey
|
||||||
|
alipayPub *rsa.PublicKey
|
||||||
|
endpoint string
|
||||||
|
client *http.Client
|
||||||
|
}
|
||||||
|
|
||||||
|
func newAlipayFromEnv() (Provider, error) { return NewProvider("alipay", ConfigFromEnv("alipay")) }
|
||||||
|
|
||||||
|
func newAlipay(config Config) (Provider, error) {
|
||||||
|
app, e := config.required("ALIPAY_APP_ID")
|
||||||
|
if e != nil {
|
||||||
|
return nil, e
|
||||||
|
}
|
||||||
|
seller, e := config.required("ALIPAY_SELLER_ID")
|
||||||
|
if e != nil {
|
||||||
|
return nil, e
|
||||||
|
}
|
||||||
|
notify, e := config.required("ALIPAY_NOTIFY_URL")
|
||||||
|
if e != nil {
|
||||||
|
return nil, e
|
||||||
|
}
|
||||||
|
if e = validateNotifyURL("ALIPAY_NOTIFY_URL", notify); e != nil {
|
||||||
|
return nil, e
|
||||||
|
}
|
||||||
|
pk, e := config.required("ALIPAY_PRIVATE_KEY")
|
||||||
|
if e != nil {
|
||||||
|
return nil, e
|
||||||
|
}
|
||||||
|
priv, e := privateKey(pk)
|
||||||
|
if e != nil {
|
||||||
|
return nil, e
|
||||||
|
}
|
||||||
|
pubs, e := config.required("ALIPAY_PUBLIC_KEY")
|
||||||
|
if e != nil {
|
||||||
|
return nil, e
|
||||||
|
}
|
||||||
|
pub, e := publicKey(pubs)
|
||||||
|
if e != nil {
|
||||||
|
return nil, e
|
||||||
|
}
|
||||||
|
return &alipay{app: app, seller: seller, notify: notify, priv: priv, alipayPub: pub, endpoint: alipayEndpoint, client: &http.Client{Timeout: 15 * time.Second, Transport: &http.Transport{DialContext: (&net.Dialer{Timeout: 5 * time.Second}).DialContext}}}, nil
|
||||||
|
}
|
||||||
|
func (a *alipay) call(ctx context.Context, method string, args map[string]string) (map[string]any, error) {
|
||||||
|
v := url.Values{"app_id": {a.app}, "method": {method}, "format": {"JSON"}, "charset": {"utf-8"}, "sign_type": {"RSA2"}, "timestamp": {time.Now().Format("2006-01-02 15:04:05")}, "version": {"1.0"}}
|
||||||
|
if method == "alipay.trade.precreate" {
|
||||||
|
v.Set("notify_url", a.notify)
|
||||||
|
}
|
||||||
|
for k, x := range args {
|
||||||
|
v.Set(k, x)
|
||||||
|
}
|
||||||
|
sig, e := signRSA(a.priv, canonicalValues(v, "sign"))
|
||||||
|
if e != nil {
|
||||||
|
return nil, e
|
||||||
|
}
|
||||||
|
v.Set("sign", sig)
|
||||||
|
req, e := http.NewRequestWithContext(ctx, "POST", a.endpoint, strings.NewReader(v.Encode()))
|
||||||
|
if e != nil {
|
||||||
|
return nil, e
|
||||||
|
}
|
||||||
|
req.Header.Set("Content-Type", "application/x-www-form-urlencoded;charset=utf-8")
|
||||||
|
resp, e := a.client.Do(req)
|
||||||
|
if e != nil {
|
||||||
|
return nil, e
|
||||||
|
}
|
||||||
|
defer resp.Body.Close()
|
||||||
|
raw, e := readLimited(resp.Body)
|
||||||
|
if e != nil {
|
||||||
|
return nil, e
|
||||||
|
}
|
||||||
|
var envelope map[string]json.RawMessage
|
||||||
|
if e = json.Unmarshal(raw, &envelope); e != nil {
|
||||||
|
return nil, e
|
||||||
|
}
|
||||||
|
payload := envelope[strings.ReplaceAll(method, ".", "_")+"_response"]
|
||||||
|
var signature string
|
||||||
|
if e = json.Unmarshal(envelope["sign"], &signature); e != nil {
|
||||||
|
return nil, errors.New("missing alipay response signature")
|
||||||
|
}
|
||||||
|
if e = verifyRSA(a.alipayPub, string(payload), signature); e != nil {
|
||||||
|
return nil, e
|
||||||
|
}
|
||||||
|
var out map[string]any
|
||||||
|
if e = json.Unmarshal(raw, &out); e != nil {
|
||||||
|
return nil, e
|
||||||
|
}
|
||||||
|
if resp.StatusCode/100 != 2 {
|
||||||
|
return nil, fmt.Errorf("alipay HTTP %d", resp.StatusCode)
|
||||||
|
}
|
||||||
|
return out, nil
|
||||||
|
}
|
||||||
|
func (a *alipay) verifyResponse(r map[string]any) error {
|
||||||
|
if r == nil {
|
||||||
|
return errors.New("missing alipay response")
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
func (a *alipay) Create(ctx context.Context, no string, amount int64, title string) (string, error) {
|
||||||
|
if amount <= 0 {
|
||||||
|
return "", errors.New("invalid amount")
|
||||||
|
}
|
||||||
|
raw, _ := json.Marshal(map[string]any{"out_trade_no": no, "total_amount": fmt.Sprintf("%d.%02d", amount/100, amount%100), "subject": title, "product_code": "FACE_TO_FACE_PAYMENT"})
|
||||||
|
o, e := a.call(ctx, "alipay.trade.precreate", map[string]string{"biz_content": string(raw)})
|
||||||
|
if e != nil {
|
||||||
|
return "", e
|
||||||
|
}
|
||||||
|
r, _ := o["alipay_trade_precreate_response"].(map[string]any)
|
||||||
|
if e = a.verifyResponse(r); e != nil {
|
||||||
|
return "", e
|
||||||
|
}
|
||||||
|
if r["code"] != "10000" {
|
||||||
|
return "", fmt.Errorf("alipay: %v", r["sub_msg"])
|
||||||
|
}
|
||||||
|
q, _ := r["qr_code"].(string)
|
||||||
|
if q == "" {
|
||||||
|
return "", errors.New("missing qr_code")
|
||||||
|
}
|
||||||
|
return q, nil
|
||||||
|
}
|
||||||
|
func (a *alipay) Query(ctx context.Context, no string) (Notification, error) {
|
||||||
|
raw, _ := json.Marshal(map[string]string{"out_trade_no": no})
|
||||||
|
o, e := a.call(ctx, "alipay.trade.query", map[string]string{"biz_content": string(raw)})
|
||||||
|
if e != nil {
|
||||||
|
return Notification{}, e
|
||||||
|
}
|
||||||
|
r, _ := o["alipay_trade_query_response"].(map[string]any)
|
||||||
|
if e = a.verifyResponse(r); e != nil {
|
||||||
|
return Notification{}, e
|
||||||
|
}
|
||||||
|
if r["code"] != "10000" {
|
||||||
|
return Notification{}, fmt.Errorf("alipay query: %v", r["sub_msg"])
|
||||||
|
}
|
||||||
|
if got, _ := r["out_trade_no"].(string); got != no {
|
||||||
|
return Notification{}, errors.New("merchant order mismatch")
|
||||||
|
}
|
||||||
|
n := Notification{EventID: "query-" + no, MerchantOrderNo: no, Currency: "CNY"}
|
||||||
|
n.TradeNo, _ = r["trade_no"].(string)
|
||||||
|
if n.TradeNo != "" {
|
||||||
|
n.EventID = "query-" + n.TradeNo
|
||||||
|
}
|
||||||
|
st, _ := r["trade_status"].(string)
|
||||||
|
n.Paid = st == "TRADE_SUCCESS" || st == "TRADE_FINISHED"
|
||||||
|
if v, ok := r["total_amount"].(string); ok {
|
||||||
|
n.AmountCents, e = parseAlipayAmount(v)
|
||||||
|
}
|
||||||
|
if n.Paid && (n.AmountCents <= 0 || n.TradeNo == "") {
|
||||||
|
return Notification{}, errors.New("incomplete paid query")
|
||||||
|
}
|
||||||
|
return n, e
|
||||||
|
}
|
||||||
|
func (a *alipay) Close(ctx context.Context, no string) error {
|
||||||
|
rawQuery, _ := json.Marshal(map[string]string{"out_trade_no": no})
|
||||||
|
o, e := a.call(ctx, "alipay.trade.query", map[string]string{"biz_content": string(rawQuery)})
|
||||||
|
if e != nil {
|
||||||
|
return e
|
||||||
|
}
|
||||||
|
r, _ := o["alipay_trade_query_response"].(map[string]any)
|
||||||
|
if r == nil {
|
||||||
|
return errors.New("missing close query response")
|
||||||
|
}
|
||||||
|
if r["code"] != "10000" {
|
||||||
|
return fmt.Errorf("alipay close query: %v", r["sub_code"])
|
||||||
|
}
|
||||||
|
if r["out_trade_no"] != no {
|
||||||
|
return errors.New("close identity mismatch")
|
||||||
|
}
|
||||||
|
if r["trade_status"] == "TRADE_CLOSED" {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
raw, _ := json.Marshal(map[string]string{"out_trade_no": no})
|
||||||
|
return a.simple(ctx, "alipay.trade.close", map[string]string{"biz_content": string(raw)})
|
||||||
|
}
|
||||||
|
func (a *alipay) Refund(ctx context.Context, no, refund string, amount int64) error {
|
||||||
|
if amount <= 0 {
|
||||||
|
return errors.New("invalid refund amount")
|
||||||
|
}
|
||||||
|
raw, _ := json.Marshal(map[string]any{"out_trade_no": no, "refund_amount": fmt.Sprintf("%d.%02d", amount/100, amount%100), "out_request_no": refund})
|
||||||
|
return a.simple(ctx, "alipay.trade.refund", map[string]string{"biz_content": string(raw)})
|
||||||
|
}
|
||||||
|
func (a *alipay) simple(ctx context.Context, m string, p map[string]string) error {
|
||||||
|
o, e := a.call(ctx, m, p)
|
||||||
|
if e != nil {
|
||||||
|
return e
|
||||||
|
}
|
||||||
|
var r map[string]any
|
||||||
|
for _, x := range o {
|
||||||
|
if z, ok := x.(map[string]any); ok {
|
||||||
|
r = z
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if e = a.verifyResponse(r); e != nil {
|
||||||
|
return e
|
||||||
|
}
|
||||||
|
if m == "alipay.trade.close" && r["sub_code"] == "ACQ.TRADE_HAS_CLOSE" {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
if r != nil && r["code"] != "10000" {
|
||||||
|
return fmt.Errorf("alipay: %v", r["sub_msg"])
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
func (a *alipay) Verify(req *http.Request) (Notification, error) {
|
||||||
|
if req == nil {
|
||||||
|
return Notification{}, errors.New("nil request")
|
||||||
|
}
|
||||||
|
if req.URL.RawQuery != "" {
|
||||||
|
return Notification{}, errors.New("query parameters not allowed")
|
||||||
|
}
|
||||||
|
if e := req.ParseForm(); e != nil {
|
||||||
|
return Notification{}, e
|
||||||
|
}
|
||||||
|
if hasDuplicate(req.PostForm) {
|
||||||
|
return Notification{}, errors.New("duplicate field")
|
||||||
|
}
|
||||||
|
f := req.PostForm
|
||||||
|
if f.Get("app_id") != a.app || f.Get("seller_id") != a.seller || f.Get("sign_type") != "RSA2" {
|
||||||
|
return Notification{}, errors.New("merchant identity mismatch")
|
||||||
|
}
|
||||||
|
sig := f.Get("sign")
|
||||||
|
if sig == "" {
|
||||||
|
return Notification{}, errors.New("missing sign")
|
||||||
|
}
|
||||||
|
b, e := base64.StdEncoding.DecodeString(sig)
|
||||||
|
if e != nil {
|
||||||
|
return Notification{}, e
|
||||||
|
}
|
||||||
|
m := url.Values{}
|
||||||
|
for k, v := range f {
|
||||||
|
if k != "sign" && k != "sign_type" {
|
||||||
|
m[k] = v
|
||||||
|
}
|
||||||
|
}
|
||||||
|
h := sha256.Sum256([]byte(canonicalValues(m, "")))
|
||||||
|
if e = rsa.VerifyPKCS1v15(a.alipayPub, crypto.SHA256, h[:], b); e != nil {
|
||||||
|
return Notification{}, errors.New("invalid alipay signature")
|
||||||
|
}
|
||||||
|
n := Notification{EventID: f.Get("notify_id"), MerchantOrderNo: f.Get("out_trade_no"), TradeNo: f.Get("trade_no"), Currency: "CNY", Paid: f.Get("trade_status") == "TRADE_SUCCESS" || f.Get("trade_status") == "TRADE_FINISHED"}
|
||||||
|
n.AmountCents, e = parseAlipayAmount(f.Get("total_amount"))
|
||||||
|
if e == nil && (n.AmountCents <= 0 || n.EventID == "" || n.MerchantOrderNo == "" || n.TradeNo == "") {
|
||||||
|
return Notification{}, errors.New("incomplete payment notification")
|
||||||
|
}
|
||||||
|
if c := f.Get("currency"); c != "" && c != "CNY" {
|
||||||
|
return Notification{}, errors.New("currency mismatch")
|
||||||
|
}
|
||||||
|
return n, e
|
||||||
|
}
|
||||||
|
func canonicalValues(v url.Values, skip string) string {
|
||||||
|
keys := make([]string, 0, len(v))
|
||||||
|
for k := range v {
|
||||||
|
if k != skip {
|
||||||
|
keys = append(keys, k)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
sort.Strings(keys)
|
||||||
|
p := make([]string, 0, len(keys))
|
||||||
|
for _, k := range keys {
|
||||||
|
p = append(p, k+"="+v.Get(k))
|
||||||
|
}
|
||||||
|
return strings.Join(p, "&")
|
||||||
|
}
|
||||||
|
func canonicalMap(v map[string]string) string {
|
||||||
|
u := url.Values{}
|
||||||
|
for k, x := range v {
|
||||||
|
u.Set(k, x)
|
||||||
|
}
|
||||||
|
return canonicalValues(u, "")
|
||||||
|
}
|
||||||
|
func hasDuplicate(v url.Values) bool {
|
||||||
|
for _, x := range v {
|
||||||
|
if len(x) != 1 {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
func parseAlipayAmount(s string) (int64, error) {
|
||||||
|
p := strings.Split(s, ".")
|
||||||
|
if len(p) > 2 || p[0] == "" {
|
||||||
|
return 0, errors.New("invalid amount")
|
||||||
|
}
|
||||||
|
frac := "00"
|
||||||
|
if len(p) == 2 {
|
||||||
|
if len(p[1]) < 1 || len(p[1]) > 2 {
|
||||||
|
return 0, errors.New("invalid amount")
|
||||||
|
}
|
||||||
|
frac = p[1]
|
||||||
|
if len(frac) == 1 {
|
||||||
|
frac += "0"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for _, part := range []string{p[0], frac} {
|
||||||
|
for _, r := range part {
|
||||||
|
if r < '0' || r > '9' {
|
||||||
|
return 0, errors.New("invalid amount")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
y, e := strconv.ParseInt(p[0], 10, 64)
|
||||||
|
if e != nil {
|
||||||
|
return 0, e
|
||||||
|
}
|
||||||
|
f, _ := strconv.ParseInt(frac, 10, 64)
|
||||||
|
if y > (math.MaxInt64-f)/100 {
|
||||||
|
return 0, errors.New("amount overflow")
|
||||||
|
}
|
||||||
|
return y*100 + f, nil
|
||||||
|
}
|
||||||
253
backend/internal/payments/config_test.go
Normal file
253
backend/internal/payments/config_test.go
Normal file
@@ -0,0 +1,253 @@
|
|||||||
|
package payments
|
||||||
|
|
||||||
|
import (
|
||||||
|
"crypto/x509"
|
||||||
|
"encoding/pem"
|
||||||
|
"reflect"
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
)
|
||||||
|
|
||||||
|
func testConfigs(t *testing.T) map[string]Config {
|
||||||
|
t.Helper()
|
||||||
|
merchant := testKey(t)
|
||||||
|
platform := testKey(t)
|
||||||
|
private := string(pem.EncodeToMemory(&pem.Block{Type: "PRIVATE KEY", Bytes: mustPKCS8(t, merchant)}))
|
||||||
|
public := string(pem.EncodeToMemory(&pem.Block{Type: "PUBLIC KEY", Bytes: mustPKIX(t, &platform.PublicKey)}))
|
||||||
|
return map[string]Config{
|
||||||
|
"alipay": {
|
||||||
|
"ALIPAY_APP_ID": "app", "ALIPAY_SELLER_ID": "seller", "ALIPAY_PRIVATE_KEY": private,
|
||||||
|
"ALIPAY_PUBLIC_KEY": public, "ALIPAY_NOTIFY_URL": "https://merchant.example/alipay",
|
||||||
|
},
|
||||||
|
"wechat": {
|
||||||
|
"WECHAT_MCH_ID": "merchant", "WECHAT_APP_ID": "app", "WECHAT_SERIAL_NO": "merchant-serial",
|
||||||
|
"WECHAT_PUBLIC_KEY_ID": "PUB_KEY_ID_0000000000000024101100397200000006", "WECHAT_PUBLIC_KEY": public,
|
||||||
|
"WECHAT_PLATFORM_SERIAL": "platform-serial", "WECHAT_PRIVATE_KEY": private,
|
||||||
|
"WECHAT_PLATFORM_PUBLIC_KEY": public, "WECHAT_API_V3_KEY": "01234567890123456789012345678901",
|
||||||
|
"WECHAT_NOTIFY_URL": "https://merchant.example/wechat",
|
||||||
|
},
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func mustPKCS8(t *testing.T, key any) []byte {
|
||||||
|
t.Helper()
|
||||||
|
b, err := x509.MarshalPKCS8PrivateKey(key)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
return b
|
||||||
|
}
|
||||||
|
|
||||||
|
func mustPKIX(t *testing.T, key any) []byte {
|
||||||
|
t.Helper()
|
||||||
|
b, err := x509.MarshalPKIXPublicKey(key)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
return b
|
||||||
|
}
|
||||||
|
|
||||||
|
func cloneConfig(c Config) Config {
|
||||||
|
copy := Config{}
|
||||||
|
for k, v := range c {
|
||||||
|
copy[k] = v
|
||||||
|
}
|
||||||
|
return copy
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestNewProviderExplicitConfig(t *testing.T) {
|
||||||
|
for channel, cfg := range testConfigs(t) {
|
||||||
|
t.Run(channel, func(t *testing.T) {
|
||||||
|
before := cloneConfig(cfg)
|
||||||
|
// An invalid process environment must not affect explicit construction.
|
||||||
|
for _, key := range RequiredSettings(channel) {
|
||||||
|
t.Setenv(key, "invalid environment value")
|
||||||
|
}
|
||||||
|
p, err := NewProvider(channel, cfg)
|
||||||
|
if err != nil || p == nil {
|
||||||
|
t.Fatalf("provider: %T, %v", p, err)
|
||||||
|
}
|
||||||
|
if !reflect.DeepEqual(cfg, before) {
|
||||||
|
t.Fatal("constructor modified configuration")
|
||||||
|
}
|
||||||
|
switch v := p.(type) {
|
||||||
|
case *alipay:
|
||||||
|
if v.endpoint != alipayEndpoint || v.app != cfg["ALIPAY_APP_ID"] {
|
||||||
|
t.Fatal("incorrect Alipay config")
|
||||||
|
}
|
||||||
|
case *wechat:
|
||||||
|
if v.endpoint != wechatEndpoint || v.publicKeyID != cfg["WECHAT_PUBLIC_KEY_ID"] || v.verificationKey(cfg["WECHAT_PLATFORM_SERIAL"]) == nil {
|
||||||
|
t.Fatal("incorrect WeChat config")
|
||||||
|
}
|
||||||
|
default:
|
||||||
|
t.Fatalf("unexpected provider %T", p)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestNewProviderValidation(t *testing.T) {
|
||||||
|
configs := testConfigs(t)
|
||||||
|
for channel, cfg := range configs {
|
||||||
|
t.Run(channel, func(t *testing.T) {
|
||||||
|
for _, key := range RequiredSettings(channel) {
|
||||||
|
t.Run("missing_"+key, func(t *testing.T) {
|
||||||
|
missing := cloneConfig(cfg)
|
||||||
|
delete(missing, key)
|
||||||
|
if _, err := NewProvider(channel, missing); err == nil || !strings.Contains(err.Error(), key) {
|
||||||
|
t.Fatalf("missing %s: %v", key, err)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
t.Run("blank_"+key, func(t *testing.T) {
|
||||||
|
blank := cloneConfig(cfg)
|
||||||
|
blank[key] = " \t"
|
||||||
|
if _, err := NewProvider(channel, blank); err == nil || !strings.Contains(err.Error(), key) {
|
||||||
|
t.Fatalf("blank %s: %v", key, err)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
for _, value := range []string{"http://merchant.example/notify", "javascript:alert(1)", "https://", "https://name:secret@merchant.example/notify", "https://merchant.example/notify#fragment"} {
|
||||||
|
t.Run("notify_"+value, func(t *testing.T) {
|
||||||
|
bad := cloneConfig(cfg)
|
||||||
|
bad[strings.ToUpper(channel)+"_NOTIFY_URL"] = value
|
||||||
|
if _, err := NewProvider(channel, bad); err == nil {
|
||||||
|
t.Fatalf("accepted %q", value)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
bad := cloneConfig(cfg)
|
||||||
|
bad[strings.ToUpper(channel)+"_PRIVATE_KEY"] = "invalid PEM"
|
||||||
|
if _, err := NewProvider(channel, bad); err == nil {
|
||||||
|
t.Fatal("accepted invalid RSA private key")
|
||||||
|
}
|
||||||
|
bad = cloneConfig(cfg)
|
||||||
|
publicKeyName := "ALIPAY_PUBLIC_KEY"
|
||||||
|
if channel == "wechat" {
|
||||||
|
publicKeyName = "WECHAT_PLATFORM_PUBLIC_KEY"
|
||||||
|
}
|
||||||
|
bad[publicKeyName] = "invalid PEM"
|
||||||
|
if _, err := NewProvider(channel, bad); err == nil {
|
||||||
|
t.Fatal("accepted invalid RSA public key")
|
||||||
|
}
|
||||||
|
bad = cloneConfig(cfg)
|
||||||
|
bad[strings.ToUpper(channel)+"_ENDPOINT"] = "https://attacker.example"
|
||||||
|
if _, err := NewProvider(channel, bad); err == nil {
|
||||||
|
t.Fatal("accepted custom gateway")
|
||||||
|
}
|
||||||
|
bad[strings.ToUpper(channel)+"_ENDPOINT"] = "http://127.0.0.1:8080"
|
||||||
|
if _, err := NewProvider(channel, bad); err == nil {
|
||||||
|
t.Fatal("accepted local gateway")
|
||||||
|
}
|
||||||
|
bad[strings.ToUpper(channel)+"_ENDPOINT"] = map[string]string{"alipay": alipayEndpoint, "wechat": wechatEndpoint}[channel]
|
||||||
|
if _, err := NewProvider(channel, bad); err != nil {
|
||||||
|
t.Fatalf("rejected official gateway: %v", err)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
bad := cloneConfig(configs["wechat"])
|
||||||
|
bad["WECHAT_API_V3_KEY"] = "short"
|
||||||
|
if _, err := NewProvider("wechat", bad); err == nil {
|
||||||
|
t.Fatal("accepted short API v3 key")
|
||||||
|
}
|
||||||
|
for _, channel := range []string{"", "ALIPAY", "other"} {
|
||||||
|
if _, err := NewProvider(channel, nil); err == nil {
|
||||||
|
t.Fatalf("accepted channel %q", channel)
|
||||||
|
}
|
||||||
|
if len(RequiredSettings(channel)) != 0 || len(ConfigFromEnv(channel)) != 0 {
|
||||||
|
t.Fatalf("unknown channel %q has settings", channel)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestConfigFromEnvSnapshot(t *testing.T) {
|
||||||
|
for channel, cfg := range testConfigs(t) {
|
||||||
|
t.Run(channel, func(t *testing.T) {
|
||||||
|
for key, value := range cfg {
|
||||||
|
t.Setenv(key, value)
|
||||||
|
}
|
||||||
|
endpointKey := strings.ToUpper(channel) + "_ENDPOINT"
|
||||||
|
t.Setenv(endpointKey, "https://custom.example")
|
||||||
|
first := ConfigFromEnv(channel)
|
||||||
|
if len(first) != len(cfg)+1 {
|
||||||
|
t.Fatalf("unexpected snapshot size: %d", len(first))
|
||||||
|
}
|
||||||
|
for key, value := range cfg {
|
||||||
|
if first[key] != strings.TrimSpace(value) {
|
||||||
|
t.Fatalf("incorrect %s snapshot", key)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if first[endpointKey] != "https://custom.example" {
|
||||||
|
t.Fatal("legacy endpoint missing")
|
||||||
|
}
|
||||||
|
t.Setenv(endpointKey, "")
|
||||||
|
for key := range cfg {
|
||||||
|
t.Setenv(key, "")
|
||||||
|
}
|
||||||
|
if len(ConfigFromEnv(channel)) != 0 {
|
||||||
|
t.Fatal("environment did not clear")
|
||||||
|
}
|
||||||
|
if first[endpointKey] != "https://custom.example" {
|
||||||
|
t.Fatal("snapshot mutated")
|
||||||
|
}
|
||||||
|
if _, err := NewProvider(channel, first); err == nil {
|
||||||
|
t.Fatal("custom endpoint from environment accepted")
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestWechatVerificationPairs(t *testing.T) {
|
||||||
|
base := testConfigs(t)["wechat"]
|
||||||
|
for _, mode := range []string{"public-only", "platform-only", "both", "none", "missing-public", "missing-id", "bad-id"} {
|
||||||
|
t.Run(mode, func(t *testing.T) {
|
||||||
|
cfg := cloneConfig(base)
|
||||||
|
switch mode {
|
||||||
|
case "public-only":
|
||||||
|
delete(cfg, "WECHAT_PLATFORM_SERIAL")
|
||||||
|
delete(cfg, "WECHAT_PLATFORM_PUBLIC_KEY")
|
||||||
|
case "platform-only":
|
||||||
|
delete(cfg, "WECHAT_PUBLIC_KEY_ID")
|
||||||
|
delete(cfg, "WECHAT_PUBLIC_KEY")
|
||||||
|
case "none":
|
||||||
|
delete(cfg, "WECHAT_PLATFORM_SERIAL")
|
||||||
|
delete(cfg, "WECHAT_PLATFORM_PUBLIC_KEY")
|
||||||
|
delete(cfg, "WECHAT_PUBLIC_KEY_ID")
|
||||||
|
delete(cfg, "WECHAT_PUBLIC_KEY")
|
||||||
|
case "missing-public":
|
||||||
|
delete(cfg, "WECHAT_PUBLIC_KEY")
|
||||||
|
case "missing-id":
|
||||||
|
delete(cfg, "WECHAT_PUBLIC_KEY_ID")
|
||||||
|
case "bad-id":
|
||||||
|
cfg["WECHAT_PUBLIC_KEY_ID"] = "merchant-cert"
|
||||||
|
}
|
||||||
|
_, err := NewProvider("wechat", cfg)
|
||||||
|
valid := mode == "public-only" || mode == "platform-only" || mode == "both"
|
||||||
|
if (err == nil) != valid {
|
||||||
|
t.Fatalf("unexpected configuration result: %v", err)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestRequiredSettingsIndependent(t *testing.T) {
|
||||||
|
for channel, cfg := range testConfigs(t) {
|
||||||
|
a := RequiredSettings(channel)
|
||||||
|
if channel == "wechat" {
|
||||||
|
if len(a) >= len(cfg) {
|
||||||
|
t.Fatalf("wechat optional verification settings became required")
|
||||||
|
}
|
||||||
|
} else if len(a) != len(cfg) {
|
||||||
|
t.Fatalf("%s: expected %d required settings, got %d", channel, len(cfg), len(a))
|
||||||
|
}
|
||||||
|
a[0] = "CHANGED"
|
||||||
|
b := RequiredSettings(channel)
|
||||||
|
if b[0] == "CHANGED" {
|
||||||
|
t.Fatalf("%s: shared settings slice", channel)
|
||||||
|
}
|
||||||
|
for _, key := range b {
|
||||||
|
if _, ok := cfg[key]; !ok {
|
||||||
|
t.Fatalf("%s: unknown setting %s", channel, key)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
119
backend/internal/payments/crypto.go
Normal file
119
backend/internal/payments/crypto.go
Normal file
@@ -0,0 +1,119 @@
|
|||||||
|
package payments
|
||||||
|
|
||||||
|
import (
|
||||||
|
"crypto"
|
||||||
|
"crypto/aes"
|
||||||
|
"crypto/cipher"
|
||||||
|
"crypto/rand"
|
||||||
|
"crypto/rsa"
|
||||||
|
"crypto/sha256"
|
||||||
|
"crypto/x509"
|
||||||
|
"encoding/base64"
|
||||||
|
"encoding/json"
|
||||||
|
"encoding/pem"
|
||||||
|
"errors"
|
||||||
|
"io"
|
||||||
|
"os"
|
||||||
|
"strconv"
|
||||||
|
"strings"
|
||||||
|
)
|
||||||
|
|
||||||
|
func readKey(v string) ([]byte, error) {
|
||||||
|
if strings.HasPrefix(v, "@") {
|
||||||
|
return os.ReadFile(strings.TrimPrefix(v, "@"))
|
||||||
|
}
|
||||||
|
return []byte(strings.ReplaceAll(v, "\\n", "\n")), nil
|
||||||
|
}
|
||||||
|
func privateKey(v string) (*rsa.PrivateKey, error) {
|
||||||
|
b, e := readKey(v)
|
||||||
|
if e != nil {
|
||||||
|
return nil, e
|
||||||
|
}
|
||||||
|
p, _ := pem.Decode(b)
|
||||||
|
if p == nil {
|
||||||
|
return nil, errors.New("invalid PEM private key")
|
||||||
|
}
|
||||||
|
if k, e := x509.ParsePKCS8PrivateKey(p.Bytes); e == nil {
|
||||||
|
if r, ok := k.(*rsa.PrivateKey); ok {
|
||||||
|
return r, nil
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if r, e := x509.ParsePKCS1PrivateKey(p.Bytes); e == nil {
|
||||||
|
return r, nil
|
||||||
|
}
|
||||||
|
return nil, errors.New("invalid RSA private key")
|
||||||
|
}
|
||||||
|
func publicKey(v string) (*rsa.PublicKey, error) {
|
||||||
|
b, e := readKey(v)
|
||||||
|
if e != nil {
|
||||||
|
return nil, e
|
||||||
|
}
|
||||||
|
p, _ := pem.Decode(b)
|
||||||
|
if p == nil {
|
||||||
|
return nil, errors.New("invalid PEM public key")
|
||||||
|
}
|
||||||
|
if c, e := x509.ParseCertificate(p.Bytes); e == nil {
|
||||||
|
if r, ok := c.PublicKey.(*rsa.PublicKey); ok {
|
||||||
|
return r, nil
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if k, e := x509.ParsePKIXPublicKey(p.Bytes); e == nil {
|
||||||
|
if r, ok := k.(*rsa.PublicKey); ok {
|
||||||
|
return r, nil
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return nil, errors.New("invalid RSA public key")
|
||||||
|
}
|
||||||
|
func signRSA(priv *rsa.PrivateKey, s string) (string, error) {
|
||||||
|
h := sha256.Sum256([]byte(s))
|
||||||
|
b, e := rsa.SignPKCS1v15(rand.Reader, priv, cryptoHash(), h[:])
|
||||||
|
return base64.StdEncoding.EncodeToString(b), e
|
||||||
|
}
|
||||||
|
func cryptoHash() crypto.Hash { return crypto.SHA256 }
|
||||||
|
func decryptGCM(key, nonce, ad, ct string) (string, error) {
|
||||||
|
block, e := aes.NewCipher([]byte(key))
|
||||||
|
if e != nil {
|
||||||
|
return "", e
|
||||||
|
}
|
||||||
|
g, e := cipher.NewGCM(block)
|
||||||
|
if e != nil {
|
||||||
|
return "", e
|
||||||
|
}
|
||||||
|
if len(nonce) != g.NonceSize() {
|
||||||
|
return "", errors.New("invalid GCM nonce length")
|
||||||
|
}
|
||||||
|
raw, e := base64.StdEncoding.DecodeString(ct)
|
||||||
|
if e != nil {
|
||||||
|
return "", e
|
||||||
|
}
|
||||||
|
plain, e := g.Open(nil, []byte(nonce), raw, []byte(ad))
|
||||||
|
return string(plain), e
|
||||||
|
}
|
||||||
|
func cents(v any) (int64, error) {
|
||||||
|
switch x := v.(type) {
|
||||||
|
case json.Number:
|
||||||
|
return strconv.ParseInt(string(x), 10, 64)
|
||||||
|
case string:
|
||||||
|
return strconv.ParseInt(x, 10, 64)
|
||||||
|
}
|
||||||
|
return 0, errors.New("invalid amount")
|
||||||
|
}
|
||||||
|
func verifyRSA(key *rsa.PublicKey, message, signature string) error {
|
||||||
|
b, e := base64.StdEncoding.DecodeString(signature)
|
||||||
|
if e != nil {
|
||||||
|
return e
|
||||||
|
}
|
||||||
|
h := sha256.Sum256([]byte(message))
|
||||||
|
return rsa.VerifyPKCS1v15(key, crypto.SHA256, h[:], b)
|
||||||
|
}
|
||||||
|
|
||||||
|
func readLimited(r io.Reader) ([]byte, error) {
|
||||||
|
b, e := io.ReadAll(io.LimitReader(r, (2<<20)+1))
|
||||||
|
if e != nil {
|
||||||
|
return nil, e
|
||||||
|
}
|
||||||
|
if len(b) > 2<<20 {
|
||||||
|
return nil, errors.New("payment response too large")
|
||||||
|
}
|
||||||
|
return b, nil
|
||||||
|
}
|
||||||
130
backend/internal/payments/payments.go
Normal file
130
backend/internal/payments/payments.go
Normal file
@@ -0,0 +1,130 @@
|
|||||||
|
package payments
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
"net/http"
|
||||||
|
"net/url"
|
||||||
|
"os"
|
||||||
|
"strings"
|
||||||
|
)
|
||||||
|
|
||||||
|
type Notification struct {
|
||||||
|
EventID, MerchantOrderNo, TradeNo, Currency string
|
||||||
|
AmountCents int64
|
||||||
|
Paid bool
|
||||||
|
}
|
||||||
|
type Provider interface {
|
||||||
|
Create(context.Context, string, int64, string) (string, error)
|
||||||
|
Query(context.Context, string) (Notification, error)
|
||||||
|
Verify(*http.Request) (Notification, error)
|
||||||
|
Close(context.Context, string) error
|
||||||
|
Refund(context.Context, string, string, int64) error
|
||||||
|
}
|
||||||
|
|
||||||
|
// Config holds channel settings using the documented ALIPAY_* and WECHAT_* keys.
|
||||||
|
// NewProvider reads this map synchronously and never modifies it or the process environment.
|
||||||
|
type Config map[string]string
|
||||||
|
|
||||||
|
const (
|
||||||
|
alipayEndpoint = "https://openapi.alipay.com/gateway.do"
|
||||||
|
wechatEndpoint = "https://api.mch.weixin.qq.com"
|
||||||
|
)
|
||||||
|
|
||||||
|
// RequiredSettings returns an independent slice. Unknown channels return nil.
|
||||||
|
func RequiredSettings(channel string) []string {
|
||||||
|
switch channel {
|
||||||
|
case "alipay":
|
||||||
|
return []string{"ALIPAY_APP_ID", "ALIPAY_SELLER_ID", "ALIPAY_PRIVATE_KEY", "ALIPAY_PUBLIC_KEY", "ALIPAY_NOTIFY_URL"}
|
||||||
|
case "wechat":
|
||||||
|
return []string{"WECHAT_MCH_ID", "WECHAT_APP_ID", "WECHAT_SERIAL_NO", "WECHAT_PRIVATE_KEY", "WECHAT_API_V3_KEY", "WECHAT_NOTIFY_URL"}
|
||||||
|
default:
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ConfigFromEnv returns a snapshot of the channel's nonempty settings, including
|
||||||
|
// its legacy endpoint setting. Unknown channels return an empty map.
|
||||||
|
func ConfigFromEnv(channel string) Config {
|
||||||
|
c := Config{}
|
||||||
|
keys := RequiredSettings(channel)
|
||||||
|
if len(keys) == 0 {
|
||||||
|
return c
|
||||||
|
}
|
||||||
|
if channel == "wechat" {
|
||||||
|
keys = append(keys, "WECHAT_PUBLIC_KEY_ID", "WECHAT_PUBLIC_KEY", "WECHAT_PLATFORM_SERIAL", "WECHAT_PLATFORM_PUBLIC_KEY")
|
||||||
|
}
|
||||||
|
keys = append(keys, strings.ToUpper(channel)+"_ENDPOINT")
|
||||||
|
for _, key := range keys {
|
||||||
|
if v := strings.TrimSpace(os.Getenv(key)); v != "" {
|
||||||
|
c[key] = v
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return c
|
||||||
|
}
|
||||||
|
|
||||||
|
// NewProvider validates settings without making network requests. Endpoints are
|
||||||
|
// fixed to the official production gateways; a conflicting override is rejected.
|
||||||
|
func NewProvider(channel string, config Config) (Provider, error) {
|
||||||
|
keys := RequiredSettings(channel)
|
||||||
|
if len(keys) == 0 {
|
||||||
|
return nil, fmt.Errorf("unsupported payment channel %q", channel)
|
||||||
|
}
|
||||||
|
for _, key := range keys {
|
||||||
|
if _, err := config.required(key); err != nil {
|
||||||
|
return nil, fmt.Errorf("%s: %w", channel, err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
endpoint := alipayEndpoint
|
||||||
|
if channel == "wechat" {
|
||||||
|
endpoint = wechatEndpoint
|
||||||
|
}
|
||||||
|
if override := config.value(strings.ToUpper(channel) + "_ENDPOINT"); override != "" && override != endpoint {
|
||||||
|
return nil, fmt.Errorf("%s: endpoint must be the official production gateway", channel)
|
||||||
|
}
|
||||||
|
var p Provider
|
||||||
|
var err error
|
||||||
|
switch channel {
|
||||||
|
case "alipay":
|
||||||
|
p, err = newAlipay(config)
|
||||||
|
case "wechat":
|
||||||
|
p, err = newWechat(config)
|
||||||
|
}
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("%s: %w", channel, err)
|
||||||
|
}
|
||||||
|
return p, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func LoadFromEnv() (map[string]Provider, error) {
|
||||||
|
out := map[string]Provider{}
|
||||||
|
for _, channel := range []string{"alipay", "wechat"} {
|
||||||
|
c := ConfigFromEnv(channel)
|
||||||
|
if len(c) == 0 {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
p, err := NewProvider(channel, c)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
out[channel] = p
|
||||||
|
}
|
||||||
|
return out, nil
|
||||||
|
}
|
||||||
|
func (c Config) value(key string) string { return strings.TrimSpace(c[key]) }
|
||||||
|
func (c Config) required(key string) (string, error) {
|
||||||
|
v := c.value(key)
|
||||||
|
if v == "" {
|
||||||
|
return "", errors.New("missing " + key)
|
||||||
|
}
|
||||||
|
return v, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func validateNotifyURL(key, value string) error {
|
||||||
|
u, err := url.Parse(value)
|
||||||
|
if err != nil || u.Scheme != "https" || u.Hostname() == "" || u.User != nil || u.Fragment != "" {
|
||||||
|
return fmt.Errorf("%s must be an absolute HTTPS URL without userinfo or fragment", key)
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
37
backend/internal/payments/payments_test.go
Normal file
37
backend/internal/payments/payments_test.go
Normal file
@@ -0,0 +1,37 @@
|
|||||||
|
package payments
|
||||||
|
|
||||||
|
import (
|
||||||
|
"crypto/aes"
|
||||||
|
"crypto/cipher"
|
||||||
|
"encoding/base64"
|
||||||
|
"testing"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestParseAlipayAmount(t *testing.T) {
|
||||||
|
for _, tc := range []struct {
|
||||||
|
s string
|
||||||
|
want int64
|
||||||
|
ok bool
|
||||||
|
}{{"1.50", 150, true}, {"0.01", 1, true}, {"1.5", 150, true}, {"-1.00", 0, false}, {"1.000", 0, false}, {"abc", 0, false}} {
|
||||||
|
got, e := parseAlipayAmount(tc.s)
|
||||||
|
if (e == nil) != tc.ok || e == nil && got != tc.want {
|
||||||
|
t.Fatalf("%q got %d err %v", tc.s, got, e)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
func TestDecryptGCMRejectsInvalidNonce(t *testing.T) {
|
||||||
|
if _, e := decryptGCM("01234567890123456789012345678901", "short", "", "AA=="); e == nil {
|
||||||
|
t.Fatal("expected nonce length error")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
func TestDecryptGCM(t *testing.T) {
|
||||||
|
key := []byte("01234567890123456789012345678901")
|
||||||
|
b, _ := aes.NewCipher(key)
|
||||||
|
g, _ := cipher.NewGCM(b)
|
||||||
|
nonce := []byte("nonce1234567")
|
||||||
|
ct := g.Seal(nil, nonce, []byte(`{"out_trade_no":"m-1"}`), []byte("ad"))
|
||||||
|
got, e := decryptGCM(string(key), string(nonce), "ad", base64.StdEncoding.EncodeToString(ct))
|
||||||
|
if e != nil || got == "" {
|
||||||
|
t.Fatalf("decrypt failed: %q %v", got, e)
|
||||||
|
}
|
||||||
|
}
|
||||||
250
backend/internal/payments/protocol_test.go
Normal file
250
backend/internal/payments/protocol_test.go
Normal file
@@ -0,0 +1,250 @@
|
|||||||
|
package payments
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"crypto/aes"
|
||||||
|
"crypto/cipher"
|
||||||
|
"crypto/rand"
|
||||||
|
"crypto/rsa"
|
||||||
|
"encoding/base64"
|
||||||
|
"encoding/json"
|
||||||
|
"fmt"
|
||||||
|
"net/http"
|
||||||
|
"net/http/httptest"
|
||||||
|
"net/url"
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
"time"
|
||||||
|
)
|
||||||
|
|
||||||
|
func testKey(t *testing.T) *rsa.PrivateKey {
|
||||||
|
t.Helper()
|
||||||
|
k, e := rsa.GenerateKey(rand.Reader, 2048)
|
||||||
|
if e != nil {
|
||||||
|
t.Fatal(e)
|
||||||
|
}
|
||||||
|
return k
|
||||||
|
}
|
||||||
|
func TestAlipaySignedResponse(t *testing.T) {
|
||||||
|
k := testKey(t)
|
||||||
|
for _, mode := range []string{"valid", "tamper", "unsigned"} {
|
||||||
|
t.Run(mode, func(t *testing.T) {
|
||||||
|
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
r.ParseForm()
|
||||||
|
if r.PostForm.Get("notify_url") != "https://example.com/notify" {
|
||||||
|
t.Error("notify_url missing")
|
||||||
|
}
|
||||||
|
payload := `{"code":"10000","qr_code":"https://qr.example","out_trade_no":"order"}`
|
||||||
|
sig, _ := signRSA(k, payload)
|
||||||
|
if mode == "tamper" {
|
||||||
|
payload = strings.ReplaceAll(payload, "qr.example", "evil.example")
|
||||||
|
}
|
||||||
|
if mode == "unsigned" {
|
||||||
|
sig = ""
|
||||||
|
}
|
||||||
|
fmt.Fprintf(w, `{"alipay_trade_precreate_response":%s,"sign":%q}`, payload, sig)
|
||||||
|
}))
|
||||||
|
defer srv.Close()
|
||||||
|
a := alipay{priv: k, alipayPub: &k.PublicKey, client: srv.Client(), endpoint: srv.URL, notify: "https://example.com/notify"}
|
||||||
|
_, e := a.Create(context.Background(), "order", 150, "title")
|
||||||
|
if (e == nil) != (mode == "valid") {
|
||||||
|
t.Fatalf("unexpected error %v", e)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
func TestAlipayNotification(t *testing.T) {
|
||||||
|
k := testKey(t)
|
||||||
|
a := alipay{app: "app", seller: "seller", alipayPub: &k.PublicKey}
|
||||||
|
for _, mode := range []string{"valid", "tamper", "identity", "duplicate"} {
|
||||||
|
t.Run(mode, func(t *testing.T) {
|
||||||
|
f := url.Values{"app_id": {"app"}, "seller_id": {"seller"}, "notify_id": {"evt"}, "out_trade_no": {"order"}, "trade_no": {"trade"}, "trade_status": {"TRADE_SUCCESS"}, "total_amount": {"1.5"}}
|
||||||
|
if mode == "identity" {
|
||||||
|
f.Set("seller_id", "other")
|
||||||
|
}
|
||||||
|
sig, _ := signRSA(k, canonicalValues(f, ""))
|
||||||
|
f.Set("sign_type", "RSA2")
|
||||||
|
f.Set("sign", sig)
|
||||||
|
if mode == "tamper" {
|
||||||
|
f.Set("total_amount", "9.00")
|
||||||
|
}
|
||||||
|
if mode == "duplicate" {
|
||||||
|
f.Add("total_amount", "1.5")
|
||||||
|
}
|
||||||
|
r := httptest.NewRequest("POST", "https://example.com", strings.NewReader(f.Encode()))
|
||||||
|
r.Header.Set("Content-Type", "application/x-www-form-urlencoded")
|
||||||
|
n, e := a.Verify(r)
|
||||||
|
if (e == nil) != (mode == "valid") {
|
||||||
|
t.Fatalf("unexpected error %v", e)
|
||||||
|
}
|
||||||
|
if e == nil && (!n.Paid || n.AmountCents != 150) {
|
||||||
|
t.Fatal(n)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
func TestWechatSignedQuery(t *testing.T) {
|
||||||
|
k := testKey(t)
|
||||||
|
for _, mode := range []string{"valid", "public", "unknown", "tamper", "unsigned", "identity"} {
|
||||||
|
t.Run(mode, func(t *testing.T) {
|
||||||
|
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
payload := `{"mchid":"merchant","appid":"app","out_trade_no":"order","trade_state":"NOTPAY","amount":{"total":150,"currency":"CNY"}}`
|
||||||
|
if mode == "identity" {
|
||||||
|
payload = strings.ReplaceAll(payload, "merchant", "other")
|
||||||
|
}
|
||||||
|
stamp := fmt.Sprint(time.Now().Unix())
|
||||||
|
sig, _ := signRSA(k, stamp+"\nnonce\n"+payload+"\n")
|
||||||
|
w.Header().Set("Wechatpay-Timestamp", stamp)
|
||||||
|
w.Header().Set("Wechatpay-Nonce", "nonce")
|
||||||
|
w.Header().Set("Wechatpay-Serial", "platform")
|
||||||
|
if mode == "public" || mode == "unknown" {
|
||||||
|
if r.Header.Get("Wechatpay-Serial") != "PUB_KEY_ID_test" || !strings.Contains(r.Header.Get("Authorization"), `serial_no="merchant-cert"`) {
|
||||||
|
t.Error("incorrect merchant certificate or public key request header")
|
||||||
|
}
|
||||||
|
w.Header().Set("Wechatpay-Serial", "PUB_KEY_ID_test")
|
||||||
|
if mode == "unknown" {
|
||||||
|
w.Header().Set("Wechatpay-Serial", "unknown")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if mode != "unsigned" {
|
||||||
|
w.Header().Set("Wechatpay-Signature", sig)
|
||||||
|
}
|
||||||
|
if mode == "tamper" {
|
||||||
|
payload = strings.ReplaceAll(payload, "150", "999")
|
||||||
|
}
|
||||||
|
fmt.Fprint(w, payload)
|
||||||
|
}))
|
||||||
|
defer srv.Close()
|
||||||
|
w := wechat{mchid: "merchant", appid: "app", serial: "merchant-cert", platformSerial: "platform", priv: k, platform: &k.PublicKey, client: srv.Client(), endpoint: srv.URL}
|
||||||
|
if mode == "public" || mode == "unknown" {
|
||||||
|
w.publicKeyID = "PUB_KEY_ID_test"
|
||||||
|
w.verificationKeys = map[string]*rsa.PublicKey{"PUB_KEY_ID_test": &k.PublicKey}
|
||||||
|
}
|
||||||
|
n, e := w.Query(context.Background(), "order")
|
||||||
|
if (e == nil) != (mode == "valid" || mode == "public") {
|
||||||
|
t.Fatalf("unexpected error %v", e)
|
||||||
|
}
|
||||||
|
if e == nil && n.Paid {
|
||||||
|
t.Fatal("NOTPAY marked paid")
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
func TestWechatNotification(t *testing.T) {
|
||||||
|
k := testKey(t)
|
||||||
|
key := "01234567890123456789012345678901"
|
||||||
|
public := testKey(t)
|
||||||
|
w := wechat{mchid: "merchant", appid: "app", platformSerial: "platform", platform: &k.PublicKey, key: key, verificationKeys: map[string]*rsa.PublicKey{"platform": &k.PublicKey, "PUB_KEY_ID_test": &public.PublicKey}}
|
||||||
|
for _, mode := range []string{"valid", "public", "unknown", "wrong-key", "tamper", "identity", "appid", "decrypt", "expired"} {
|
||||||
|
t.Run(mode, func(t *testing.T) {
|
||||||
|
plain := `{"mchid":"merchant","appid":"app","out_trade_no":"order","transaction_id":"trade","trade_state":"SUCCESS","amount":{"total":150,"currency":"CNY"}}`
|
||||||
|
if mode == "identity" {
|
||||||
|
plain = strings.ReplaceAll(plain, "merchant", "other")
|
||||||
|
}
|
||||||
|
if mode == "appid" {
|
||||||
|
plain = strings.ReplaceAll(plain, `"appid":"app"`, `"appid":"other"`)
|
||||||
|
}
|
||||||
|
block, _ := aes.NewCipher([]byte(key))
|
||||||
|
g, _ := cipher.NewGCM(block)
|
||||||
|
ct := g.Seal(nil, []byte("123456789012"), []byte(plain), []byte("ad"))
|
||||||
|
if mode == "decrypt" {
|
||||||
|
ct[0] ^= 1
|
||||||
|
}
|
||||||
|
obj := map[string]any{"id": "evt", "event_type": "TRANSACTION.SUCCESS", "resource": map[string]string{"algorithm": "AEAD_AES_256_GCM", "nonce": "123456789012", "associated_data": "ad", "ciphertext": base64.StdEncoding.EncodeToString(ct)}}
|
||||||
|
body, _ := json.Marshal(obj)
|
||||||
|
stamp := fmt.Sprint(time.Now().Unix())
|
||||||
|
if mode == "expired" {
|
||||||
|
stamp = "1"
|
||||||
|
}
|
||||||
|
signer := k
|
||||||
|
if mode == "public" {
|
||||||
|
signer = public
|
||||||
|
}
|
||||||
|
sig, _ := signRSA(signer, stamp+"\nnonce\n"+string(body)+"\n")
|
||||||
|
if mode == "tamper" {
|
||||||
|
body = append(body, ' ')
|
||||||
|
}
|
||||||
|
r := httptest.NewRequest("POST", "https://example.com", strings.NewReader(string(body)))
|
||||||
|
r.Header.Set("Wechatpay-Timestamp", stamp)
|
||||||
|
r.Header.Set("Wechatpay-Nonce", "nonce")
|
||||||
|
r.Header.Set("Wechatpay-Serial", "platform")
|
||||||
|
if mode == "public" || mode == "wrong-key" {
|
||||||
|
r.Header.Set("Wechatpay-Serial", "PUB_KEY_ID_test")
|
||||||
|
}
|
||||||
|
if mode == "unknown" {
|
||||||
|
r.Header.Set("Wechatpay-Serial", "unknown")
|
||||||
|
}
|
||||||
|
r.Header.Set("Wechatpay-Signature", sig)
|
||||||
|
n, e := w.Verify(r)
|
||||||
|
if (e == nil) != (mode == "valid" || mode == "public") {
|
||||||
|
t.Fatalf("unexpected error %v", e)
|
||||||
|
}
|
||||||
|
if e == nil && (!n.Paid || n.AmountCents != 150) {
|
||||||
|
t.Fatal(n)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
func TestInvalidConfig(t *testing.T) {
|
||||||
|
for _, k := range []string{"ALIPAY_APP_ID", "ALIPAY_PRIVATE_KEY", "WECHAT_MCH_ID", "WECHAT_PRIVATE_KEY"} {
|
||||||
|
t.Setenv(k, "")
|
||||||
|
}
|
||||||
|
m, e := LoadFromEnv()
|
||||||
|
if e != nil || len(m) != 0 {
|
||||||
|
t.Fatal(m, e)
|
||||||
|
}
|
||||||
|
t.Setenv("ALIPAY_APP_ID", "configured")
|
||||||
|
if _, e = LoadFromEnv(); e == nil {
|
||||||
|
t.Fatal("incomplete config accepted")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestAlreadyClosedOrders(t *testing.T) {
|
||||||
|
k := testKey(t)
|
||||||
|
t.Run("alipay", func(t *testing.T) {
|
||||||
|
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
r.ParseForm()
|
||||||
|
if r.Form.Get("method") != "alipay.trade.query" {
|
||||||
|
t.Error("unexpected close request")
|
||||||
|
}
|
||||||
|
payload := `{"code":"10000","out_trade_no":"order","trade_status":"TRADE_CLOSED"}`
|
||||||
|
sig, _ := signRSA(k, payload)
|
||||||
|
fmt.Fprintf(w, `{"alipay_trade_query_response":%s,"sign":%q}`, payload, sig)
|
||||||
|
}))
|
||||||
|
defer srv.Close()
|
||||||
|
a := alipay{priv: k, alipayPub: &k.PublicKey, client: srv.Client(), endpoint: srv.URL}
|
||||||
|
if e := a.Close(context.Background(), "order"); e != nil {
|
||||||
|
t.Fatal(e)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
t.Run("wechat", func(t *testing.T) {
|
||||||
|
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
if r.Method != "GET" {
|
||||||
|
t.Error("unexpected close request")
|
||||||
|
}
|
||||||
|
payload := `{"mchid":"merchant","out_trade_no":"order","trade_state":"CLOSED"}`
|
||||||
|
stamp := fmt.Sprint(time.Now().Unix())
|
||||||
|
sig, _ := signRSA(k, stamp+"\nnonce\n"+payload+"\n")
|
||||||
|
w.Header().Set("Wechatpay-Timestamp", stamp)
|
||||||
|
w.Header().Set("Wechatpay-Nonce", "nonce")
|
||||||
|
w.Header().Set("Wechatpay-Serial", "platform")
|
||||||
|
w.Header().Set("Wechatpay-Signature", sig)
|
||||||
|
fmt.Fprint(w, payload)
|
||||||
|
}))
|
||||||
|
defer srv.Close()
|
||||||
|
w := wechat{mchid: "merchant", priv: k, platform: &k.PublicKey, platformSerial: "platform", endpoint: srv.URL, client: srv.Client()}
|
||||||
|
if e := w.Close(context.Background(), "order"); e != nil {
|
||||||
|
t.Fatal(e)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
func TestAmountRejectsMalformedAndOverflow(t *testing.T) {
|
||||||
|
for _, s := range []string{"1x.00", "+1.00", "1.-1", "9223372036854775807.00", "1.001", "NaN", "1e2.00"} {
|
||||||
|
if _, e := parseAlipayAmount(s); e == nil {
|
||||||
|
t.Fatalf("accepted %q", s)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if _, e := cents(float64(150)); e == nil {
|
||||||
|
t.Fatal("accepted floating amount")
|
||||||
|
}
|
||||||
|
}
|
||||||
337
backend/internal/payments/wechat.go
Normal file
337
backend/internal/payments/wechat.go
Normal file
@@ -0,0 +1,337 @@
|
|||||||
|
package payments
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bytes"
|
||||||
|
"context"
|
||||||
|
"crypto"
|
||||||
|
"crypto/rand"
|
||||||
|
"crypto/rsa"
|
||||||
|
"crypto/sha256"
|
||||||
|
"encoding/base64"
|
||||||
|
"encoding/json"
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
"net"
|
||||||
|
"net/http"
|
||||||
|
"net/url"
|
||||||
|
"strconv"
|
||||||
|
"strings"
|
||||||
|
|
||||||
|
"time"
|
||||||
|
)
|
||||||
|
|
||||||
|
type wechat struct {
|
||||||
|
mchid, serial, platformSerial, appid, notify, key, endpoint string
|
||||||
|
priv *rsa.PrivateKey
|
||||||
|
platform *rsa.PublicKey
|
||||||
|
publicKeyID string
|
||||||
|
verificationKeys map[string]*rsa.PublicKey
|
||||||
|
client *http.Client
|
||||||
|
}
|
||||||
|
|
||||||
|
func newWechatFromEnv() (Provider, error) { return NewProvider("wechat", ConfigFromEnv("wechat")) }
|
||||||
|
|
||||||
|
func newWechat(config Config) (Provider, error) {
|
||||||
|
m, e := config.required("WECHAT_MCH_ID")
|
||||||
|
if e != nil {
|
||||||
|
return nil, e
|
||||||
|
}
|
||||||
|
s, e := config.required("WECHAT_SERIAL_NO")
|
||||||
|
if e != nil {
|
||||||
|
return nil, e
|
||||||
|
}
|
||||||
|
pk, e := config.required("WECHAT_PRIVATE_KEY")
|
||||||
|
if e != nil {
|
||||||
|
return nil, e
|
||||||
|
}
|
||||||
|
priv, e := privateKey(pk)
|
||||||
|
if e != nil {
|
||||||
|
return nil, e
|
||||||
|
}
|
||||||
|
platformSerial := config.value("WECHAT_PLATFORM_SERIAL")
|
||||||
|
publicKeyID := config.value("WECHAT_PUBLIC_KEY_ID")
|
||||||
|
keys := map[string]*rsa.PublicKey{}
|
||||||
|
var pub *rsa.PublicKey
|
||||||
|
for _, pair := range [][2]string{{"WECHAT_PLATFORM_SERIAL", "WECHAT_PLATFORM_PUBLIC_KEY"}, {"WECHAT_PUBLIC_KEY_ID", "WECHAT_PUBLIC_KEY"}} {
|
||||||
|
id, material := config.value(pair[0]), config.value(pair[1])
|
||||||
|
if id == "" && material == "" {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if id == "" || material == "" {
|
||||||
|
return nil, fmt.Errorf("%s and %s must be configured together", pair[0], pair[1])
|
||||||
|
}
|
||||||
|
if pair[0] == "WECHAT_PLATFORM_SERIAL" && strings.HasPrefix(id, "PUB_KEY_ID_") {
|
||||||
|
return nil, errors.New("WECHAT_PLATFORM_SERIAL must be a platform certificate serial")
|
||||||
|
}
|
||||||
|
if pair[0] == "WECHAT_PUBLIC_KEY_ID" && (!strings.HasPrefix(id, "PUB_KEY_ID_") || len(id) <= len("PUB_KEY_ID_")) {
|
||||||
|
return nil, errors.New("invalid WECHAT_PUBLIC_KEY_ID")
|
||||||
|
}
|
||||||
|
if _, exists := keys[id]; exists {
|
||||||
|
return nil, errors.New("duplicate wechat verification key identifier")
|
||||||
|
}
|
||||||
|
key, err := publicKey(material)
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("invalid %s", pair[1])
|
||||||
|
}
|
||||||
|
keys[id] = key
|
||||||
|
if pair[0] == "WECHAT_PLATFORM_SERIAL" {
|
||||||
|
pub = key
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if len(keys) == 0 {
|
||||||
|
return nil, errors.New("configure WECHAT_PUBLIC_KEY_ID and WECHAT_PUBLIC_KEY or WECHAT_PLATFORM_SERIAL and WECHAT_PLATFORM_PUBLIC_KEY")
|
||||||
|
}
|
||||||
|
k, e := config.required("WECHAT_API_V3_KEY")
|
||||||
|
if e != nil || len(k) != 32 {
|
||||||
|
return nil, errors.New("WECHAT_API_V3_KEY must be 32 bytes")
|
||||||
|
}
|
||||||
|
appid, e := config.required("WECHAT_APP_ID")
|
||||||
|
if e != nil {
|
||||||
|
return nil, e
|
||||||
|
}
|
||||||
|
notify := config.value("WECHAT_NOTIFY_URL")
|
||||||
|
if notify == "" {
|
||||||
|
return nil, errors.New("missing WECHAT_NOTIFY_URL")
|
||||||
|
}
|
||||||
|
if e = validateNotifyURL("WECHAT_NOTIFY_URL", notify); e != nil {
|
||||||
|
return nil, e
|
||||||
|
}
|
||||||
|
return &wechat{mchid: m, serial: s, platformSerial: platformSerial, appid: appid, notify: notify, key: k, priv: priv, platform: pub, publicKeyID: publicKeyID, verificationKeys: keys, endpoint: wechatEndpoint, client: &http.Client{Timeout: 15 * time.Second, Transport: &http.Transport{DialContext: (&net.Dialer{Timeout: 5 * time.Second}).DialContext}}}, nil
|
||||||
|
}
|
||||||
|
func (w *wechat) auth(method, path string, body []byte) (http.Header, error) {
|
||||||
|
ts := fmt.Sprint(time.Now().Unix())
|
||||||
|
nonce := make([]byte, 16)
|
||||||
|
if _, e := rand.Read(nonce); e != nil {
|
||||||
|
return nil, e
|
||||||
|
}
|
||||||
|
ns := base64.RawURLEncoding.EncodeToString(nonce)
|
||||||
|
message := method + "\n" + path + "\n" + ts + "\n" + ns + "\n" + string(body) + "\n"
|
||||||
|
h := sha256.Sum256([]byte(message))
|
||||||
|
sig, e := rsa.SignPKCS1v15(rand.Reader, w.priv, crypto.SHA256, h[:])
|
||||||
|
if e != nil {
|
||||||
|
return nil, e
|
||||||
|
}
|
||||||
|
v := fmt.Sprintf("WECHATPAY2-SHA256-RSA2048 mchid=\"%s\",nonce_str=\"%s\",signature=\"%s\",timestamp=\"%s\",serial_no=\"%s\"", w.mchid, ns, base64.StdEncoding.EncodeToString(sig), ts, w.serial)
|
||||||
|
return http.Header{"Authorization": {v}}, nil
|
||||||
|
}
|
||||||
|
func (w *wechat) do(ctx context.Context, method, path string, body []byte) (map[string]any, error) {
|
||||||
|
h, e := w.auth(method, path, body)
|
||||||
|
if e != nil {
|
||||||
|
return nil, e
|
||||||
|
}
|
||||||
|
req, e := http.NewRequestWithContext(ctx, method, w.endpoint+path, bytes.NewReader(body))
|
||||||
|
if e != nil {
|
||||||
|
return nil, e
|
||||||
|
}
|
||||||
|
req.Header = h
|
||||||
|
req.Header.Set("Content-Type", "application/json")
|
||||||
|
req.Header.Set("Accept", "application/json")
|
||||||
|
if w.publicKeyID != "" {
|
||||||
|
req.Header.Set("Wechatpay-Serial", w.publicKeyID)
|
||||||
|
}
|
||||||
|
resp, e := w.client.Do(req)
|
||||||
|
if e != nil {
|
||||||
|
return nil, e
|
||||||
|
}
|
||||||
|
defer resp.Body.Close()
|
||||||
|
raw, e := readLimited(resp.Body)
|
||||||
|
if e != nil {
|
||||||
|
return nil, e
|
||||||
|
}
|
||||||
|
var out map[string]any
|
||||||
|
if len(raw) > 0 {
|
||||||
|
dec := json.NewDecoder(bytes.NewReader(raw))
|
||||||
|
dec.UseNumber()
|
||||||
|
if e := dec.Decode(&out); e != nil {
|
||||||
|
return nil, e
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if resp.Header.Get("Wechatpay-Signature") == "" {
|
||||||
|
return nil, errors.New("missing wechat response signature")
|
||||||
|
}
|
||||||
|
if sig := resp.Header.Get("Wechatpay-Signature"); sig != "" {
|
||||||
|
ts, nonce := resp.Header.Get("Wechatpay-Timestamp"), resp.Header.Get("Wechatpay-Nonce")
|
||||||
|
stamp, e := strconv.ParseInt(ts, 10, 64)
|
||||||
|
if e != nil || nonce == "" || time.Since(time.Unix(stamp, 0)) > 5*time.Minute || time.Until(time.Unix(stamp, 0)) > 5*time.Minute {
|
||||||
|
return nil, errors.New("wechat response timestamp outside window")
|
||||||
|
}
|
||||||
|
serial := resp.Header.Get("Wechatpay-Serial")
|
||||||
|
key := w.verificationKey(serial)
|
||||||
|
if key == nil {
|
||||||
|
return nil, errors.New("wechat response serial mismatch")
|
||||||
|
}
|
||||||
|
b, e := base64.StdEncoding.DecodeString(sig)
|
||||||
|
if e != nil {
|
||||||
|
return nil, e
|
||||||
|
}
|
||||||
|
h := sha256.Sum256([]byte(ts + "\n" + nonce + "\n" + string(raw) + "\n"))
|
||||||
|
if e = rsa.VerifyPKCS1v15(key, crypto.SHA256, h[:], b); e != nil {
|
||||||
|
return nil, errors.New("invalid wechat response signature")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if resp.StatusCode < 200 || resp.StatusCode >= 300 {
|
||||||
|
return out, fmt.Errorf("wechat HTTP %d", resp.StatusCode)
|
||||||
|
}
|
||||||
|
return out, nil
|
||||||
|
}
|
||||||
|
func (w *wechat) Create(ctx context.Context, no string, amount int64, title string) (string, error) {
|
||||||
|
if amount <= 0 {
|
||||||
|
return "", errors.New("invalid amount")
|
||||||
|
}
|
||||||
|
b, _ := json.Marshal(map[string]any{"appid": w.appid, "mchid": w.mchid, "description": title, "out_trade_no": no, "notify_url": w.notify, "amount": map[string]any{"total": amount, "currency": "CNY"}})
|
||||||
|
o, e := w.do(ctx, "POST", "/v3/pay/transactions/native", b)
|
||||||
|
if e != nil {
|
||||||
|
return "", e
|
||||||
|
}
|
||||||
|
q, _ := o["code_url"].(string)
|
||||||
|
if q == "" {
|
||||||
|
return "", errors.New("wechat missing code_url")
|
||||||
|
}
|
||||||
|
return q, nil
|
||||||
|
}
|
||||||
|
func (w *wechat) Query(ctx context.Context, no string) (Notification, error) {
|
||||||
|
o, e := w.do(ctx, "GET", "/v3/pay/transactions/out-trade-no/"+urlPath(no)+"?mchid="+urlPath(w.mchid), nil)
|
||||||
|
if e != nil {
|
||||||
|
return Notification{}, e
|
||||||
|
}
|
||||||
|
if o["mchid"] != w.mchid || o["appid"] != w.appid || o["out_trade_no"] != no {
|
||||||
|
return Notification{}, errors.New("wechat query identity mismatch")
|
||||||
|
}
|
||||||
|
n := Notification{EventID: "query-" + no, MerchantOrderNo: no, Currency: "CNY"}
|
||||||
|
n.TradeNo, _ = o["transaction_id"].(string)
|
||||||
|
if n.TradeNo != "" {
|
||||||
|
n.EventID = "query-" + n.TradeNo
|
||||||
|
}
|
||||||
|
status, _ := o["trade_state"].(string)
|
||||||
|
n.Paid = status == "SUCCESS"
|
||||||
|
if am, ok := o["amount"].(map[string]any); ok {
|
||||||
|
if am["currency"] != "CNY" {
|
||||||
|
return Notification{}, errors.New("currency mismatch")
|
||||||
|
}
|
||||||
|
n.AmountCents, e = cents(am["total"])
|
||||||
|
if e != nil || n.AmountCents < 0 {
|
||||||
|
return Notification{}, errors.New("invalid amount")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if n.Paid && (n.AmountCents <= 0 || n.TradeNo == "") {
|
||||||
|
return Notification{}, errors.New("incomplete paid query")
|
||||||
|
}
|
||||||
|
return n, nil
|
||||||
|
}
|
||||||
|
func urlPath(s string) string {
|
||||||
|
return url.PathEscape(s)
|
||||||
|
}
|
||||||
|
func (w *wechat) Close(ctx context.Context, no string) error {
|
||||||
|
o, e := w.do(ctx, "GET", "/v3/pay/transactions/out-trade-no/"+urlPath(no)+"?mchid="+url.QueryEscape(w.mchid), nil)
|
||||||
|
if e != nil {
|
||||||
|
return e
|
||||||
|
}
|
||||||
|
if o["mchid"] != w.mchid || o["out_trade_no"] != no {
|
||||||
|
return errors.New("close identity mismatch")
|
||||||
|
}
|
||||||
|
if o["trade_state"] == "CLOSED" {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
_, e = w.do(ctx, "POST", "/v3/pay/transactions/out-trade-no/"+urlPath(no)+"/close", []byte(`{"mchid":"`+w.mchid+`"}`))
|
||||||
|
return e
|
||||||
|
}
|
||||||
|
func (w *wechat) Refund(ctx context.Context, no, refund string, amount int64) error {
|
||||||
|
original, e := w.Query(ctx, no)
|
||||||
|
if e != nil {
|
||||||
|
return e
|
||||||
|
}
|
||||||
|
if amount <= 0 || amount > original.AmountCents {
|
||||||
|
return errors.New("invalid refund amount")
|
||||||
|
}
|
||||||
|
b, _ := json.Marshal(map[string]any{"out_trade_no": no, "out_refund_no": refund, "amount": map[string]any{"refund": amount, "total": original.AmountCents, "currency": "CNY"}})
|
||||||
|
_, e = w.do(ctx, "POST", "/v3/refund/domestic/refunds", b)
|
||||||
|
return e
|
||||||
|
}
|
||||||
|
func (w *wechat) Verify(req *http.Request) (Notification, error) {
|
||||||
|
if req == nil {
|
||||||
|
return Notification{}, errors.New("nil request")
|
||||||
|
}
|
||||||
|
ts := req.Header.Get("Wechatpay-Timestamp")
|
||||||
|
nonce := req.Header.Get("Wechatpay-Nonce")
|
||||||
|
sig := req.Header.Get("Wechatpay-Signature")
|
||||||
|
serial := req.Header.Get("Wechatpay-Serial")
|
||||||
|
key := w.verificationKey(serial)
|
||||||
|
if key == nil {
|
||||||
|
return Notification{}, errors.New("wechat certificate serial mismatch")
|
||||||
|
}
|
||||||
|
stamp, e := strconv.ParseInt(ts, 10, 64)
|
||||||
|
if e != nil || time.Since(time.Unix(stamp, 0)) > 5*time.Minute || time.Until(time.Unix(stamp, 0)) > 5*time.Minute {
|
||||||
|
return Notification{}, errors.New("wechat notification timestamp outside window")
|
||||||
|
}
|
||||||
|
if sig == "" || ts == "" || nonce == "" {
|
||||||
|
return Notification{}, errors.New("missing wechat signature headers")
|
||||||
|
}
|
||||||
|
body, e := readLimited(req.Body)
|
||||||
|
if e != nil {
|
||||||
|
return Notification{}, e
|
||||||
|
}
|
||||||
|
msg := ts + "\n" + nonce + "\n" + string(body) + "\n"
|
||||||
|
raw, e := base64.StdEncoding.DecodeString(sig)
|
||||||
|
if e != nil {
|
||||||
|
return Notification{}, e
|
||||||
|
}
|
||||||
|
h := sha256.Sum256([]byte(msg))
|
||||||
|
if e = rsa.VerifyPKCS1v15(key, crypto.SHA256, h[:], raw); e != nil {
|
||||||
|
return Notification{}, errors.New("invalid wechat signature")
|
||||||
|
}
|
||||||
|
var env struct {
|
||||||
|
Id string `json:"id"`
|
||||||
|
EventType string `json:"event_type"`
|
||||||
|
Resource struct {
|
||||||
|
Algorithm string `json:"algorithm"`
|
||||||
|
Nonce string `json:"nonce"`
|
||||||
|
AssociatedData string `json:"associated_data"`
|
||||||
|
Ciphertext string `json:"ciphertext"`
|
||||||
|
} `json:"resource"`
|
||||||
|
}
|
||||||
|
if e = json.Unmarshal(body, &env); e != nil {
|
||||||
|
return Notification{}, e
|
||||||
|
}
|
||||||
|
if env.EventType != "TRANSACTION.SUCCESS" || env.Id == "" {
|
||||||
|
return Notification{}, errors.New("unexpected notification event")
|
||||||
|
}
|
||||||
|
if env.Resource.Algorithm != "AEAD_AES_256_GCM" {
|
||||||
|
return Notification{}, errors.New("unsupported wechat notification algorithm")
|
||||||
|
}
|
||||||
|
plain, e := decryptGCM(w.key, env.Resource.Nonce, env.Resource.AssociatedData, env.Resource.Ciphertext)
|
||||||
|
if e != nil {
|
||||||
|
return Notification{}, e
|
||||||
|
}
|
||||||
|
var x struct {
|
||||||
|
TransactionId string `json:"transaction_id"`
|
||||||
|
OutTradeNo string `json:"out_trade_no"`
|
||||||
|
TradeState string `json:"trade_state"`
|
||||||
|
Appid string `json:"appid"`
|
||||||
|
Amount struct {
|
||||||
|
Total int64 `json:"total"`
|
||||||
|
Currency string `json:"currency"`
|
||||||
|
} `json:"amount"`
|
||||||
|
Mchid string `json:"mchid"`
|
||||||
|
}
|
||||||
|
if e = json.Unmarshal([]byte(plain), &x); e != nil {
|
||||||
|
return Notification{}, e
|
||||||
|
}
|
||||||
|
if x.Mchid != w.mchid || (w.appid != "" && x.Appid != w.appid) || x.Amount.Currency != "CNY" || x.Amount.Total <= 0 || x.OutTradeNo == "" || x.TransactionId == "" {
|
||||||
|
return Notification{}, errors.New("wechat merchant or currency mismatch")
|
||||||
|
}
|
||||||
|
return Notification{EventID: env.Id, MerchantOrderNo: x.OutTradeNo, TradeNo: x.TransactionId, Currency: x.Amount.Currency, AmountCents: x.Amount.Total, Paid: x.TradeState == "SUCCESS"}, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// Select only explicitly configured trusted keys; never fetch a key named by a request.
|
||||||
|
func (w *wechat) verificationKey(id string) *rsa.PublicKey {
|
||||||
|
if id == "" {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
if w.verificationKeys != nil {
|
||||||
|
return w.verificationKeys[id]
|
||||||
|
}
|
||||||
|
if id == w.platformSerial {
|
||||||
|
return w.platform
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
6
backend/migrations/000013_online_payments.down.sql
Normal file
6
backend/migrations/000013_online_payments.down.sql
Normal file
@@ -0,0 +1,6 @@
|
|||||||
|
-- Destructive: back up and obtain operator approval before running.
|
||||||
|
-- Existing issued licenses remain; payment records and checkout links are removed.
|
||||||
|
DROP TABLE authorization_grant_logs;
|
||||||
|
DROP TABLE payment_notifications;
|
||||||
|
DROP TABLE payment_orders;
|
||||||
|
ALTER TABLE offline_orders DROP COLUMN payment_expires_at, DROP COLUMN payment_status, DROP COLUMN payment_channel;
|
||||||
66
backend/migrations/000013_online_payments.up.sql
Normal file
66
backend/migrations/000013_online_payments.up.sql
Normal file
@@ -0,0 +1,66 @@
|
|||||||
|
-- Explicit operator migration; startup never applies DDL.
|
||||||
|
ALTER TABLE offline_orders
|
||||||
|
ADD COLUMN payment_channel VARCHAR(16) NULL AFTER currency,
|
||||||
|
ADD COLUMN payment_status VARCHAR(32) NOT NULL DEFAULT 'unpaid' AFTER status,
|
||||||
|
ADD COLUMN payment_expires_at TIMESTAMP(6) NULL AFTER paid_at;
|
||||||
|
UPDATE offline_orders SET payment_status='paid' WHERE status IN ('paid','issued');
|
||||||
|
|
||||||
|
CREATE TABLE payment_orders (
|
||||||
|
id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
|
||||||
|
order_id BIGINT UNSIGNED NOT NULL,
|
||||||
|
merchant_order_no CHAR(32) CHARACTER SET ascii COLLATE ascii_bin NOT NULL,
|
||||||
|
channel VARCHAR(16) CHARACTER SET ascii COLLATE ascii_bin NOT NULL,
|
||||||
|
channel_trade_no VARCHAR(128) CHARACTER SET ascii COLLATE ascii_bin NULL,
|
||||||
|
amount_cents BIGINT UNSIGNED NOT NULL,
|
||||||
|
currency CHAR(3) NOT NULL DEFAULT 'CNY',
|
||||||
|
license_days INT UNSIGNED NOT NULL,
|
||||||
|
checkout_token CHAR(64) CHARACTER SET ascii COLLATE ascii_bin NOT NULL,
|
||||||
|
status VARCHAR(32) NOT NULL DEFAULT 'created',
|
||||||
|
code_url TEXT NULL,
|
||||||
|
expires_at TIMESTAMP(6) NOT NULL,
|
||||||
|
paid_at TIMESTAMP(6) NULL,
|
||||||
|
closed_at TIMESTAMP(6) NULL,
|
||||||
|
last_error VARCHAR(255) NULL,
|
||||||
|
last_queried_at TIMESTAMP(6) NULL,
|
||||||
|
created_at TIMESTAMP(6) NOT NULL DEFAULT CURRENT_TIMESTAMP(6),
|
||||||
|
updated_at TIMESTAMP(6) NOT NULL DEFAULT CURRENT_TIMESTAMP(6) ON UPDATE CURRENT_TIMESTAMP(6),
|
||||||
|
PRIMARY KEY (id),
|
||||||
|
UNIQUE KEY uq_payment_orders_order (order_id),
|
||||||
|
UNIQUE KEY uq_payment_orders_merchant_no (merchant_order_no),
|
||||||
|
UNIQUE KEY uq_payment_orders_token (checkout_token),
|
||||||
|
UNIQUE KEY uq_payment_orders_channel_trade (channel, channel_trade_no),
|
||||||
|
KEY idx_payment_orders_status (status),
|
||||||
|
CONSTRAINT fk_payment_orders_order FOREIGN KEY (order_id) REFERENCES offline_orders(id)
|
||||||
|
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
|
||||||
|
|
||||||
|
CREATE TABLE payment_notifications (
|
||||||
|
id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
|
||||||
|
channel VARCHAR(16) CHARACTER SET ascii COLLATE ascii_bin NOT NULL,
|
||||||
|
event_id VARCHAR(190) CHARACTER SET ascii COLLATE ascii_bin NOT NULL,
|
||||||
|
merchant_order_no CHAR(32) CHARACTER SET ascii COLLATE ascii_bin NOT NULL,
|
||||||
|
channel_trade_no VARCHAR(128) CHARACTER SET ascii COLLATE ascii_bin NOT NULL,
|
||||||
|
payload_digest BINARY(32) NOT NULL,
|
||||||
|
verified TINYINT(1) NOT NULL DEFAULT 1,
|
||||||
|
processed TINYINT(1) NOT NULL DEFAULT 0,
|
||||||
|
received_at TIMESTAMP(6) NOT NULL DEFAULT CURRENT_TIMESTAMP(6),
|
||||||
|
processed_at TIMESTAMP(6) NULL,
|
||||||
|
PRIMARY KEY (id),
|
||||||
|
UNIQUE KEY uq_payment_notifications_event (channel, event_id),
|
||||||
|
CONSTRAINT fk_payment_notifications_payment FOREIGN KEY (merchant_order_no) REFERENCES payment_orders(merchant_order_no)
|
||||||
|
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
|
||||||
|
|
||||||
|
CREATE TABLE authorization_grant_logs (
|
||||||
|
id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
|
||||||
|
order_id BIGINT UNSIGNED NOT NULL,
|
||||||
|
license_id BIGINT UNSIGNED NULL,
|
||||||
|
idempotency_key VARCHAR(128) CHARACTER SET ascii COLLATE ascii_bin NOT NULL,
|
||||||
|
status VARCHAR(32) NOT NULL,
|
||||||
|
error_message VARCHAR(255) NULL,
|
||||||
|
created_at TIMESTAMP(6) NOT NULL DEFAULT CURRENT_TIMESTAMP(6),
|
||||||
|
updated_at TIMESTAMP(6) NOT NULL DEFAULT CURRENT_TIMESTAMP(6) ON UPDATE CURRENT_TIMESTAMP(6),
|
||||||
|
PRIMARY KEY (id),
|
||||||
|
UNIQUE KEY uq_authorization_grant_order (order_id),
|
||||||
|
UNIQUE KEY uq_authorization_grant_key (idempotency_key),
|
||||||
|
CONSTRAINT fk_authorization_grant_order FOREIGN KEY (order_id) REFERENCES offline_orders(id),
|
||||||
|
CONSTRAINT fk_authorization_grant_license FOREIGN KEY (license_id) REFERENCES licenses(id) ON DELETE SET NULL
|
||||||
|
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
|
||||||
@@ -0,0 +1,4 @@
|
|||||||
|
ALTER TABLE payment_orders DROP FOREIGN KEY fk_payment_order_config_version;
|
||||||
|
ALTER TABLE payment_orders DROP COLUMN provider_config_version;
|
||||||
|
DROP TABLE payment_channel_configs;
|
||||||
|
DROP TABLE payment_channel_config_versions;
|
||||||
24
backend/migrations/000014_payment_channel_config.up.sql
Normal file
24
backend/migrations/000014_payment_channel_config.up.sql
Normal file
@@ -0,0 +1,24 @@
|
|||||||
|
-- Explicit operator migration; startup never applies DDL.
|
||||||
|
-- Published versions are append-only: application code only inserts versions.
|
||||||
|
CREATE TABLE payment_channel_config_versions (
|
||||||
|
channel VARCHAR(16) CHARACTER SET ascii COLLATE ascii_bin NOT NULL,
|
||||||
|
version BIGINT UNSIGNED NOT NULL,
|
||||||
|
enabled TINYINT(1) NOT NULL DEFAULT 0,
|
||||||
|
config_encrypted MEDIUMBLOB NOT NULL,
|
||||||
|
created_by BIGINT UNSIGNED NULL,
|
||||||
|
created_at TIMESTAMP(6) NOT NULL DEFAULT CURRENT_TIMESTAMP(6),
|
||||||
|
PRIMARY KEY (channel, version),
|
||||||
|
CONSTRAINT fk_payment_config_version_admin FOREIGN KEY (created_by) REFERENCES admins(id) ON DELETE SET NULL
|
||||||
|
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
|
||||||
|
|
||||||
|
CREATE TABLE payment_channel_configs (
|
||||||
|
channel VARCHAR(16) CHARACTER SET ascii COLLATE ascii_bin NOT NULL,
|
||||||
|
active_version BIGINT UNSIGNED NULL,
|
||||||
|
PRIMARY KEY (channel),
|
||||||
|
CONSTRAINT fk_payment_config_active FOREIGN KEY (channel, active_version) REFERENCES payment_channel_config_versions(channel, version)
|
||||||
|
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
|
||||||
|
INSERT INTO payment_channel_configs(channel) VALUES ('alipay'), ('wechat');
|
||||||
|
|
||||||
|
ALTER TABLE payment_orders
|
||||||
|
ADD COLUMN provider_config_version BIGINT UNSIGNED NULL AFTER channel,
|
||||||
|
ADD CONSTRAINT fk_payment_order_config_version FOREIGN KEY (channel, provider_config_version) REFERENCES payment_channel_config_versions(channel, version);
|
||||||
@@ -0,0 +1,51 @@
|
|||||||
|
-- Preserve the repaired schema-14 tables for current installations and restore
|
||||||
|
-- the retained early schema-14 table only when it can be renamed without loss.
|
||||||
|
SET @schema = DATABASE();
|
||||||
|
|
||||||
|
SET @sql = (
|
||||||
|
SELECT IF(
|
||||||
|
EXISTS (SELECT 1 FROM information_schema.table_constraints WHERE constraint_schema=@schema AND table_name='payment_orders' AND constraint_name='fk_payment_order_config_version'),
|
||||||
|
'ALTER TABLE payment_orders DROP FOREIGN KEY fk_payment_order_config_version',
|
||||||
|
'SELECT 1'
|
||||||
|
)
|
||||||
|
);
|
||||||
|
PREPARE stmt FROM @sql;
|
||||||
|
EXECUTE stmt;
|
||||||
|
DEALLOCATE PREPARE stmt;
|
||||||
|
|
||||||
|
SET @sql = (
|
||||||
|
SELECT IF(
|
||||||
|
EXISTS (SELECT 1 FROM information_schema.columns WHERE table_schema=@schema AND table_name='payment_orders' AND column_name='provider_config_version'),
|
||||||
|
'ALTER TABLE payment_orders DROP COLUMN provider_config_version',
|
||||||
|
'SELECT 1'
|
||||||
|
)
|
||||||
|
);
|
||||||
|
PREPARE stmt FROM @sql;
|
||||||
|
EXECUTE stmt;
|
||||||
|
DEALLOCATE PREPARE stmt;
|
||||||
|
|
||||||
|
SET @sql = (
|
||||||
|
SELECT IF(
|
||||||
|
EXISTS (SELECT 1 FROM information_schema.tables WHERE table_schema=@schema AND table_name='payment_channel_configs_legacy_v14')
|
||||||
|
AND EXISTS (SELECT 1 FROM information_schema.tables WHERE table_schema=@schema AND table_name='payment_channel_configs'),
|
||||||
|
'DROP TABLE payment_channel_configs',
|
||||||
|
'SELECT 1'
|
||||||
|
)
|
||||||
|
);
|
||||||
|
PREPARE stmt FROM @sql;
|
||||||
|
EXECUTE stmt;
|
||||||
|
DEALLOCATE PREPARE stmt;
|
||||||
|
|
||||||
|
SET @sql = (
|
||||||
|
SELECT IF(
|
||||||
|
EXISTS (SELECT 1 FROM information_schema.tables WHERE table_schema=@schema AND table_name='payment_channel_configs_legacy_v14')
|
||||||
|
AND NOT EXISTS (SELECT 1 FROM information_schema.tables WHERE table_schema=@schema AND table_name='payment_channel_configs'),
|
||||||
|
'RENAME TABLE payment_channel_configs_legacy_v14 TO payment_channel_configs',
|
||||||
|
'SELECT 1'
|
||||||
|
)
|
||||||
|
);
|
||||||
|
PREPARE stmt FROM @sql;
|
||||||
|
EXECUTE stmt;
|
||||||
|
DEALLOCATE PREPARE stmt;
|
||||||
|
|
||||||
|
-- Never drop immutable configuration history during this repair rollback.
|
||||||
@@ -0,0 +1,57 @@
|
|||||||
|
-- Schema 15 repairs early, incompatible schema-14 payment configuration tables.
|
||||||
|
-- The legacy table is retained verbatim and is never interpreted as active config.
|
||||||
|
SET @schema = DATABASE();
|
||||||
|
|
||||||
|
SET @sql = (
|
||||||
|
SELECT IF(
|
||||||
|
EXISTS (SELECT 1 FROM information_schema.tables WHERE table_schema=@schema AND table_name='payment_channel_configs')
|
||||||
|
AND NOT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_schema=@schema AND table_name='payment_channel_configs' AND column_name='active_version'),
|
||||||
|
'RENAME TABLE payment_channel_configs TO payment_channel_configs_legacy_v14',
|
||||||
|
'SELECT 1'
|
||||||
|
)
|
||||||
|
);
|
||||||
|
PREPARE stmt FROM @sql;
|
||||||
|
EXECUTE stmt;
|
||||||
|
DEALLOCATE PREPARE stmt;
|
||||||
|
|
||||||
|
CREATE TABLE IF NOT EXISTS payment_channel_config_versions (
|
||||||
|
channel VARCHAR(16) CHARACTER SET ascii COLLATE ascii_bin NOT NULL,
|
||||||
|
version BIGINT UNSIGNED NOT NULL,
|
||||||
|
enabled TINYINT(1) NOT NULL DEFAULT 0,
|
||||||
|
config_encrypted MEDIUMBLOB NOT NULL,
|
||||||
|
created_by BIGINT UNSIGNED NULL,
|
||||||
|
created_at TIMESTAMP(6) NOT NULL DEFAULT CURRENT_TIMESTAMP(6),
|
||||||
|
PRIMARY KEY (channel, version),
|
||||||
|
CONSTRAINT fk_payment_config_version_admin FOREIGN KEY (created_by) REFERENCES admins(id) ON DELETE SET NULL
|
||||||
|
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
|
||||||
|
|
||||||
|
CREATE TABLE IF NOT EXISTS payment_channel_configs (
|
||||||
|
channel VARCHAR(16) CHARACTER SET ascii COLLATE ascii_bin NOT NULL,
|
||||||
|
active_version BIGINT UNSIGNED NULL,
|
||||||
|
PRIMARY KEY (channel),
|
||||||
|
CONSTRAINT fk_payment_config_active FOREIGN KEY (channel, active_version) REFERENCES payment_channel_config_versions(channel, version)
|
||||||
|
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
|
||||||
|
|
||||||
|
INSERT IGNORE INTO payment_channel_configs(channel) VALUES ('alipay'), ('wechat');
|
||||||
|
|
||||||
|
SET @sql = (
|
||||||
|
SELECT IF(
|
||||||
|
NOT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_schema=@schema AND table_name='payment_orders' AND column_name='provider_config_version'),
|
||||||
|
'ALTER TABLE payment_orders ADD COLUMN provider_config_version BIGINT UNSIGNED NULL AFTER channel',
|
||||||
|
'SELECT 1'
|
||||||
|
)
|
||||||
|
);
|
||||||
|
PREPARE stmt FROM @sql;
|
||||||
|
EXECUTE stmt;
|
||||||
|
DEALLOCATE PREPARE stmt;
|
||||||
|
|
||||||
|
SET @sql = (
|
||||||
|
SELECT IF(
|
||||||
|
NOT EXISTS (SELECT 1 FROM information_schema.table_constraints WHERE constraint_schema=@schema AND table_name='payment_orders' AND constraint_name='fk_payment_order_config_version'),
|
||||||
|
'ALTER TABLE payment_orders ADD CONSTRAINT fk_payment_order_config_version FOREIGN KEY (channel, provider_config_version) REFERENCES payment_channel_config_versions(channel, version)',
|
||||||
|
'SELECT 1'
|
||||||
|
)
|
||||||
|
);
|
||||||
|
PREPARE stmt FROM @sql;
|
||||||
|
EXECUTE stmt;
|
||||||
|
DEALLOCATE PREPARE stmt;
|
||||||
@@ -1,5 +1,10 @@
|
|||||||
# MySQL migration baseline
|
# MySQL migration baseline
|
||||||
|
|
||||||
|
Schema 15 repairs installations that applied an early incompatible schema-14 `payment_channel_configs` table (`id/channel/enabled/config_json/secret_encrypted/updated_by`). It renames that table to `payment_channel_configs_legacy_v14` without interpreting or deleting its rows, then creates the immutable encrypted-version table, active pointer table, and payment-order version foreign key required by the current service. The retained legacy table is deliberately not migrated into active configuration because its values cannot be safely interpreted as the current encrypted format. Schema 15 uses metadata-guarded MySQL `PREPARE` branches so it is safe for both early schema-14 and final schema-14 installations. Its down migration removes only the repair-layer order column/foreign key and restores the retained legacy table name when possible; it does not delete the retained legacy rows or immutable version history. Apply 15 before starting a service that requires `RequiredSchemaVersion=15`, and rehearse both schema-14 shapes only on an isolated database.
|
||||||
|
|
||||||
|
Schema 14 adds encrypted immutable payment channel configuration versions, per-channel active pointers, and payment order version references. Apply schemas 13 and 14 explicitly before starting the payment configuration UI/API; startup never migrates. Provide PAYMENT_CONFIG_ENCRYPTION_KEY_FILE as an absolute path to an independent 32-byte raw random key, mounted read-only and backed up securely with the database. All API processes must use the same key. Missing key prevents configuration saves and new environment-backed payment snapshots. Retain historical versions and the startup environment merchant configuration for legacy NULL-version orders. Disabling a channel blocks new payment orders but keeps bound historical notification/query verification. Down 14 destroys configuration history and bindings: quiesce payment entry points, back up, obtain operator approval, and do not resume historical payments as environment-backed transactions. Isolated migration 14/13 down/up and configuration integration tests passed; no business database migration was performed.
|
||||||
|
|
||||||
|
|
||||||
Status: DEV schemas are implemented through version 8 (local releases and digest-object locking). Formal entitlement policy acceptance and seed data remain pending. Read-only verification on 2026-09-30: business license_platform is version=7 dirty=false; isolated license_download_260930 is version=8 dirty=false. No business database migration was executed during the deployment-delivery slice.
|
Status: DEV schemas are implemented through version 8 (local releases and digest-object locking). Formal entitlement policy acceptance and seed data remain pending. Read-only verification on 2026-09-30: business license_platform is version=7 dirty=false; isolated license_download_260930 is version=8 dirty=false. No business database migration was executed during the deployment-delivery slice.
|
||||||
|
|
||||||
## Version 007 to 008
|
## Version 007 to 008
|
||||||
|
|||||||
73
docs/online-payments.md
Normal file
73
docs/online-payments.md
Normal file
@@ -0,0 +1,73 @@
|
|||||||
|
# 在线扫码支付与自动授权
|
||||||
|
|
||||||
|
本次接入基于现有 Go/Gin/MySQL 订单服务、Vue 管理端和客户端授权协议。原业务采用 offline_orders 待收款→已收款→已发放,由管理员选择客户、产品、金额及授权起止时间。客户端门户只用实例凭据认证,且实例建立依赖已有授权;当前没有允许首次购买者登录的客户账户。产品模型也没有售价、授权套餐或续费规则。
|
||||||
|
|
||||||
|
## 本次业务范围
|
||||||
|
|
||||||
|
管理员先为已有客户建立业务订单,然后选择支付宝或微信以及授权天数,创建扫码付款链接。管理员负责订单金额与客户归属,不接受客户任意报价。客户通过不可猜测的付款链接访问独立付款页,扫码支付、轮询服务端状态,开通完成后取得授权密钥供现有客户端激活。授权有效期从支付确认时刻开始计算,天数保存在支付单,后续修改环境变量不改变订单权益。当前不是无人值守首次客户注册,也不自动激活某个既有实例。
|
||||||
|
|
||||||
|
微信新接入推荐公钥方案:配置 WECHAT_PUBLIC_KEY_ID 和 WECHAT_PUBLIC_KEY;存量平台证书方案使用 WECHAT_PLATFORM_SERIAL 和 WECHAT_PLATFORM_PUBLIC_KEY。两组可共存,基础字段必填且验签方案至少一组完整;响应和回调依据收到的 Wechatpay-Serial 精确选择已配置公钥,未知标识拒绝。Authorization 的 serial_no 始终是商户 API 证书序列号;公钥模式另外发送 Wechatpay-Serial 公钥 ID 请求头。切换以商户号为维度进行,不与新平台证书灰度轮换同时操作;配置不会自动下载证书或自动执行商户平台切换,旧订单所绑定历史版本仍须保留对应验签能力。Native 扫码下单不需要 openid,appid 必须与 mchid 在商户平台绑定;本地只能校验字段齐全,实际绑定须商户联调确认。
|
||||||
|
|
||||||
|
支付回调使用官方渠道协议验签,检查商户/应用身份,微信解密 resource。HMAC 自定义 JSON 通知不是官方支付宝/微信回调,已移除。未配置渠道的服务正常启动,但该渠道付款请求和回调返回503。配置不完整应导致启动失败,防止误接收回调。
|
||||||
|
|
||||||
|
## 数据与一致性
|
||||||
|
|
||||||
|
迁移13扩展业务订单并创建支付单、支付通知与授权流水。一个业务订单仅有一个支付单,冻结渠道、金额及授权期限。网络超时后相同商户单号重试,避免创建另一笔可重复扣款的订单。不允许在线下单后再人工确认同一订单收款。
|
||||||
|
|
||||||
|
支付成功在同一数据库事务中写许可证、更新业务订单与支付单、记录通知和授权流水及审计;任何失败回滚,渠道重试或主动查单补发。业务订单行锁及支付流水唯一约束防止重复授权。晚到的真实成功付款仍需确认,不能仅依据本地二维码期限拒绝已经扣款的通知。
|
||||||
|
|
||||||
|
原 licenses.issued_by 仍然非空,自动发放归属订单创建管理员,审计details标明 payment_channel 是实际触发者。无需把授权表管理员外键改为可空。
|
||||||
|
|
||||||
|
## 接口
|
||||||
|
|
||||||
|
- POST /api/v1/orders/:id/payment:管理员会话 + Idempotency-Key;JSON channel、license_days。返回二维码内容及 /checkout#token=... 付款链接。
|
||||||
|
- POST /api/v1/payments/checkout:JSON token。返回限定订单的支付状态和付款成功后的授权密钥。凭证不写浏览器持久存储、日志或 URL query。
|
||||||
|
- POST /api/v1/payments/alipay/notify:官方支付宝异步通知。
|
||||||
|
- POST /api/v1/payments/wechat/notify:官方微信 APIv3 通知。
|
||||||
|
- GET /api/v1/payment-channels:管理员会话查询两家渠道的启用状态、配置来源及必需配置字段名;普通字段通过白名单返回,敏感字段仅返回是否已配置。
|
||||||
|
- GET /api/v1/payment-channels/:channel:管理员读取单渠道配置。响应 data 包含 channel、enabled、configuration_source(none/environment/database)、version、effective、can_save、required_settings、fields 普通字段,以及 secret_fields: [{name, configured}];不返回密钥材料。
|
||||||
|
- PUT /api/v1/payment-channels/:channel:管理员提交 {enabled, fields, secrets}。空密钥或未提交密钥保留原值;非空值替换。成功响应使用相同的脱敏结构。前端使用带管理员会话的客户端调用。
|
||||||
|
- GET /api/v1/payment-orders:管理员查询最近100笔支付流水,包含关联订单状态、授权ID、二维码展示期限及固定异常码,不返回付款token或授权密钥。
|
||||||
|
|
||||||
|
管理端侧栏新增“支付管理”(/payments),支付宝与微信分别读取配置并展示可编辑表单。普通 fields 使用小写业务字段:app_id、seller_id(支付宝)、mch_id/serial_no/public_key_id/platform_serial(微信)、notify_url。网关 endpoint 不开放编辑,也不提交。敏感 secrets 为 private_key/public_key(支付宝)、private_key/public_key/platform_public_key/api_v3_key(微信);仅显示已配置/未配置,输入始终从空值开始,空白提交时省略该字段以保留现值。新密钥在提交后清空,失败重试替换时需重新输入;刷新与离开页面也清空密钥,不写浏览器持久存储。只复制普通字段白名单和 configured 布尔状态,禁止把返回密钥材料绑定到输入。后端可选提供 version/effective/can_save:仅在提供时展示版本、生效状态或禁用保存提示,不推断未知生效状态。
|
||||||
|
|
||||||
|
启用时前端检查必填普通字段、HTTPS 通知地址、未配置的必填密钥以及新 APIv3 密钥的 32 字节长度。保存失败显示固定的安全提示,不回显可能含敏感值的服务端错误;最终格式、权限、加密主密钥和生效校验仍由后端负责。只有 PUT 成功才提示保存成功;配置校验不代表真实交易联调通过。保存期间禁止该渠道重复提交及刷新。单渠道加载失败不影响另一渠道及支付流水。
|
||||||
|
|
||||||
|
流水仍支持最近100笔按渠道、支付状态、订单ID、商户单号或渠道交易号筛选、重置与刷新,并跳转订单页生成付款链接。筛选和每页20条的分页只作用于当前加载数据,不代表服务端全部记录。异常仅显示固定提示,不显示付款token、授权密钥或原始异常。此页面不提供退款、关单或人工补单。单渠道 GET/PUT 的前端验证使用模拟响应;服务端配置接口另已通过隔离 MySQL 集成验证,真实商户联调仍待执行。
|
||||||
|
|
||||||
|
启动后每分钟扫描最多100笔未确认支付,查询渠道真实状态;付款页主动查询至少15秒间隔,已有入口限流覆盖查单与回调。
|
||||||
|
|
||||||
|
## 配置与迁移
|
||||||
|
|
||||||
|
渠道字段见 backend/internal/payments/README.md。证书与商户私钥只保存在受保护的服务器文件或密钥管理服务。公网 HTTPS notify URL 必须可达;反向代理不能要求管理登录,也不能屏蔽支付平台请求。
|
||||||
|
|
||||||
|
业务数据库不会在启动时自动迁移。先备份并核对当前 schema version 与 dirty=false;维护窗口由运维明确执行迁移13、14,核对 schema version=14 和表结构后再部署新服务。迁移14创建 payment_channel_config_versions 不可变版本表、payment_channel_configs 当前版本指针,并新增 payment_orders.provider_config_version 与复合外键。每次后台保存插入新版本并切换指针,已发布配置内容不更新。回滚14会删除配置及支付单的版本绑定,必须先停用支付入口并备份,不能把回滚后的历史交易直接视为环境交易继续运行。回滚13会删除支付记录和付款链接,已签发授权继续存在;回滚需运维批准。测试只使用隔离数据库。
|
||||||
|
|
||||||
|
PAYMENT_CONFIG_ENCRYPTION_KEY_FILE 指向受保护的服务器密钥文件,文件必须恰好包含32个原始字节,不接受Base64文本或附加换行。此密钥独立于实例凭据加密密钥,必须在多进程部署中一致并安全备份。所有保存的普通字段和敏感字段整体使用 AES-GCM 加密,附加认证数据绑定渠道和版本。主密钥缺失时 can_save=false,PUT 返回409;enabled=true 时配置必须完整且格式有效,禁用状态允许保存不完整配置。空字符串或省略 secret 保留当前密钥,首次保存从启动时环境配置快照继承;网关固定为官方地址,接口拒绝任意网关字段。保存接口仅允许 admin,校验 Origin 与 Sec-Fetch-Site 同源并返回 no-store;审计只记录版本元数据。
|
||||||
|
|
||||||
|
新支付单必须绑定非空配置版本。未通过后台保存、仍使用环境配置的渠道,在第一次创建新支付单时加密发布环境快照并绑定版本,因此环境兼容部署也必须提供支付配置主密钥;缺失时返回409拒绝新建支付。迁移前 provider_config_version=NULL 的历史单仅使用启动时环境 Provider,后续后台保存不会替换它。启用、禁用与发布在渠道指针行上串行化;禁用阻止新订单,已有订单的二维码重试、回调验签、查单及授权仍解析绑定的历史版本。配置更新不会更改已有订单的商户身份或授权期限。
|
||||||
|
|
||||||
|
支付宝/微信通知按已绑定的历史版本逐一验证,再检查 merchant_order_no 的渠道与版本绑定,避免另一商户配置确认历史交易。回调不受当前启用开关影响,历史版本和解密主密钥必须保留。后台读取生效版本、历史查询按订单读取版本,不通过可变共享 Provider map 或进程缓存切换配置,因此多进程可及时读取已提交配置。版本数量较大时回调逐一验签会增加数据库、密钥解析和验签成本;后续可按可信通知元数据筛选候选版本,但必须保留所有历史绑定交易的验证能力。
|
||||||
|
|
||||||
|
现有 compose 的 api 只在 internal 私网,无法访问外部支付网关;实际启用渠道需给 API 提供受控出网、正确DNS和外部代理/TLS,同时注入商户密钥。不能直接沿用本地 compose 假设其可完成公网交易。
|
||||||
|
|
||||||
|
## 验证与运维
|
||||||
|
|
||||||
|
隔离 MySQL 容器 `payment-test-a32a5fdee010` 已执行迁移1–14及14、13的 down/up 往返,并通过支付事务与 HTTP 付款页集成测试:重复和并发通知、金额不符、渠道交易冲突、审计写入失败回滚后重试、在线订单拒绝人工确认,以及付款确认后取得授权密钥。容器保留供复核,凭据不写入此文档。迁移往返测试须显式设置 `PAYMENT_MIGRATION_ROUNDTRIP=1`,且只能用于可回滚的隔离数据库;常规测试不应降级业务数据库。
|
||||||
|
|
||||||
|
管理员删除未激活授权时,授权流水保留并清空许可证引用,付款页显示授权已移除并停止轮询;删除授权不会触发退款或重新签发。在线付款链接包含取授权密钥的权限,应只交给对应客户。
|
||||||
|
|
||||||
|
后台配置集成验证另覆盖真实管理员会话、非管理员与跨站请求拒绝、配置保存后生效、密文和响应不含 PEM、空或省略密钥保留、历史版本不可变、错误版本无法签发、禁用后新建支付拒绝,以及历史版本真实 RSA 签名回调成功签发。AES-GCM 测试覆盖跨渠道、跨版本、错误主密钥与密文篡改拒绝。
|
||||||
|
|
||||||
|
后端全量测试和 go vet、前端相关26项测试、类型检查与生产构建通过。Windows race 检查因工具链缺少 MinGW mingwex.lib 未执行,不视为通过。上述交易测试使用本地模拟渠道与测试 RSA 密钥验证业务一致性;真实商户、公网回调、渠道响应及小额实付仍须联调验收。
|
||||||
|
|
||||||
|
## 后续优化
|
||||||
|
|
||||||
|
1. 客户自助首次购买:增加客户账户及验证、服务端定价套餐,再创建订单;不能用已有实例凭据冒充整个客户账户。
|
||||||
|
2. 续费:明确续费是延长旧授权、创建新授权还是更换实例证书。当前实现按购买发新授权,不自动重绑实例。
|
||||||
|
3. 退款:provider 能力可实现退款,但退款审批、授权回收和已离线客户端权益策略需确定后再开放业务退款API,不能仅退款后直接删授权。
|
||||||
|
4. 对账:下载官方账单并核对交易号、金额、退款,建立差异工单;主动查单不能替代账单对账。
|
||||||
|
5. 异常恢复:新增人工核查和关单入口,区分渠道处理中、支付已完成授权待处理、退款状态,并接入失败告警。30分钟是本地二维码展示期限,不代表渠道自动关单。
|
||||||
|
6. 大规模使用:把轮询补单改为分布式任务领取/重试退避,增加支付与授权指标,二维码凭证到期及密钥轮换策略。
|
||||||
|
|
||||||
|
商户实测上线验收仍需真实凭据与公网地址:支付宝沙箱/商户测试、微信商户小额实付、回调重试、断网恢复、主动补单、退款按批准策略处理。没有真实商户联调结果不能宣称生产上线完成。
|
||||||
334
frontend/package-lock.json
generated
334
frontend/package-lock.json
generated
@@ -11,10 +11,12 @@
|
|||||||
"axios": "^1.7.9",
|
"axios": "^1.7.9",
|
||||||
"element-plus": "^2.9.4",
|
"element-plus": "^2.9.4",
|
||||||
"pinia": "^2.3.0",
|
"pinia": "^2.3.0",
|
||||||
|
"qrcode": "^1.5.4",
|
||||||
"vue": "^3.5.13",
|
"vue": "^3.5.13",
|
||||||
"vue-router": "^4.5.0"
|
"vue-router": "^4.5.0"
|
||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
|
"@types/qrcode": "^1.5.6",
|
||||||
"@vitejs/plugin-vue": "^5.2.1",
|
"@vitejs/plugin-vue": "^5.2.1",
|
||||||
"@vue/test-utils": "^2.5.1",
|
"@vue/test-utils": "^2.5.1",
|
||||||
"jsdom": "^26.1.0",
|
"jsdom": "^26.1.0",
|
||||||
@@ -1115,6 +1117,26 @@
|
|||||||
"@types/lodash": "*"
|
"@types/lodash": "*"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"node_modules/@types/node": {
|
||||||
|
"version": "26.6.5",
|
||||||
|
"resolved": "https://registry.npmmirror.com/@types/node/-/node-26.6.5.tgz",
|
||||||
|
"integrity": "sha512-uMzsv9stDdofIZBx4UGh4Z9ZgXnGC9seRDscilBcTHAeOFk67MZg/k9bWVfO+bk4qZmG+l52hRnLwUiH2LnJTg==",
|
||||||
|
"dev": true,
|
||||||
|
"license": "MIT",
|
||||||
|
"dependencies": {
|
||||||
|
"undici-types": "~8.9.0"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/@types/qrcode": {
|
||||||
|
"version": "1.5.6",
|
||||||
|
"resolved": "https://registry.npmmirror.com/@types/qrcode/-/qrcode-1.5.6.tgz",
|
||||||
|
"integrity": "sha512-te7NQcV2BOvdj2b1hCAHzAoMNuj65kNBMz0KBaxM6c3VGBOhU0dURQKOtH8CFNI/dsKkwlv32p26qYQTWoB5bw==",
|
||||||
|
"dev": true,
|
||||||
|
"license": "MIT",
|
||||||
|
"dependencies": {
|
||||||
|
"@types/node": "*"
|
||||||
|
}
|
||||||
|
},
|
||||||
"node_modules/@types/web-bluetooth": {
|
"node_modules/@types/web-bluetooth": {
|
||||||
"version": "0.0.21",
|
"version": "0.0.21",
|
||||||
"resolved": "https://registry.npmmirror.com/@types/web-bluetooth/-/web-bluetooth-0.0.21.tgz",
|
"resolved": "https://registry.npmmirror.com/@types/web-bluetooth/-/web-bluetooth-0.0.21.tgz",
|
||||||
@@ -1526,6 +1548,30 @@
|
|||||||
"dev": true,
|
"dev": true,
|
||||||
"license": "MIT"
|
"license": "MIT"
|
||||||
},
|
},
|
||||||
|
"node_modules/ansi-regex": {
|
||||||
|
"version": "5.0.1",
|
||||||
|
"resolved": "https://registry.npmmirror.com/ansi-regex/-/ansi-regex-5.0.1.tgz",
|
||||||
|
"integrity": "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==",
|
||||||
|
"license": "MIT",
|
||||||
|
"engines": {
|
||||||
|
"node": ">=8"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/ansi-styles": {
|
||||||
|
"version": "4.3.0",
|
||||||
|
"resolved": "https://registry.npmmirror.com/ansi-styles/-/ansi-styles-4.3.0.tgz",
|
||||||
|
"integrity": "sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg==",
|
||||||
|
"license": "MIT",
|
||||||
|
"dependencies": {
|
||||||
|
"color-convert": "^2.0.1"
|
||||||
|
},
|
||||||
|
"engines": {
|
||||||
|
"node": ">=8"
|
||||||
|
},
|
||||||
|
"funding": {
|
||||||
|
"url": "https://github.com/chalk/ansi-styles?sponsor=1"
|
||||||
|
}
|
||||||
|
},
|
||||||
"node_modules/assertion-error": {
|
"node_modules/assertion-error": {
|
||||||
"version": "2.0.1",
|
"version": "2.0.1",
|
||||||
"resolved": "https://registry.npmmirror.com/assertion-error/-/assertion-error-2.0.1.tgz",
|
"resolved": "https://registry.npmmirror.com/assertion-error/-/assertion-error-2.0.1.tgz",
|
||||||
@@ -1600,6 +1646,15 @@
|
|||||||
"node": ">= 0.4"
|
"node": ">= 0.4"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"node_modules/camelcase": {
|
||||||
|
"version": "5.3.1",
|
||||||
|
"resolved": "https://registry.npmmirror.com/camelcase/-/camelcase-5.3.1.tgz",
|
||||||
|
"integrity": "sha512-L28STB170nwWS63UjtlEOE3dldQApaJXZkOI1uMFfzf3rRuPegHaHesyee+YxQ+W6SvRDQV6UrdOdRiR153wJg==",
|
||||||
|
"license": "MIT",
|
||||||
|
"engines": {
|
||||||
|
"node": ">=6"
|
||||||
|
}
|
||||||
|
},
|
||||||
"node_modules/chai": {
|
"node_modules/chai": {
|
||||||
"version": "5.3.3",
|
"version": "5.3.3",
|
||||||
"resolved": "https://registry.npmmirror.com/chai/-/chai-5.3.3.tgz",
|
"resolved": "https://registry.npmmirror.com/chai/-/chai-5.3.3.tgz",
|
||||||
@@ -1627,6 +1682,35 @@
|
|||||||
"node": ">= 16"
|
"node": ">= 16"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"node_modules/cliui": {
|
||||||
|
"version": "6.0.0",
|
||||||
|
"resolved": "https://registry.npmmirror.com/cliui/-/cliui-6.0.0.tgz",
|
||||||
|
"integrity": "sha512-t6wbgtoCXvAzst7QgXxJYqPt0usEfbgQdftEPbLL/cvv6HPE5VgvqCuAIDR0NgU52ds6rFwqrgakNLrHEjCbrQ==",
|
||||||
|
"license": "ISC",
|
||||||
|
"dependencies": {
|
||||||
|
"string-width": "^4.2.0",
|
||||||
|
"strip-ansi": "^6.0.0",
|
||||||
|
"wrap-ansi": "^6.2.0"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/color-convert": {
|
||||||
|
"version": "2.0.1",
|
||||||
|
"resolved": "https://registry.npmmirror.com/color-convert/-/color-convert-2.0.1.tgz",
|
||||||
|
"integrity": "sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ==",
|
||||||
|
"license": "MIT",
|
||||||
|
"dependencies": {
|
||||||
|
"color-name": "~1.1.4"
|
||||||
|
},
|
||||||
|
"engines": {
|
||||||
|
"node": ">=7.0.0"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/color-name": {
|
||||||
|
"version": "1.1.4",
|
||||||
|
"resolved": "https://registry.npmmirror.com/color-name/-/color-name-1.1.4.tgz",
|
||||||
|
"integrity": "sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==",
|
||||||
|
"license": "MIT"
|
||||||
|
},
|
||||||
"node_modules/combined-stream": {
|
"node_modules/combined-stream": {
|
||||||
"version": "1.0.8",
|
"version": "1.0.8",
|
||||||
"resolved": "https://registry.npmmirror.com/combined-stream/-/combined-stream-1.0.8.tgz",
|
"resolved": "https://registry.npmmirror.com/combined-stream/-/combined-stream-1.0.8.tgz",
|
||||||
@@ -1724,6 +1808,15 @@
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"node_modules/decamelize": {
|
||||||
|
"version": "1.2.0",
|
||||||
|
"resolved": "https://registry.npmmirror.com/decamelize/-/decamelize-1.2.0.tgz",
|
||||||
|
"integrity": "sha512-z2S+W9X73hAUUki+N+9Za2lBlun89zigOyGrsax+KUQ6wKW4ZoWpEYBkGhQjwAjjDCkWxhY0VKEhk8wzY7F5cA==",
|
||||||
|
"license": "MIT",
|
||||||
|
"engines": {
|
||||||
|
"node": ">=0.10.0"
|
||||||
|
}
|
||||||
|
},
|
||||||
"node_modules/decimal.js": {
|
"node_modules/decimal.js": {
|
||||||
"version": "10.6.0",
|
"version": "10.6.0",
|
||||||
"resolved": "https://registry.npmmirror.com/decimal.js/-/decimal.js-10.6.0.tgz",
|
"resolved": "https://registry.npmmirror.com/decimal.js/-/decimal.js-10.6.0.tgz",
|
||||||
@@ -1750,6 +1843,12 @@
|
|||||||
"node": ">=0.4.0"
|
"node": ">=0.4.0"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"node_modules/dijkstrajs": {
|
||||||
|
"version": "1.0.3",
|
||||||
|
"resolved": "https://registry.npmmirror.com/dijkstrajs/-/dijkstrajs-1.0.3.tgz",
|
||||||
|
"integrity": "sha512-qiSlmBq9+BCdCA/L46dw8Uy93mloxsPSbwnm5yrKn2vMPiy8KyAskTF6zuV/j5BMsmOGZDPs7KjU+mjb670kfA==",
|
||||||
|
"license": "MIT"
|
||||||
|
},
|
||||||
"node_modules/dunder-proto": {
|
"node_modules/dunder-proto": {
|
||||||
"version": "1.0.1",
|
"version": "1.0.1",
|
||||||
"resolved": "https://registry.npmmirror.com/dunder-proto/-/dunder-proto-1.0.1.tgz",
|
"resolved": "https://registry.npmmirror.com/dunder-proto/-/dunder-proto-1.0.1.tgz",
|
||||||
@@ -1848,6 +1947,12 @@
|
|||||||
"vue": "^3.3.7"
|
"vue": "^3.3.7"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"node_modules/emoji-regex": {
|
||||||
|
"version": "8.0.0",
|
||||||
|
"resolved": "https://registry.npmmirror.com/emoji-regex/-/emoji-regex-8.0.0.tgz",
|
||||||
|
"integrity": "sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A==",
|
||||||
|
"license": "MIT"
|
||||||
|
},
|
||||||
"node_modules/entities": {
|
"node_modules/entities": {
|
||||||
"version": "7.0.1",
|
"version": "7.0.1",
|
||||||
"resolved": "https://registry.npmmirror.com/entities/-/entities-7.0.1.tgz",
|
"resolved": "https://registry.npmmirror.com/entities/-/entities-7.0.1.tgz",
|
||||||
@@ -1988,6 +2093,19 @@
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"node_modules/find-up": {
|
||||||
|
"version": "4.1.0",
|
||||||
|
"resolved": "https://registry.npmmirror.com/find-up/-/find-up-4.1.0.tgz",
|
||||||
|
"integrity": "sha512-PpOwAdQ/YlXQ2vj8a3h8IipDuYRi3wceVQQGYWxNINccq40Anw7BlsEXCMbt1Zt+OLA6Fq9suIpIWD0OsnISlw==",
|
||||||
|
"license": "MIT",
|
||||||
|
"dependencies": {
|
||||||
|
"locate-path": "^5.0.0",
|
||||||
|
"path-exists": "^4.0.0"
|
||||||
|
},
|
||||||
|
"engines": {
|
||||||
|
"node": ">=8"
|
||||||
|
}
|
||||||
|
},
|
||||||
"node_modules/follow-redirects": {
|
"node_modules/follow-redirects": {
|
||||||
"version": "1.16.0",
|
"version": "1.16.0",
|
||||||
"resolved": "https://registry.npmmirror.com/follow-redirects/-/follow-redirects-1.16.0.tgz",
|
"resolved": "https://registry.npmmirror.com/follow-redirects/-/follow-redirects-1.16.0.tgz",
|
||||||
@@ -2048,6 +2166,15 @@
|
|||||||
"url": "https://github.com/sponsors/ljharb"
|
"url": "https://github.com/sponsors/ljharb"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"node_modules/get-caller-file": {
|
||||||
|
"version": "2.0.5",
|
||||||
|
"resolved": "https://registry.npmmirror.com/get-caller-file/-/get-caller-file-2.0.5.tgz",
|
||||||
|
"integrity": "sha512-DyFP3BM/3YHTQOCUL/w0OZHR0lpKeGrxotcHWcqNEdnltqFwXVfhEBQ94eIo34AfQpo0rGki4cyIiftY06h2Fg==",
|
||||||
|
"license": "ISC",
|
||||||
|
"engines": {
|
||||||
|
"node": "6.* || 8.* || >= 10.*"
|
||||||
|
}
|
||||||
|
},
|
||||||
"node_modules/get-intrinsic": {
|
"node_modules/get-intrinsic": {
|
||||||
"version": "1.3.0",
|
"version": "1.3.0",
|
||||||
"resolved": "https://registry.npmmirror.com/get-intrinsic/-/get-intrinsic-1.3.0.tgz",
|
"resolved": "https://registry.npmmirror.com/get-intrinsic/-/get-intrinsic-1.3.0.tgz",
|
||||||
@@ -2273,6 +2400,15 @@
|
|||||||
"dev": true,
|
"dev": true,
|
||||||
"license": "ISC"
|
"license": "ISC"
|
||||||
},
|
},
|
||||||
|
"node_modules/is-fullwidth-code-point": {
|
||||||
|
"version": "3.0.0",
|
||||||
|
"resolved": "https://registry.npmmirror.com/is-fullwidth-code-point/-/is-fullwidth-code-point-3.0.0.tgz",
|
||||||
|
"integrity": "sha512-zymm5+u+sCsSWyD9qNaejV3DFvhCKclKdizYaJUuHA83RLjb7nSuGnddCHGv0hk+KY7BMAlsWeK4Ueg6EV6XQg==",
|
||||||
|
"license": "MIT",
|
||||||
|
"engines": {
|
||||||
|
"node": ">=8"
|
||||||
|
}
|
||||||
|
},
|
||||||
"node_modules/is-potential-custom-element-name": {
|
"node_modules/is-potential-custom-element-name": {
|
||||||
"version": "1.0.1",
|
"version": "1.0.1",
|
||||||
"resolved": "https://registry.npmmirror.com/is-potential-custom-element-name/-/is-potential-custom-element-name-1.0.1.tgz",
|
"resolved": "https://registry.npmmirror.com/is-potential-custom-element-name/-/is-potential-custom-element-name-1.0.1.tgz",
|
||||||
@@ -2380,6 +2516,18 @@
|
|||||||
"node": ">= 14"
|
"node": ">= 14"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"node_modules/locate-path": {
|
||||||
|
"version": "5.0.0",
|
||||||
|
"resolved": "https://registry.npmmirror.com/locate-path/-/locate-path-5.0.0.tgz",
|
||||||
|
"integrity": "sha512-t7hw9pI+WvuwNJXwk5zVHpyhIqzg2qTlklJOf0mVxGSbe3Fp2VieZcduNYjaLDoy6p9uGpQEGWG87WpMKlNq8g==",
|
||||||
|
"license": "MIT",
|
||||||
|
"dependencies": {
|
||||||
|
"p-locate": "^4.1.0"
|
||||||
|
},
|
||||||
|
"engines": {
|
||||||
|
"node": ">=8"
|
||||||
|
}
|
||||||
|
},
|
||||||
"node_modules/lodash": {
|
"node_modules/lodash": {
|
||||||
"version": "4.18.1",
|
"version": "4.18.1",
|
||||||
"resolved": "https://registry.npmmirror.com/lodash/-/lodash-4.18.1.tgz",
|
"resolved": "https://registry.npmmirror.com/lodash/-/lodash-4.18.1.tgz",
|
||||||
@@ -2548,6 +2696,42 @@
|
|||||||
"dev": true,
|
"dev": true,
|
||||||
"license": "MIT"
|
"license": "MIT"
|
||||||
},
|
},
|
||||||
|
"node_modules/p-limit": {
|
||||||
|
"version": "2.3.0",
|
||||||
|
"resolved": "https://registry.npmmirror.com/p-limit/-/p-limit-2.3.0.tgz",
|
||||||
|
"integrity": "sha512-//88mFWSJx8lxCzwdAABTJL2MyWB12+eIY7MDL2SqLmAkeKU9qxRvWuSyTjm3FUmpBEMuFfckAIqEaVGUDxb6w==",
|
||||||
|
"license": "MIT",
|
||||||
|
"dependencies": {
|
||||||
|
"p-try": "^2.0.0"
|
||||||
|
},
|
||||||
|
"engines": {
|
||||||
|
"node": ">=6"
|
||||||
|
},
|
||||||
|
"funding": {
|
||||||
|
"url": "https://github.com/sponsors/sindresorhus"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/p-locate": {
|
||||||
|
"version": "4.1.0",
|
||||||
|
"resolved": "https://registry.npmmirror.com/p-locate/-/p-locate-4.1.0.tgz",
|
||||||
|
"integrity": "sha512-R79ZZ/0wAxKGu3oYMlz8jy/kbhsNrS7SKZ7PxEHBgJ5+F2mtFW2fK2cOtBh1cHYkQsbzFV7I+EoRKe6Yt0oK7A==",
|
||||||
|
"license": "MIT",
|
||||||
|
"dependencies": {
|
||||||
|
"p-limit": "^2.2.0"
|
||||||
|
},
|
||||||
|
"engines": {
|
||||||
|
"node": ">=8"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/p-try": {
|
||||||
|
"version": "2.2.0",
|
||||||
|
"resolved": "https://registry.npmmirror.com/p-try/-/p-try-2.2.0.tgz",
|
||||||
|
"integrity": "sha512-R4nPAVTAU0B9D35/Gk3uJf/7XYbQcyohSKdvAxIRSNghFl4e71hVoGnBNQz9cWaXxO2I10KTC+3jMdvvoKw6dQ==",
|
||||||
|
"license": "MIT",
|
||||||
|
"engines": {
|
||||||
|
"node": ">=6"
|
||||||
|
}
|
||||||
|
},
|
||||||
"node_modules/parse5": {
|
"node_modules/parse5": {
|
||||||
"version": "7.3.0",
|
"version": "7.3.0",
|
||||||
"resolved": "https://registry.npmmirror.com/parse5/-/parse5-7.3.0.tgz",
|
"resolved": "https://registry.npmmirror.com/parse5/-/parse5-7.3.0.tgz",
|
||||||
@@ -2581,6 +2765,15 @@
|
|||||||
"dev": true,
|
"dev": true,
|
||||||
"license": "MIT"
|
"license": "MIT"
|
||||||
},
|
},
|
||||||
|
"node_modules/path-exists": {
|
||||||
|
"version": "4.0.0",
|
||||||
|
"resolved": "https://registry.npmmirror.com/path-exists/-/path-exists-4.0.0.tgz",
|
||||||
|
"integrity": "sha512-ak9Qy5Q7jYb2Wwcey5Fpvg2KoAc/ZIhLSLOSBmRmygPsGwkVVt0fZa0qrtMz+m6tJTAHfZQ8FnmB4MG4LWy7/w==",
|
||||||
|
"license": "MIT",
|
||||||
|
"engines": {
|
||||||
|
"node": ">=8"
|
||||||
|
}
|
||||||
|
},
|
||||||
"node_modules/path-scurry": {
|
"node_modules/path-scurry": {
|
||||||
"version": "2.0.2",
|
"version": "2.0.2",
|
||||||
"resolved": "https://registry.npmmirror.com/path-scurry/-/path-scurry-2.0.2.tgz",
|
"resolved": "https://registry.npmmirror.com/path-scurry/-/path-scurry-2.0.2.tgz",
|
||||||
@@ -2666,6 +2859,15 @@
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"node_modules/pngjs": {
|
||||||
|
"version": "5.0.0",
|
||||||
|
"resolved": "https://registry.npmmirror.com/pngjs/-/pngjs-5.0.0.tgz",
|
||||||
|
"integrity": "sha512-40QW5YalBNfQo5yRYmiw7Yz6TKKVr3h6970B2YE+3fQpsWcrbj1PzJgxeJ19DRQjhMbKPIuMY8rFaXc8moolVw==",
|
||||||
|
"license": "MIT",
|
||||||
|
"engines": {
|
||||||
|
"node": ">=10.13.0"
|
||||||
|
}
|
||||||
|
},
|
||||||
"node_modules/postcss": {
|
"node_modules/postcss": {
|
||||||
"version": "8.5.28",
|
"version": "8.5.28",
|
||||||
"resolved": "https://registry.npmmirror.com/postcss/-/postcss-8.5.28.tgz",
|
"resolved": "https://registry.npmmirror.com/postcss/-/postcss-8.5.28.tgz",
|
||||||
@@ -2720,6 +2922,38 @@
|
|||||||
"node": ">=6"
|
"node": ">=6"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"node_modules/qrcode": {
|
||||||
|
"version": "1.5.4",
|
||||||
|
"resolved": "https://registry.npmmirror.com/qrcode/-/qrcode-1.5.4.tgz",
|
||||||
|
"integrity": "sha512-1ca71Zgiu6ORjHqFBDpnSMTR2ReToX4l1Au1VFLyVeBTFavzQnv5JxMFr3ukHVKpSrSA2MCk0lNJSykjUfz7Zg==",
|
||||||
|
"license": "MIT",
|
||||||
|
"dependencies": {
|
||||||
|
"dijkstrajs": "^1.0.1",
|
||||||
|
"pngjs": "^5.0.0",
|
||||||
|
"yargs": "^15.3.1"
|
||||||
|
},
|
||||||
|
"bin": {
|
||||||
|
"qrcode": "bin/qrcode"
|
||||||
|
},
|
||||||
|
"engines": {
|
||||||
|
"node": ">=10.13.0"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/require-directory": {
|
||||||
|
"version": "2.1.1",
|
||||||
|
"resolved": "https://registry.npmmirror.com/require-directory/-/require-directory-2.1.1.tgz",
|
||||||
|
"integrity": "sha512-fGxEI7+wsG9xrvdjsrlmL22OMTTiHRwAMroiEeMgq8gzoLC/PQr7RsRDSTLUg/bZAZtF+TVIkHc6/4RIKrui+Q==",
|
||||||
|
"license": "MIT",
|
||||||
|
"engines": {
|
||||||
|
"node": ">=0.10.0"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/require-main-filename": {
|
||||||
|
"version": "2.0.0",
|
||||||
|
"resolved": "https://registry.npmmirror.com/require-main-filename/-/require-main-filename-2.0.0.tgz",
|
||||||
|
"integrity": "sha512-NKN5kMDylKuldxYLSUfrbo5Tuzh4hd+2E8NPPX02mZtn1VuREQToYe/ZdlJy+J3uCpfaiGF05e7B8W0iXbQHmg==",
|
||||||
|
"license": "ISC"
|
||||||
|
},
|
||||||
"node_modules/rollup": {
|
"node_modules/rollup": {
|
||||||
"version": "4.63.5",
|
"version": "4.63.5",
|
||||||
"resolved": "https://registry.npmmirror.com/rollup/-/rollup-4.63.5.tgz",
|
"resolved": "https://registry.npmmirror.com/rollup/-/rollup-4.63.5.tgz",
|
||||||
@@ -2806,6 +3040,12 @@
|
|||||||
"node": ">=10"
|
"node": ">=10"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"node_modules/set-blocking": {
|
||||||
|
"version": "2.0.0",
|
||||||
|
"resolved": "https://registry.npmmirror.com/set-blocking/-/set-blocking-2.0.0.tgz",
|
||||||
|
"integrity": "sha512-KiKBS8AnWGEyLzofFfmvKwpdPzqiy16LvQfK3yv/fVH7Bj13/wl3JSR1J+rfgRE9q7xUJK4qvgS8raSOeLUehw==",
|
||||||
|
"license": "ISC"
|
||||||
|
},
|
||||||
"node_modules/siginfo": {
|
"node_modules/siginfo": {
|
||||||
"version": "2.0.0",
|
"version": "2.0.0",
|
||||||
"resolved": "https://registry.npmmirror.com/siginfo/-/siginfo-2.0.0.tgz",
|
"resolved": "https://registry.npmmirror.com/siginfo/-/siginfo-2.0.0.tgz",
|
||||||
@@ -2836,6 +3076,32 @@
|
|||||||
"dev": true,
|
"dev": true,
|
||||||
"license": "MIT"
|
"license": "MIT"
|
||||||
},
|
},
|
||||||
|
"node_modules/string-width": {
|
||||||
|
"version": "4.2.3",
|
||||||
|
"resolved": "https://registry.npmmirror.com/string-width/-/string-width-4.2.3.tgz",
|
||||||
|
"integrity": "sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g==",
|
||||||
|
"license": "MIT",
|
||||||
|
"dependencies": {
|
||||||
|
"emoji-regex": "^8.0.0",
|
||||||
|
"is-fullwidth-code-point": "^3.0.0",
|
||||||
|
"strip-ansi": "^6.0.1"
|
||||||
|
},
|
||||||
|
"engines": {
|
||||||
|
"node": ">=8"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/strip-ansi": {
|
||||||
|
"version": "6.0.1",
|
||||||
|
"resolved": "https://registry.npmmirror.com/strip-ansi/-/strip-ansi-6.0.1.tgz",
|
||||||
|
"integrity": "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==",
|
||||||
|
"license": "MIT",
|
||||||
|
"dependencies": {
|
||||||
|
"ansi-regex": "^5.0.1"
|
||||||
|
},
|
||||||
|
"engines": {
|
||||||
|
"node": ">=8"
|
||||||
|
}
|
||||||
|
},
|
||||||
"node_modules/strip-literal": {
|
"node_modules/strip-literal": {
|
||||||
"version": "3.1.0",
|
"version": "3.1.0",
|
||||||
"resolved": "https://registry.npmmirror.com/strip-literal/-/strip-literal-3.1.0.tgz",
|
"resolved": "https://registry.npmmirror.com/strip-literal/-/strip-literal-3.1.0.tgz",
|
||||||
@@ -2977,6 +3243,13 @@
|
|||||||
"node": ">=14.17"
|
"node": ">=14.17"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"node_modules/undici-types": {
|
||||||
|
"version": "8.9.0",
|
||||||
|
"resolved": "https://registry.npmmirror.com/undici-types/-/undici-types-8.9.0.tgz",
|
||||||
|
"integrity": "sha512-KTDyRTYX8sWmKXAikPHHSyc63CRPETMctyjKFupcC6OBLXT3xsN0e9aF7m+mIXutFWpUXuedtowG7iLOzp0kQg==",
|
||||||
|
"dev": true,
|
||||||
|
"license": "MIT"
|
||||||
|
},
|
||||||
"node_modules/vite": {
|
"node_modules/vite": {
|
||||||
"version": "6.4.3",
|
"version": "6.4.3",
|
||||||
"resolved": "https://registry.npmmirror.com/vite/-/vite-6.4.3.tgz",
|
"resolved": "https://registry.npmmirror.com/vite/-/vite-6.4.3.tgz",
|
||||||
@@ -3301,6 +3574,12 @@
|
|||||||
"node": ">=18"
|
"node": ">=18"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"node_modules/which-module": {
|
||||||
|
"version": "2.0.1",
|
||||||
|
"resolved": "https://registry.npmmirror.com/which-module/-/which-module-2.0.1.tgz",
|
||||||
|
"integrity": "sha512-iBdZ57RDvnOR9AGBhML2vFZf7h8vmBjhoaZqODJBFWHVtKkDmKuHai3cx5PgVMrX5YDNp27AofYbAwctSS+vhQ==",
|
||||||
|
"license": "ISC"
|
||||||
|
},
|
||||||
"node_modules/why-is-node-running": {
|
"node_modules/why-is-node-running": {
|
||||||
"version": "2.3.0",
|
"version": "2.3.0",
|
||||||
"resolved": "https://registry.npmmirror.com/why-is-node-running/-/why-is-node-running-2.3.0.tgz",
|
"resolved": "https://registry.npmmirror.com/why-is-node-running/-/why-is-node-running-2.3.0.tgz",
|
||||||
@@ -3318,6 +3597,20 @@
|
|||||||
"node": ">=8"
|
"node": ">=8"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"node_modules/wrap-ansi": {
|
||||||
|
"version": "6.2.0",
|
||||||
|
"resolved": "https://registry.npmmirror.com/wrap-ansi/-/wrap-ansi-6.2.0.tgz",
|
||||||
|
"integrity": "sha512-r6lPcBGxZXlIcymEu7InxDMhdW0KDxpLgoFLcguasxCaJ/SOIZwINatK9KY/tf+ZrlywOKU0UDj3ATXUBfxJXA==",
|
||||||
|
"license": "MIT",
|
||||||
|
"dependencies": {
|
||||||
|
"ansi-styles": "^4.0.0",
|
||||||
|
"string-width": "^4.1.0",
|
||||||
|
"strip-ansi": "^6.0.0"
|
||||||
|
},
|
||||||
|
"engines": {
|
||||||
|
"node": ">=8"
|
||||||
|
}
|
||||||
|
},
|
||||||
"node_modules/ws": {
|
"node_modules/ws": {
|
||||||
"version": "8.22.0",
|
"version": "8.22.0",
|
||||||
"resolved": "https://registry.npmmirror.com/ws/-/ws-8.22.0.tgz",
|
"resolved": "https://registry.npmmirror.com/ws/-/ws-8.22.0.tgz",
|
||||||
@@ -3356,6 +3649,47 @@
|
|||||||
"integrity": "sha512-JZnDKK8B0RCDw84FNdDAIpZK+JuJw+s7Lz8nksI7SIuU3UXJJslUthsi+uWBUYOwPFwW7W7PRLRfUKpxjtjFCw==",
|
"integrity": "sha512-JZnDKK8B0RCDw84FNdDAIpZK+JuJw+s7Lz8nksI7SIuU3UXJJslUthsi+uWBUYOwPFwW7W7PRLRfUKpxjtjFCw==",
|
||||||
"dev": true,
|
"dev": true,
|
||||||
"license": "MIT"
|
"license": "MIT"
|
||||||
|
},
|
||||||
|
"node_modules/y18n": {
|
||||||
|
"version": "4.0.3",
|
||||||
|
"resolved": "https://registry.npmmirror.com/y18n/-/y18n-4.0.3.tgz",
|
||||||
|
"integrity": "sha512-JKhqTOwSrqNA1NY5lSztJ1GrBiUodLMmIZuLiDaMRJ+itFd+ABVE8XBjOvIWL+rSqNDC74LCSFmlb/U4UZ4hJQ==",
|
||||||
|
"license": "ISC"
|
||||||
|
},
|
||||||
|
"node_modules/yargs": {
|
||||||
|
"version": "15.4.1",
|
||||||
|
"resolved": "https://registry.npmmirror.com/yargs/-/yargs-15.4.1.tgz",
|
||||||
|
"integrity": "sha512-aePbxDmcYW++PaqBsJ+HYUFwCdv4LVvdnhBy78E57PIor8/OVvhMrADFFEDh8DHDFRv/O9i3lPhsENjO7QX0+A==",
|
||||||
|
"license": "MIT",
|
||||||
|
"dependencies": {
|
||||||
|
"cliui": "^6.0.0",
|
||||||
|
"decamelize": "^1.2.0",
|
||||||
|
"find-up": "^4.1.0",
|
||||||
|
"get-caller-file": "^2.0.1",
|
||||||
|
"require-directory": "^2.1.1",
|
||||||
|
"require-main-filename": "^2.0.0",
|
||||||
|
"set-blocking": "^2.0.0",
|
||||||
|
"string-width": "^4.2.0",
|
||||||
|
"which-module": "^2.0.0",
|
||||||
|
"y18n": "^4.0.0",
|
||||||
|
"yargs-parser": "^18.1.2"
|
||||||
|
},
|
||||||
|
"engines": {
|
||||||
|
"node": ">=8"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/yargs-parser": {
|
||||||
|
"version": "18.1.3",
|
||||||
|
"resolved": "https://registry.npmmirror.com/yargs-parser/-/yargs-parser-18.1.3.tgz",
|
||||||
|
"integrity": "sha512-o50j0JeToy/4K6OZcaQmW6lyXXKhq7csREXcDwk2omFPJEwUNOVtJKvmDr9EI1fAJZUyZcRF7kxGBWmRXudrCQ==",
|
||||||
|
"license": "ISC",
|
||||||
|
"dependencies": {
|
||||||
|
"camelcase": "^5.0.0",
|
||||||
|
"decamelize": "^1.2.0"
|
||||||
|
},
|
||||||
|
"engines": {
|
||||||
|
"node": ">=6"
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -13,10 +13,12 @@
|
|||||||
"axios": "^1.7.9",
|
"axios": "^1.7.9",
|
||||||
"element-plus": "^2.9.4",
|
"element-plus": "^2.9.4",
|
||||||
"pinia": "^2.3.0",
|
"pinia": "^2.3.0",
|
||||||
|
"qrcode": "^1.5.4",
|
||||||
"vue": "^3.5.13",
|
"vue": "^3.5.13",
|
||||||
"vue-router": "^4.5.0"
|
"vue-router": "^4.5.0"
|
||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
|
"@types/qrcode": "^1.5.6",
|
||||||
"@vitejs/plugin-vue": "^5.2.1",
|
"@vitejs/plugin-vue": "^5.2.1",
|
||||||
"@vue/test-utils": "^2.5.1",
|
"@vue/test-utils": "^2.5.1",
|
||||||
"jsdom": "^26.1.0",
|
"jsdom": "^26.1.0",
|
||||||
|
|||||||
46
frontend/src/api.test.ts
Normal file
46
frontend/src/api.test.ts
Normal file
@@ -0,0 +1,46 @@
|
|||||||
|
import { describe, expect, it } from 'vitest'
|
||||||
|
import { api, ApiError } from './api'
|
||||||
|
|
||||||
|
async function rejectedResponse(status?:unknown, detail?:unknown) {
|
||||||
|
return api.get('/payment-channels/alipay', {
|
||||||
|
adapter:async () => { throw {response:{status,data:{error:detail}},config:{secret:'request-secret'},request:{secret:'request-secret'}} },
|
||||||
|
}).catch((error:unknown) => error)
|
||||||
|
}
|
||||||
|
|
||||||
|
describe('API error interceptor', () => {
|
||||||
|
it('preserves Error.message compatibility and validated code/status without retaining raw request data', async () => {
|
||||||
|
const error = await rejectedResponse(503,{code:'payment_schema_unavailable',message:'Existing page message',secret:'raw-secret'})
|
||||||
|
expect(error).toBeInstanceOf(Error)
|
||||||
|
expect(error).toBeInstanceOf(ApiError)
|
||||||
|
expect(error).toMatchObject({message:'Existing page message',code:'payment_schema_unavailable',status:503})
|
||||||
|
expect(error).not.toHaveProperty('response')
|
||||||
|
expect(error).not.toHaveProperty('config')
|
||||||
|
expect(error).not.toHaveProperty('request')
|
||||||
|
expect(JSON.stringify(error)).not.toMatch(/raw-secret|request-secret/)
|
||||||
|
})
|
||||||
|
|
||||||
|
it.each([
|
||||||
|
['<script>secret</script>', '503'],
|
||||||
|
['a'.repeat(65), 600],
|
||||||
|
[{secret:'raw-secret'}, 401.5],
|
||||||
|
['SECRET PRIVATE KEY', null],
|
||||||
|
])('drops malformed metadata %j / %j', async (code,status) => {
|
||||||
|
const error = await rejectedResponse(status,{code,message:{secret:'raw-secret'}})
|
||||||
|
expect(error).toBeInstanceOf(ApiError)
|
||||||
|
expect(error).toMatchObject({message:'请求失败,请稍后重试'})
|
||||||
|
expect((error as ApiError).code).toBeUndefined()
|
||||||
|
expect((error as ApiError).status).toBeUndefined()
|
||||||
|
})
|
||||||
|
|
||||||
|
it('falls back safely when there is no response', async () => {
|
||||||
|
const error = await api.get('/payment-channels/wechat',{adapter:async () => { throw new Error('network internal detail') }}).catch((error:unknown) => error)
|
||||||
|
expect(error).toBeInstanceOf(ApiError)
|
||||||
|
expect(error).toMatchObject({message:'请求失败,请稍后重试'})
|
||||||
|
expect((error as ApiError).status).toBeUndefined()
|
||||||
|
})
|
||||||
|
|
||||||
|
it('leaves successful responses unchanged', async () => {
|
||||||
|
const response = await api.get('/me',{adapter:async config => ({data:{data:{username:'admin'}},status:200,statusText:'OK',headers:{},config})})
|
||||||
|
expect(response.data).toEqual({data:{username:'admin'}})
|
||||||
|
})
|
||||||
|
})
|
||||||
11
frontend/src/payments-api.test.ts
Normal file
11
frontend/src/payments-api.test.ts
Normal file
@@ -0,0 +1,11 @@
|
|||||||
|
import { beforeEach, expect, it, vi } from 'vitest'
|
||||||
|
const api = vi.hoisted(() => ({get:vi.fn(),put:vi.fn()}))
|
||||||
|
vi.mock('./api', () => ({api}))
|
||||||
|
import { getPaymentChannel, listPaymentOrders, savePaymentChannel } from './payments-api'
|
||||||
|
beforeEach(() => vi.resetAllMocks())
|
||||||
|
it('uses the authenticated admin client for payment order and channel configuration requests', async () => {
|
||||||
|
await listPaymentOrders(); expect(api.get).toHaveBeenCalledWith('/payment-orders')
|
||||||
|
await getPaymentChannel('alipay'); expect(api.get).toHaveBeenCalledWith('/payment-channels/alipay')
|
||||||
|
const value = {enabled:true,fields:{app_id:'app',seller_id:'seller',notify_url:'https://merchant.example/notify'},secrets:{private_key:'replacement'}}
|
||||||
|
await savePaymentChannel('alipay',value); expect(api.put).toHaveBeenCalledWith('/payment-channels/alipay',value)
|
||||||
|
})
|
||||||
42
frontend/src/payments-api.ts
Normal file
42
frontend/src/payments-api.ts
Normal file
@@ -0,0 +1,42 @@
|
|||||||
|
import axios from 'axios'
|
||||||
|
import type { PaymentChannel } from './orders-api'
|
||||||
|
import { api } from './api'
|
||||||
|
|
||||||
|
export type PaymentOrder = {
|
||||||
|
id:number; order_id:number; merchant_order_no:string; channel:PaymentChannel; channel_trade_no:string|null;
|
||||||
|
amount_cents:number; currency:string; status:string; order_status:string; license_id:number|null;
|
||||||
|
last_error:string|null; paid_at:string|null; created_at:string; expires_at:string;
|
||||||
|
}
|
||||||
|
export const listPaymentOrders = () => api.get<{data:PaymentOrder[]}>('/payment-orders')
|
||||||
|
|
||||||
|
// GET/PUT never return credential material; fields contains ordinary metadata only.
|
||||||
|
export type PaymentChannelMetadata = {
|
||||||
|
app_id:string; notify_url:string; seller_id?:string; mch_id?:string;
|
||||||
|
serial_no?:string; public_key_id?:string; platform_serial?:string;
|
||||||
|
}
|
||||||
|
export type PaymentChannelSecrets = {
|
||||||
|
private_key?:string; public_key?:string; platform_public_key?:string; api_v3_key?:string;
|
||||||
|
}
|
||||||
|
export type PaymentChannelConfiguration = {
|
||||||
|
channel:PaymentChannel; enabled?:boolean; configuration_source?:'environment'|'database'|'none';
|
||||||
|
version?:number|null; effective?:boolean; can_save?:boolean; required_settings?:string[];
|
||||||
|
fields:PaymentChannelMetadata;
|
||||||
|
secret_fields:{name:keyof PaymentChannelSecrets; configured:boolean}[];
|
||||||
|
}
|
||||||
|
export type PaymentChannelUpdate = {
|
||||||
|
enabled:boolean; fields:PaymentChannelMetadata; secrets:PaymentChannelSecrets;
|
||||||
|
}
|
||||||
|
export const getPaymentChannel = (channel:PaymentChannel) => api.get<{data:PaymentChannelConfiguration}>(`/payment-channels/${channel}`)
|
||||||
|
export const savePaymentChannel = (channel:PaymentChannel, value:PaymentChannelUpdate) => api.put<{data:PaymentChannelConfiguration}>(`/payment-channels/${channel}`, value)
|
||||||
|
|
||||||
|
const checkoutClient = axios.create({ baseURL: '/api/v1', timeout: 8000, withCredentials: false })
|
||||||
|
export type CheckoutPayment = { code_url:string; status:string; order_status:string; license_id:number|null; license_key:string; amount_cents:number; currency:string; channel:PaymentChannel }
|
||||||
|
export const getCheckoutPayment = (token:string) => checkoutClient.post<{data:CheckoutPayment}>('/payments/checkout', {token})
|
||||||
|
|
||||||
|
export function checkoutLink(value:string) {
|
||||||
|
const url = new URL(value, window.location.origin)
|
||||||
|
if (url.origin !== window.location.origin || url.pathname !== '/checkout' || url.search || !new URLSearchParams(url.hash.slice(1)).get('token')) {
|
||||||
|
throw new Error('付款链接无效')
|
||||||
|
}
|
||||||
|
return url.href
|
||||||
|
}
|
||||||
77
frontend/src/views/Checkout.test.ts
Normal file
77
frontend/src/views/Checkout.test.ts
Normal file
@@ -0,0 +1,77 @@
|
|||||||
|
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||||
|
import { flushPromises, mount } from '@vue/test-utils'
|
||||||
|
import QRCode from 'qrcode'
|
||||||
|
const calls = vi.hoisted(() => ({ getCheckoutPayment:vi.fn() }))
|
||||||
|
vi.mock('../payments-api', () => calls)
|
||||||
|
import Checkout from './Checkout.vue'
|
||||||
|
import type { CheckoutPayment } from '../payments-api'
|
||||||
|
const pending:CheckoutPayment = {code_url:'alipays://platformapi/startapp?test=payment',status:'pending',order_status:'pending_payment',license_id:null,license_key:'',amount_cents:1234,currency:'CNY',channel:'alipay'}
|
||||||
|
const response = (value = pending) => ({data:{data:value}})
|
||||||
|
let qrImage = ''
|
||||||
|
let wrapper:ReturnType<typeof mount>|undefined
|
||||||
|
beforeEach(async () => { qrImage = await QRCode.toDataURL(pending.code_url, {width:280,margin:2,errorCorrectionLevel:'M'}); vi.useFakeTimers(); vi.resetAllMocks(); vi.spyOn(QRCode, 'toDataURL').mockImplementation((() => Promise.resolve(qrImage)) as typeof QRCode.toDataURL); window.history.replaceState({}, '', '/checkout#token=secret-checkout'); calls.getCheckoutPayment.mockResolvedValue(response()) })
|
||||||
|
afterEach(() => { wrapper?.unmount(); wrapper = undefined; vi.useRealTimers(); vi.restoreAllMocks() })
|
||||||
|
describe('Checkout', () => {
|
||||||
|
it('uses the hash token, generates a real QR image, polls every 3 seconds and stops after issuance', async () => {
|
||||||
|
const storage = vi.spyOn(Storage.prototype, 'setItem')
|
||||||
|
wrapper = mount(Checkout); await flushPromises()
|
||||||
|
expect(calls.getCheckoutPayment).toHaveBeenCalledWith('secret-checkout')
|
||||||
|
expect(wrapper.get('img').attributes('src')).toBe(qrImage)
|
||||||
|
expect(QRCode.toDataURL).toHaveBeenCalledWith(pending.code_url, {width:280,margin:2,errorCorrectionLevel:'M'})
|
||||||
|
expect(wrapper.text()).toContain('12.34 CNY')
|
||||||
|
expect(storage).not.toHaveBeenCalled()
|
||||||
|
calls.getCheckoutPayment.mockResolvedValue(response({...pending,status:'paid',order_status:'issued',license_id:71,license_key:'issued-key'}))
|
||||||
|
await vi.advanceTimersByTimeAsync(2999); expect(calls.getCheckoutPayment).toHaveBeenCalledTimes(1)
|
||||||
|
await vi.advanceTimersByTimeAsync(1); await flushPromises()
|
||||||
|
expect(wrapper.get('input').element.value).toBe('issued-key'); expect(wrapper.text()).toContain('现有客户端');
|
||||||
|
const copy = vi.fn().mockResolvedValue(undefined); vi.stubGlobal('navigator', {...navigator, clipboard:{writeText:copy}})
|
||||||
|
await wrapper.get('button').trigger('click'); await flushPromises(); expect(copy).toHaveBeenCalledWith('issued-key'); vi.unstubAllGlobals()
|
||||||
|
expect(wrapper.text()).toContain('开通成功'); expect(wrapper.text()).toContain('71'); expect(wrapper.find('img').exists()).toBe(false)
|
||||||
|
await vi.advanceTimersByTimeAsync(9000); expect(calls.getCheckoutPayment).toHaveBeenCalledTimes(2)
|
||||||
|
})
|
||||||
|
it('does not submit a missing token or use query-string credentials', async () => {
|
||||||
|
window.history.replaceState({}, '', '/checkout?token=wrong')
|
||||||
|
wrapper = mount(Checkout); await flushPromises()
|
||||||
|
expect(wrapper.get('[role="alert"]').text()).toContain('缺少 token'); expect(calls.getCheckoutPayment).not.toHaveBeenCalled()
|
||||||
|
})
|
||||||
|
it('hides stale QR codes on query failure and retries without exposing API error content', async () => {
|
||||||
|
wrapper = mount(Checkout); await flushPromises()
|
||||||
|
calls.getCheckoutPayment.mockRejectedValueOnce(new Error('secret-checkout'))
|
||||||
|
await vi.advanceTimersByTimeAsync(3000); await flushPromises()
|
||||||
|
expect(wrapper.find('img').exists()).toBe(false); expect(wrapper.text()).not.toContain('secret-checkout')
|
||||||
|
await wrapper.get('button').trigger('click'); await flushPromises()
|
||||||
|
expect(wrapper.find('img').exists()).toBe(true)
|
||||||
|
wrapper.unmount(); wrapper = undefined
|
||||||
|
await vi.advanceTimersByTimeAsync(6000); expect(calls.getCheckoutPayment).toHaveBeenCalledTimes(3)
|
||||||
|
})
|
||||||
|
it('shows failed payments and permits a manual retry', async () => {
|
||||||
|
calls.getCheckoutPayment.mockResolvedValueOnce(response({...pending,status:'failed'}))
|
||||||
|
wrapper = mount(Checkout); await flushPromises()
|
||||||
|
expect(wrapper.text()).toContain('支付未完成'); expect(wrapper.find('img').exists()).toBe(false)
|
||||||
|
await vi.advanceTimersByTimeAsync(6000); expect(calls.getCheckoutPayment).toHaveBeenCalledTimes(1)
|
||||||
|
await wrapper.get('button').trigger('click'); await flushPromises(); expect(wrapper.find('img').exists()).toBe(true)
|
||||||
|
})
|
||||||
|
it('asks administrators to inspect expired orders instead of promising a rebuild action', async () => {
|
||||||
|
calls.getCheckoutPayment.mockResolvedValueOnce(response({...pending,status:'expired'}))
|
||||||
|
wrapper = mount(Checkout); await flushPromises()
|
||||||
|
expect(wrapper.text()).toContain('联系管理员核查订单')
|
||||||
|
expect(wrapper.text()).not.toContain('重新创建付款链接')
|
||||||
|
})
|
||||||
|
it('stops polling when the administrator removed the authorization', async () => {
|
||||||
|
calls.getCheckoutPayment.mockResolvedValueOnce(response({...pending,status:'paid',order_status:'authorization_removed'}))
|
||||||
|
wrapper = mount(Checkout); await flushPromises()
|
||||||
|
expect(wrapper.text()).toContain('授权已被管理员移除,请联系管理员核查')
|
||||||
|
expect(wrapper.text()).not.toContain('开通成功')
|
||||||
|
expect(wrapper.find('img').exists()).toBe(false)
|
||||||
|
await vi.advanceTimersByTimeAsync(9000)
|
||||||
|
expect(calls.getCheckoutPayment).toHaveBeenCalledTimes(1)
|
||||||
|
})
|
||||||
|
it('ignores old in-flight responses when the hash token changes', async () => {
|
||||||
|
let resolve!:(value:ReturnType<typeof response>)=>void
|
||||||
|
calls.getCheckoutPayment.mockReturnValueOnce(new Promise(done => { resolve = done }))
|
||||||
|
wrapper = mount(Checkout); await flushPromises()
|
||||||
|
window.history.replaceState({}, '', '/checkout#token=new-token'); window.dispatchEvent(new Event('hashchange')); await flushPromises()
|
||||||
|
resolve(response({...pending,status:'paid',order_status:'issued'})); await flushPromises()
|
||||||
|
expect(wrapper.text()).not.toContain('开通成功'); expect(calls.getCheckoutPayment).toHaveBeenLastCalledWith('new-token')
|
||||||
|
})
|
||||||
|
})
|
||||||
71
frontend/src/views/Checkout.vue
Normal file
71
frontend/src/views/Checkout.vue
Normal file
@@ -0,0 +1,71 @@
|
|||||||
|
<script setup lang="ts">
|
||||||
|
import { computed, onMounted, onUnmounted, ref } from 'vue'
|
||||||
|
import QRCode from 'qrcode'
|
||||||
|
import { getCheckoutPayment, type CheckoutPayment } from '../payments-api'
|
||||||
|
|
||||||
|
const payment = ref<CheckoutPayment|null>(null), qr = ref(''), busy = ref(false), error = ref('')
|
||||||
|
const copyNotice = ref('')
|
||||||
|
async function copyLicenseKey() {
|
||||||
|
if (!payment.value?.license_key) return
|
||||||
|
try { await navigator.clipboard.writeText(payment.value.license_key); copyNotice.value = '授权密钥已复制' }
|
||||||
|
catch { copyNotice.value = '复制失败,请手动复制授权密钥' }
|
||||||
|
}
|
||||||
|
const issued = computed(() => payment.value?.order_status === 'issued')
|
||||||
|
const removed = computed(() => payment.value?.order_status === 'authorization_removed')
|
||||||
|
const failed = computed(() => ['failed', 'expired', 'cancelled', 'closed'].includes(payment.value?.status || ''))
|
||||||
|
let token = '', timer:ReturnType<typeof setTimeout>|undefined, generation = 0, disposed = false
|
||||||
|
function stopPolling() { clearTimeout(timer); timer = undefined }
|
||||||
|
async function load() {
|
||||||
|
if (!token || busy.value || disposed) return
|
||||||
|
stopPolling()
|
||||||
|
const current = generation
|
||||||
|
busy.value = true; error.value = ''
|
||||||
|
try {
|
||||||
|
const result = (await getCheckoutPayment(token)).data.data
|
||||||
|
if (disposed || current !== generation) return
|
||||||
|
payment.value = result
|
||||||
|
qr.value = ''
|
||||||
|
if (!issued.value && !removed.value && !failed.value && result.status !== 'paid' && result.code_url) {
|
||||||
|
const image = await QRCode.toDataURL(result.code_url, {width:280, margin:2, errorCorrectionLevel:'M'})
|
||||||
|
if (disposed || current !== generation) return
|
||||||
|
qr.value = image
|
||||||
|
}
|
||||||
|
if (!issued.value && !removed.value && !failed.value) timer = setTimeout(load, 3000)
|
||||||
|
} catch {
|
||||||
|
if (!disposed && current === generation) { qr.value = ''; error.value = '支付查询失败,请重试' }
|
||||||
|
} finally {
|
||||||
|
if (current === generation) busy.value = false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
function readToken() {
|
||||||
|
generation++; stopPolling(); busy.value = false; payment.value = null; qr.value = ''; error.value = ''; copyNotice.value = ''
|
||||||
|
token = new URLSearchParams(window.location.hash.slice(1)).get('token') || ''
|
||||||
|
if (!token) { error.value = '付款链接无效,缺少 token'; return }
|
||||||
|
void load()
|
||||||
|
}
|
||||||
|
onMounted(() => { readToken(); window.addEventListener('hashchange', readToken) })
|
||||||
|
onUnmounted(() => { disposed = true; generation++; token = ''; stopPolling(); window.removeEventListener('hashchange', readToken) })
|
||||||
|
</script>
|
||||||
|
<template>
|
||||||
|
<main class="checkout">
|
||||||
|
<h1>订单付款</h1>
|
||||||
|
<p v-if="error" role="alert">{{ error }}</p>
|
||||||
|
<template v-if="payment">
|
||||||
|
<p class="amount">{{ (payment.amount_cents / 100).toFixed(2) }} {{ payment.currency }}</p>
|
||||||
|
<p>{{ payment.channel === 'alipay' ? '支付宝' : '微信支付' }}</p>
|
||||||
|
<template v-if="issued"><h2 role="status">开通成功</h2><p v-if="payment.license_id">授权 ID:{{ payment.license_id }}</p><template v-if="payment.license_key"><label>授权密钥<input :value="payment.license_key" readonly aria-label="授权密钥"></label><p><button @click="copyLicenseKey">复制授权密钥</button></p><p v-if="copyNotice" role="status">{{ copyNotice }}</p></template><p>授权已开通,请在现有客户端输入授权密钥完成激活。</p></template>
|
||||||
|
<p v-else-if="removed" role="status">授权已被管理员移除,请联系管理员核查</p>
|
||||||
|
<p v-else-if="failed" role="status">支付未完成或已失效,请重试查询;如仍无法付款,请联系管理员核查订单。</p>
|
||||||
|
<template v-else>
|
||||||
|
<p role="status">{{ payment.status === 'paid' || payment.order_status === 'paid' ? '已收款,正在开通授权' : '请使用对应支付应用扫码付款' }}</p>
|
||||||
|
<img v-if="qr" :src="qr" alt="付款二维码" width="280" height="280">
|
||||||
|
<p v-if="!qr && !busy && !error && payment.status !== 'paid'">暂未获取到付款二维码,正在查询</p>
|
||||||
|
</template>
|
||||||
|
</template>
|
||||||
|
<p v-if="busy" role="status">正在查询支付状态…</p>
|
||||||
|
<button v-if="token && (error || failed)" :disabled="busy" @click="load">重试查询</button>
|
||||||
|
</main>
|
||||||
|
</template>
|
||||||
|
<style scoped>
|
||||||
|
.checkout{max-width:520px;margin:40px auto;padding:28px;text-align:center;background:#fff;border-radius:12px;color:#202124}h1{font-size:24px}.amount{font-size:28px;font-weight:600}img{max-width:100%;height:auto}input{display:block;width:100%;box-sizing:border-box;padding:10px;margin-top:8px}button{padding:10px 20px;cursor:pointer}p[role=alert]{color:#a4262c}
|
||||||
|
</style>
|
||||||
219
frontend/src/views/PaymentsPanel.test.ts
Normal file
219
frontend/src/views/PaymentsPanel.test.ts
Normal file
@@ -0,0 +1,219 @@
|
|||||||
|
import { beforeEach, describe, expect, it, vi } from 'vitest'
|
||||||
|
import { flushPromises, mount } from '@vue/test-utils'
|
||||||
|
import { defineComponent, nextTick } from 'vue'
|
||||||
|
import ElementPlus, { ElPagination } from 'element-plus'
|
||||||
|
import { formatDateTime } from '../date-format'
|
||||||
|
import { ApiError } from '../api'
|
||||||
|
const calls = vi.hoisted(() => ({getPaymentChannel:vi.fn(),savePaymentChannel:vi.fn(),listPaymentOrders:vi.fn()}))
|
||||||
|
vi.mock('../payments-api', () => calls)
|
||||||
|
import PaymentsPanel from './PaymentsPanel.vue'
|
||||||
|
const row = {id:1,order_id:7,merchant_order_no:'merchant-7',channel:'alipay',channel_trade_no:null,amount_cents:12345,currency:'CNY',status:'paid',order_status:'issued',license_id:8,last_error:'secret-token-and-license-key',paid_at:'2026-10-14T04:00:00Z',created_at:'2026-10-14T03:00:00Z',expires_at:'2026-10-14T05:00:00Z',token:'hidden-token',license_key:'hidden-license'}
|
||||||
|
const configuration = (channel:string) => ({channel,enabled:channel === 'alipay',configuration_source:'database',fields:channel === 'alipay' ? {app_id:'app-1',seller_id:'seller-1',notify_url:'https://merchant.example/notify'} : {app_id:'wx-1',mch_id:'mch-1',serial_no:'serial-1',platform_serial:'platform-1',notify_url:'https://merchant.example/wechat'},secret_fields:(channel === 'alipay' ? ['private_key','public_key'] : ['private_key','platform_public_key','api_v3_key']).map(name => ({name,configured:true}))})
|
||||||
|
const options = {global:{plugins:[ElementPlus],stubs:{
|
||||||
|
'el-button':defineComponent({props:['disabled'],emits:['click'],template:'<button :disabled="disabled" @click="$emit(\'click\',$event)"><slot/></button>'}),
|
||||||
|
'router-link':defineComponent({props:['to'],template:'<a :href="to"><slot/></a>'}),
|
||||||
|
'el-input':defineComponent({inheritAttrs:false,props:['modelValue'],emits:['update:modelValue'],template:'<input v-bind="$attrs" :value="modelValue" @input="$emit(\'update:modelValue\',$event.target.value)">' }),
|
||||||
|
'el-select':defineComponent({inheritAttrs:false,props:['modelValue'],emits:['update:modelValue'],template:'<select v-bind="$attrs" :value="modelValue" @change="$emit(\'update:modelValue\',$event.target.value)"><slot/></select>'}),
|
||||||
|
'el-option':defineComponent({props:['value','label'],template:'<option :value="value">{{ label }}</option>'}),
|
||||||
|
}}}
|
||||||
|
beforeEach(() => { vi.resetAllMocks(); calls.getPaymentChannel.mockImplementation((channel:string) => Promise.resolve({data:{data:configuration(channel)}})); calls.savePaymentChannel.mockImplementation((channel:string) => Promise.resolve({data:{data:configuration(channel)}})); calls.listPaymentOrders.mockResolvedValue({data:{data:[row,{...row,id:2,order_id:9,merchant_order_no:'merchant-9',channel:'wechat',status:'created',order_status:'pending_payment',last_error:null}]}}) })
|
||||||
|
describe('PaymentsPanel', () => {
|
||||||
|
it('collapses channel forms by default and expands them independently', async () => {
|
||||||
|
const wrapper = mount(PaymentsPanel,{...options,attachTo:document.body}); await flushPromises()
|
||||||
|
const alipayToggle = wrapper.get('[aria-label="支付宝渠道配置"]')
|
||||||
|
const wechatToggle = wrapper.get('[aria-label="微信支付渠道配置"]')
|
||||||
|
expect(alipayToggle.attributes('aria-expanded')).toBe('false')
|
||||||
|
expect(wechatToggle.attributes('aria-expanded')).toBe('false')
|
||||||
|
await alipayToggle.trigger('click')
|
||||||
|
expect(alipayToggle.attributes('aria-expanded')).toBe('true')
|
||||||
|
expect(wrapper.get('#channel-details-alipay').isVisible()).toBe(true)
|
||||||
|
expect(wrapper.get('#channel-details-wechat').isVisible()).toBe(false)
|
||||||
|
await wechatToggle.trigger('click')
|
||||||
|
expect(wrapper.get('#channel-details-wechat').isVisible()).toBe(true)
|
||||||
|
await alipayToggle.trigger('click')
|
||||||
|
expect(wrapper.get('#channel-details-alipay').isVisible()).toBe(false)
|
||||||
|
wrapper.unmount()
|
||||||
|
})
|
||||||
|
it('shows editable channel configuration, formats records and filters the recent results', async () => {
|
||||||
|
const wrapper = mount(PaymentsPanel,options); await flushPromises()
|
||||||
|
expect(wrapper.text()).toContain('已启用'); expect(wrapper.text()).toContain('未启用')
|
||||||
|
expect(wrapper.text()).toContain('应用 ID'); expect(wrapper.text()).toContain('留空保留现值')
|
||||||
|
expect(wrapper.text()).toContain('123.45 CNY'); expect(wrapper.text()).toContain(formatDateTime(row.created_at))
|
||||||
|
expect(wrapper.text()).not.toMatch(/secret-token|hidden-token|hidden-license/)
|
||||||
|
expect(wrapper.get('a').attributes('href')).toBe('/orders')
|
||||||
|
await wrapper.get('[aria-label="支付渠道筛选"]').setValue('wechat')
|
||||||
|
expect(wrapper.findAll('.el-table__body tbody tr')).toHaveLength(1); expect(wrapper.text()).not.toContain('merchant-7')
|
||||||
|
expect(wrapper.get('.el-table__body tbody tr').text()).toContain('待支付')
|
||||||
|
expect(wrapper.get('.el-table__body tbody tr').text()).not.toContain('未知状态')
|
||||||
|
expect(wrapper.get('[aria-label="支付状态筛选"] option[value="created"]').text()).toBe('待支付')
|
||||||
|
await wrapper.get('[aria-label="支付状态筛选"]').setValue('paid')
|
||||||
|
expect(wrapper.text()).toContain('暂无符合条件')
|
||||||
|
await wrapper.findAll('button').find(button=>button.text()==='重置筛选')!.trigger('click')
|
||||||
|
await wrapper.get('[aria-label="搜索支付流水"]').setValue('merchant-7')
|
||||||
|
expect(wrapper.findAll('.el-table__body tbody tr')).toHaveLength(1)
|
||||||
|
await wrapper.findAll('button').find(button=>button.text().includes('刷新支付数据'))!.trigger('click'); await flushPromises()
|
||||||
|
expect(calls.listPaymentOrders).toHaveBeenCalledTimes(2); wrapper.unmount()
|
||||||
|
})
|
||||||
|
it('handles partial failure safely and allows refresh recovery', async () => {
|
||||||
|
calls.listPaymentOrders.mockRejectedValueOnce(new Error('sensitive-token'))
|
||||||
|
const wrapper = mount(PaymentsPanel,options); await flushPromises()
|
||||||
|
expect(wrapper.text()).toContain('应用 ID'); expect(wrapper.get('[role="alert"]').text()).toContain('支付流水加载失败')
|
||||||
|
expect(wrapper.text()).not.toContain('sensitive-token')
|
||||||
|
await wrapper.findAll('button').find(button=>button.text().includes('刷新支付数据'))!.trigger('click'); await flushPromises()
|
||||||
|
expect(wrapper.find('[role="alert"]').exists()).toBe(false); expect(wrapper.findAll('.el-table__body tbody tr')).toHaveLength(2); wrapper.unmount()
|
||||||
|
})
|
||||||
|
it('shows loading then empty results', async () => {
|
||||||
|
let resolve!: (value:unknown) => void
|
||||||
|
calls.listPaymentOrders.mockReturnValueOnce(new Promise(r=>{resolve=r}))
|
||||||
|
const wrapper = mount(PaymentsPanel,options)
|
||||||
|
await nextTick()
|
||||||
|
expect(wrapper.text()).toContain('正在加载支付数据')
|
||||||
|
resolve({data:{data:[]}}); await flushPromises()
|
||||||
|
expect(wrapper.text()).toContain('暂无符合条件'); wrapper.unmount()
|
||||||
|
})
|
||||||
|
it('paginates loaded records and resets the page after filtering and refresh', async () => {
|
||||||
|
const records = Array.from({length:25}, (_,index)=>({...row,id:index+1,merchant_order_no:`merchant-${index+1}`}))
|
||||||
|
calls.listPaymentOrders.mockResolvedValue({data:{data:records}})
|
||||||
|
const wrapper = mount(PaymentsPanel,options); await flushPromises()
|
||||||
|
expect(wrapper.findAll('.el-table__body tbody tr')).toHaveLength(20)
|
||||||
|
expect(wrapper.text()).toContain('每页 20 条')
|
||||||
|
wrapper.findComponent(ElPagination).vm.$emit('update:current-page',2); await nextTick()
|
||||||
|
expect(wrapper.findAll('.el-table__body tbody tr')).toHaveLength(5)
|
||||||
|
expect(wrapper.text()).toContain('merchant-25')
|
||||||
|
await wrapper.get('[aria-label="搜索支付流水"]').setValue('merchant-1'); await nextTick()
|
||||||
|
expect(wrapper.findComponent(ElPagination).props('currentPage')).toBe(1)
|
||||||
|
expect(wrapper.findAll('.el-table__body tbody tr')).toHaveLength(11)
|
||||||
|
await wrapper.findAll('button').find(button=>button.text()==='重置筛选')!.trigger('click')
|
||||||
|
wrapper.findComponent(ElPagination).vm.$emit('update:current-page',2); await nextTick()
|
||||||
|
await wrapper.findAll('button').find(button=>button.text().includes('刷新支付数据'))!.trigger('click'); await flushPromises()
|
||||||
|
expect(wrapper.findComponent(ElPagination).props('currentPage')).toBe(1)
|
||||||
|
expect(wrapper.findAll('.el-table__body tbody tr')).toHaveLength(20)
|
||||||
|
wrapper.unmount()
|
||||||
|
})
|
||||||
|
it('loads ordinary fields but never echoes returned secret material, and omits blank secrets on save', async () => {
|
||||||
|
calls.getPaymentChannel.mockImplementation((channel:string) => Promise.resolve({data:{data:{...configuration(channel),secrets:{private_key:'server-secret'},fields:{...configuration(channel).fields,private_key:'server-secret'},secret_fields:configuration(channel).secret_fields.map(flag => ({...flag,value:'server-secret'}))}}}))
|
||||||
|
const wrapper = mount(PaymentsPanel,options); await flushPromises()
|
||||||
|
expect(calls.getPaymentChannel).toHaveBeenCalledWith('alipay'); expect(calls.getPaymentChannel).toHaveBeenCalledWith('wechat')
|
||||||
|
expect(wrapper.get<HTMLInputElement>('[aria-label="支付宝应用 ID"]').element.value).toBe('app-1')
|
||||||
|
expect(wrapper.get<HTMLInputElement>('[aria-label="支付宝商户私钥"]').element.value).toBe('')
|
||||||
|
expect(wrapper.html()).not.toContain('server-secret')
|
||||||
|
await wrapper.get('[aria-label="支付宝应用 ID"]').setValue('app-edited')
|
||||||
|
await wrapper.get('[data-channel="alipay"] form').trigger('submit'); await flushPromises()
|
||||||
|
expect(calls.savePaymentChannel).toHaveBeenCalledWith('alipay',{enabled:true,fields:{app_id:'app-edited',seller_id:'seller-1',notify_url:'https://merchant.example/notify'},secrets:{}})
|
||||||
|
expect(wrapper.text()).toContain('配置保存成功'); expect(wrapper.text()).toContain('不代表真实交易联调通过')
|
||||||
|
wrapper.unmount()
|
||||||
|
})
|
||||||
|
it('submits replacement credentials once, clears inputs, blocks duplicate save and refresh while saving', async () => {
|
||||||
|
let resolve!: (value:unknown) => void
|
||||||
|
calls.savePaymentChannel.mockReturnValueOnce(new Promise(r => {resolve=r}))
|
||||||
|
const wrapper = mount(PaymentsPanel,options); await flushPromises()
|
||||||
|
await wrapper.get('[aria-label="支付宝商户私钥"]').setValue('replacement-secret')
|
||||||
|
await wrapper.get('[data-channel="alipay"] form').trigger('submit')
|
||||||
|
expect(calls.savePaymentChannel.mock.calls[0]![1].secrets).toEqual({private_key:'replacement-secret'})
|
||||||
|
expect(wrapper.get<HTMLInputElement>('[aria-label="支付宝商户私钥"]').element.value).toBe('')
|
||||||
|
expect(wrapper.html()).not.toContain('replacement-secret')
|
||||||
|
await wrapper.get('[data-channel="alipay"] form').trigger('submit')
|
||||||
|
expect(calls.savePaymentChannel).toHaveBeenCalledTimes(1)
|
||||||
|
expect(wrapper.findAll('button').find(button => button.text().includes('刷新支付数据'))!.attributes('disabled')).toBeDefined()
|
||||||
|
resolve({data:{data:configuration('alipay')}}); await flushPromises()
|
||||||
|
expect(wrapper.text()).toContain('配置保存成功'); wrapper.unmount()
|
||||||
|
})
|
||||||
|
it('shows safe save failures, retains ordinary drafts and clears credentials for retry', async () => {
|
||||||
|
calls.savePaymentChannel.mockRejectedValueOnce(new Error('replacement-secret raw PEM database-error'))
|
||||||
|
const wrapper = mount(PaymentsPanel,options); await flushPromises()
|
||||||
|
await wrapper.get('[aria-label="支付宝应用 ID"]').setValue('draft-app')
|
||||||
|
await wrapper.get('[aria-label="支付宝商户私钥"]').setValue('replacement-secret')
|
||||||
|
await wrapper.get('[data-channel="alipay"] form').trigger('submit'); await flushPromises()
|
||||||
|
expect(wrapper.get('[role="alert"]').text()).toContain('服务端校验未通过')
|
||||||
|
expect(wrapper.text()).not.toContain('配置保存成功'); expect(wrapper.html()).not.toMatch(/replacement-secret|raw PEM|database-error/)
|
||||||
|
expect(wrapper.get<HTMLInputElement>('[aria-label="支付宝商户私钥"]').element.value).toBe('')
|
||||||
|
expect(wrapper.get<HTMLInputElement>('[aria-label="支付宝应用 ID"]').element.value).toBe('draft-app')
|
||||||
|
await wrapper.get('[data-channel="alipay"] form').trigger('submit'); await flushPromises()
|
||||||
|
expect(wrapper.find('[role="alert"]').exists()).toBe(false); expect(wrapper.text()).toContain('配置保存成功'); wrapper.unmount()
|
||||||
|
})
|
||||||
|
it('validates required fields, HTTPS callbacks, missing secrets and APIv3 byte length before saving', async () => {
|
||||||
|
calls.getPaymentChannel.mockImplementation((channel:string) => Promise.resolve({data:{data:{...configuration(channel),secret_fields:configuration(channel).secret_fields.map(flag => ({...flag,configured:false}))}}}))
|
||||||
|
const wrapper = mount(PaymentsPanel,options); await flushPromises()
|
||||||
|
const alipay = wrapper.get('[data-channel="alipay"] form')
|
||||||
|
await wrapper.get('[aria-label="支付宝应用 ID"]').setValue(''); await alipay.trigger('submit')
|
||||||
|
expect(wrapper.text()).toContain('请填写应用 ID')
|
||||||
|
await wrapper.get('[aria-label="支付宝应用 ID"]').setValue('app')
|
||||||
|
await wrapper.get('[aria-label="支付宝HTTPS 通知地址"]').setValue('http://merchant.example'); await alipay.trigger('submit')
|
||||||
|
expect(wrapper.text()).toContain('通知地址必须')
|
||||||
|
await wrapper.get('[aria-label="支付宝HTTPS 通知地址"]').setValue('https://merchant.example'); await alipay.trigger('submit')
|
||||||
|
expect(wrapper.text()).toContain('请填写商户私钥')
|
||||||
|
await wrapper.get('[aria-label="微信支付启用渠道"]').setValue(true)
|
||||||
|
await wrapper.get('[aria-label="微信支付商户私钥"]').setValue('private')
|
||||||
|
await wrapper.get('[aria-label="微信支付平台证书 / 验签公钥(兼容)"]').setValue('public')
|
||||||
|
await wrapper.get('[aria-label="微信支付APIv3 密钥"]').setValue('短密钥')
|
||||||
|
await wrapper.get('[data-channel="wechat"] form').trigger('submit')
|
||||||
|
expect(wrapper.text()).toContain('APIv3 密钥必须为 32 字节'); expect(calls.savePaymentChannel).not.toHaveBeenCalled()
|
||||||
|
wrapper.unmount()
|
||||||
|
})
|
||||||
|
it('accepts platform-only settings and validates the optional public-key pair', async () => {
|
||||||
|
const wrapper = mount(PaymentsPanel,options); await flushPromises()
|
||||||
|
await wrapper.get('[aria-label="微信支付启用渠道"]').setValue(true)
|
||||||
|
const form = wrapper.get('[data-channel="wechat"] form')
|
||||||
|
await form.trigger('submit'); await flushPromises()
|
||||||
|
expect(calls.savePaymentChannel).toHaveBeenCalledTimes(1)
|
||||||
|
await wrapper.get('[aria-label="微信支付启用渠道"]').setValue(true)
|
||||||
|
await wrapper.get('[aria-label="微信支付微信支付公钥 ID(推荐)"]').setValue('PUB_KEY_ID_test')
|
||||||
|
await form.trigger('submit')
|
||||||
|
expect(wrapper.text()).toContain('请完整填写微信支付公钥 ID 和微信支付公钥')
|
||||||
|
expect(calls.savePaymentChannel).toHaveBeenCalledTimes(1)
|
||||||
|
await wrapper.get('[aria-label="微信支付微信支付公钥(推荐)"]').setValue('new-public')
|
||||||
|
await form.trigger('submit'); await flushPromises()
|
||||||
|
expect(calls.savePaymentChannel).toHaveBeenLastCalledWith('wechat',expect.objectContaining({fields:expect.objectContaining({public_key_id:'PUB_KEY_ID_test'}),secrets:{public_key:'new-public'}}))
|
||||||
|
wrapper.unmount()
|
||||||
|
})
|
||||||
|
it('isolates failed channel loads, refreshes them and disables saving when unavailable', async () => {
|
||||||
|
calls.getPaymentChannel.mockRejectedValueOnce(new Error('secret-load-error'))
|
||||||
|
const wrapper = mount(PaymentsPanel,options); await flushPromises()
|
||||||
|
expect(wrapper.get('[data-channel="alipay"]').text()).toContain('渠道配置加载失败')
|
||||||
|
expect(wrapper.find('[data-channel="wechat"] form').exists()).toBe(true)
|
||||||
|
expect(wrapper.findAll('.el-table__body tbody tr')).toHaveLength(2)
|
||||||
|
expect(wrapper.html()).not.toContain('secret-load-error')
|
||||||
|
calls.getPaymentChannel.mockImplementation((channel:string) => Promise.resolve({data:{data:{...configuration(channel),can_save:false}}}))
|
||||||
|
await wrapper.findAll('button').find(button => button.text().includes('刷新支付数据'))!.trigger('click'); await flushPromises()
|
||||||
|
expect(wrapper.text()).toContain('当前不能保存配置')
|
||||||
|
await wrapper.get('[data-channel="alipay"] form').trigger('submit')
|
||||||
|
expect(calls.savePaymentChannel).not.toHaveBeenCalled(); wrapper.unmount()
|
||||||
|
})
|
||||||
|
it('allows disabling a channel without requiring replacement credentials', async () => {
|
||||||
|
const wrapper = mount(PaymentsPanel,options); await flushPromises()
|
||||||
|
await wrapper.get('[aria-label="支付宝启用渠道"]').setValue(false)
|
||||||
|
await wrapper.get('[aria-label="支付宝应用 ID"]').setValue('')
|
||||||
|
await wrapper.get('[data-channel="alipay"] form').trigger('submit'); await flushPromises()
|
||||||
|
expect(calls.savePaymentChannel.mock.calls[0]![1]).toMatchObject({enabled:false,secrets:{}})
|
||||||
|
wrapper.unmount()
|
||||||
|
})
|
||||||
|
|
||||||
|
it.each([
|
||||||
|
['payment_schema_unavailable',503,'支付配置数据库结构未就绪,请管理员备份数据库并执行最新迁移后重启服务'],
|
||||||
|
['configuration_key_unavailable',503,'支付配置无法解密,请检查服务端支付加密主密钥'],
|
||||||
|
['payment_schema_unavailable',401,'登录已失效,请重新登录'],
|
||||||
|
['configuration_key_unavailable',403,'无权限访问支付配置,请联系管理员'],
|
||||||
|
[undefined,404,'服务版本不支持该接口,请更新并重启服务'],
|
||||||
|
['unknown_code',503,null],
|
||||||
|
[undefined,undefined,null],
|
||||||
|
])('maps load and save errors safely for %s / %s', async (code,status,message) => {
|
||||||
|
const error = new ApiError('raw-server-secret PEM SQL token',code,status)
|
||||||
|
calls.getPaymentChannel.mockRejectedValueOnce(error)
|
||||||
|
const wrapper = mount(PaymentsPanel,options); await flushPromises()
|
||||||
|
expect(wrapper.get('[data-channel="alipay"] [role="alert"]').text()).toBe(message || '渠道配置加载失败,请刷新重试')
|
||||||
|
expect(wrapper.find('[data-channel="wechat"] form').exists()).toBe(true)
|
||||||
|
expect(wrapper.findAll('.el-table__body tbody tr')).toHaveLength(2)
|
||||||
|
expect(wrapper.html()).not.toContain('raw-server-secret')
|
||||||
|
await wrapper.findAll('button').find(button => button.text().includes('刷新支付数据'))!.trigger('click'); await flushPromises()
|
||||||
|
expect(wrapper.find('[data-channel="alipay"] [role="alert"]').exists()).toBe(false)
|
||||||
|
calls.savePaymentChannel.mockRejectedValueOnce(error)
|
||||||
|
await wrapper.get('[aria-label="支付宝商户私钥"]').setValue('replacement-secret')
|
||||||
|
await wrapper.get('[data-channel="alipay"] form').trigger('submit'); await flushPromises()
|
||||||
|
expect(wrapper.get('[data-channel="alipay"] [role="alert"]').text()).toBe(message || '保存失败:服务端校验未通过或暂不可用,请核对配置与密钥格式后重试')
|
||||||
|
expect(wrapper.get<HTMLInputElement>('[aria-label="支付宝商户私钥"]').element.value).toBe('')
|
||||||
|
expect(wrapper.html()).not.toMatch(/raw-server-secret|replacement-secret|PEM SQL token/)
|
||||||
|
expect(wrapper.text()).not.toContain('配置保存成功')
|
||||||
|
wrapper.unmount()
|
||||||
|
})
|
||||||
|
|
||||||
|
})
|
||||||
209
frontend/src/views/PaymentsPanel.vue
Normal file
209
frontend/src/views/PaymentsPanel.vue
Normal file
@@ -0,0 +1,209 @@
|
|||||||
|
<script setup lang="ts">
|
||||||
|
import { computed, onMounted, onUnmounted, ref, watch } from 'vue'
|
||||||
|
import { formatDateTime } from '../date-format'
|
||||||
|
import { getPaymentChannel, savePaymentChannel, listPaymentOrders, type PaymentChannelConfiguration, type PaymentChannelMetadata, type PaymentChannelSecrets, type PaymentOrder } from '../payments-api'
|
||||||
|
import type { PaymentChannel } from '../orders-api'
|
||||||
|
import { ApiError } from '../api'
|
||||||
|
function configurationError(error:unknown, fallback:string) {
|
||||||
|
if (!(error instanceof ApiError)) return fallback
|
||||||
|
if (error.status === 401) return '登录已失效,请重新登录'
|
||||||
|
if (error.status === 403) return '无权限访问支付配置,请联系管理员'
|
||||||
|
if (error.status === 404) return '服务版本不支持该接口,请更新并重启服务'
|
||||||
|
if (error.code === 'payment_schema_unavailable') return '支付配置数据库结构未就绪,请管理员备份数据库并执行最新迁移后重启服务'
|
||||||
|
if (error.code === 'configuration_key_unavailable') return '支付配置无法解密,请检查服务端支付加密主密钥'
|
||||||
|
return fallback
|
||||||
|
}
|
||||||
|
type Field = { key:keyof PaymentChannelMetadata; label:string; help:string }
|
||||||
|
type SecretField = { key:keyof PaymentChannelSecrets; label:string; help:string }
|
||||||
|
const ordinaryFields:Record<PaymentChannel, Field[]> = {
|
||||||
|
alipay:[
|
||||||
|
{key:'app_id',label:'应用 ID',help:'来源:支付宝开放平台 → 我的应用 → 应用详情。'},
|
||||||
|
{key:'seller_id',label:'卖家 ID',help:'来源:支付宝商家/开放平台账户信息中的商户 PID。'},
|
||||||
|
{key:'notify_url',label:'HTTPS 通知地址',help:'来源:本系统部署的公网 HTTPS 域名,加上 /api/v1/payments/alipay/notify 路径;反向代理有前缀时按实际地址填写。'},
|
||||||
|
],
|
||||||
|
wechat:[
|
||||||
|
{key:'app_id',label:'应用 ID',help:'来源:与微信支付商户号绑定的公众号、小程序或开放平台 AppID。'},
|
||||||
|
{key:'mch_id',label:'商户 ID',help:'来源:微信支付商户平台 → 账户中心 → 商户信息。'},
|
||||||
|
{key:'serial_no',label:'商户证书序列号',help:'来源:微信支付商户平台 → 账户中心 → API 安全 → 商户 API 证书详情。'},
|
||||||
|
{key:'public_key_id',label:'微信支付公钥 ID(推荐)',help:'来源:API 安全 → 微信支付公钥 → 申请/下载公钥后的公钥详情。通常以 PUB_KEY_ID_ 开头。'},
|
||||||
|
{key:'platform_serial',label:'平台证书序列号(兼容)',help:'来源:已通过微信支付官方工具或证书接口获取的微信支付平台证书,读取其序列号;兼容方案使用。'},
|
||||||
|
{key:'notify_url',label:'HTTPS 通知地址',help:'来源:本系统部署的公网 HTTPS 域名,加上 /api/v1/payments/wechat/notify 路径;反向代理有前缀时按实际地址填写。'},
|
||||||
|
],
|
||||||
|
}
|
||||||
|
const secretFields:Record<PaymentChannel, SecretField[]> = {
|
||||||
|
alipay:[
|
||||||
|
{key:'private_key',label:'商户私钥',help:'来源:配置应用接口加签时,由支付宝密钥工具或本地工具生成并保存的应用 RSA 私钥;与上传的应用公钥配对。'},
|
||||||
|
{key:'public_key',label:'支付宝验签公钥',help:'来源:支付宝开放平台应用 → 开发设置 → 接口加签;使用支付宝公钥。'},
|
||||||
|
],
|
||||||
|
wechat:[
|
||||||
|
{key:'private_key',label:'商户私钥',help:'来源:申请商户 API 证书时由证书工具生成并保存的 apiclient_key.pem。填写完整 PEM 私钥,与商户证书配对。'},
|
||||||
|
{key:'public_key',label:'微信支付公钥(推荐)',help:'来源:API 安全 → 微信支付公钥 → 下载的 PEM 公钥文件,必须与上方公钥 ID 配对。'},
|
||||||
|
{key:'platform_public_key',label:'平台证书 / 验签公钥(兼容)',help:'来源:从已获取的微信支付平台证书中提取的 RSA 公钥,或完整 PEM 平台证书;必须与上方平台证书序列号配对。'},
|
||||||
|
{key:'api_v3_key',label:'APIv3 密钥',help:'来源:API 安全 → APIv3 密钥;必须是当前设置的 32 字节密钥。'},
|
||||||
|
],
|
||||||
|
}
|
||||||
|
type ChannelForm = { channel:PaymentChannel; config:PaymentChannelConfiguration|null; enabled:boolean; fields:PaymentChannelMetadata; secrets:PaymentChannelSecrets; loading:boolean; saving:boolean; error:string; success:string }
|
||||||
|
const channels = ref<ChannelForm[]>(['alipay','wechat'].map(channel => ({channel:channel as PaymentChannel,config:null,enabled:false,fields:{app_id:'',notify_url:''},secrets:{},loading:true,saving:false,error:'',success:''})))
|
||||||
|
const expandedChannels = ref<Record<PaymentChannel, boolean>>({alipay:false,wechat:false})
|
||||||
|
const saving = computed(() => channels.value.some(form => form.saving))
|
||||||
|
const sourceName = (source:string) => ({environment:'服务端环境变量',database:'后台配置',none:'未配置'} as Record<string,string>)[source] || '未知来源'
|
||||||
|
// Allowlist ordinary fields and boolean flags; never assign returned secret material.
|
||||||
|
function applyConfiguration(form:ChannelForm, value:PaymentChannelConfiguration) {
|
||||||
|
form.config = {channel:form.channel,enabled:value.enabled,configuration_source:value.configuration_source,required_settings:[],version:value.version,effective:value.effective,can_save:value.can_save,fields:{app_id:'',notify_url:''},secret_fields:[]}
|
||||||
|
form.enabled = value.enabled === true; form.fields = {app_id:'',notify_url:''}; form.secrets = {}
|
||||||
|
for (const field of ordinaryFields[form.channel]) form.fields[field.key] = value.fields[field.key] || ''
|
||||||
|
for (const field of secretFields[form.channel]) form.config.secret_fields.push({name:field.key,configured:value.secret_fields.some(flag => flag.name === field.key && flag.configured === true)})
|
||||||
|
}
|
||||||
|
function configured(form:ChannelForm, key:keyof PaymentChannelSecrets) { return form.config?.secret_fields.some(field => field.name === key && field.configured) === true }
|
||||||
|
async function loadChannel(form:ChannelForm, current:number) {
|
||||||
|
form.loading = true; form.config = null; form.secrets = {}; form.error = ''; form.success = ''
|
||||||
|
try {
|
||||||
|
const response = await getPaymentChannel(form.channel)
|
||||||
|
if (current === request) applyConfiguration(form,response.data.data)
|
||||||
|
} catch (error) { if (current === request) form.error = configurationError(error, '渠道配置加载失败,请刷新重试') }
|
||||||
|
finally { if (current === request) form.loading = false }
|
||||||
|
}
|
||||||
|
function validate(form:ChannelForm) {
|
||||||
|
if (!form.enabled) return ''
|
||||||
|
for (const field of ordinaryFields[form.channel]) {
|
||||||
|
if (form.channel === 'wechat' && ['public_key_id','platform_serial'].includes(field.key)) continue
|
||||||
|
if (!form.fields[field.key]?.trim()) return `请填写${field.label}`
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
const url = new URL(form.fields.notify_url)
|
||||||
|
if (url.protocol !== 'https:' || url.username || url.password) return '通知地址必须为不含账号密码的 HTTPS 地址'
|
||||||
|
} catch { return '请填写有效的 HTTPS 通知地址' }
|
||||||
|
const hasSecret = (key:keyof PaymentChannelSecrets) => !!form.secrets[key]?.trim() || configured(form,key)
|
||||||
|
for (const field of secretFields[form.channel]) {
|
||||||
|
if (form.channel === 'wechat' && ['public_key','platform_public_key'].includes(field.key)) continue
|
||||||
|
if (!hasSecret(field.key)) return `请填写${field.label}`
|
||||||
|
}
|
||||||
|
if (form.channel === 'wechat') {
|
||||||
|
const publicID = form.fields.public_key_id?.trim() || ''
|
||||||
|
const platformID = form.fields.platform_serial?.trim() || ''
|
||||||
|
if (publicID && (!/^PUB_KEY_ID_.+/.test(publicID) || !hasSecret('public_key'))) return '请完整填写微信支付公钥 ID 和微信支付公钥'
|
||||||
|
if (platformID && !hasSecret('platform_public_key')) return '请完整填写平台证书序列号和平台验签公钥'
|
||||||
|
if (hasSecret('public_key') && !publicID) return '请填写微信支付公钥 ID'
|
||||||
|
if (hasSecret('platform_public_key') && !platformID) return '请填写平台证书序列号'
|
||||||
|
if (!publicID && !platformID) return '请至少配置一组微信支付公钥或平台证书验签方案'
|
||||||
|
}
|
||||||
|
if (form.channel === 'wechat' && form.secrets.api_v3_key && new TextEncoder().encode(form.secrets.api_v3_key).length !== 32) return 'APIv3 密钥必须为 32 字节'
|
||||||
|
return ''
|
||||||
|
}
|
||||||
|
async function saveChannel(form:ChannelForm) {
|
||||||
|
if (form.saving || form.loading || loading.value || !form.config || form.config.can_save === false) return
|
||||||
|
form.success = ''; form.error = validate(form)
|
||||||
|
if (form.error) return
|
||||||
|
const current = request
|
||||||
|
const secrets:PaymentChannelSecrets = {}
|
||||||
|
for (const field of secretFields[form.channel]) if (form.secrets[field.key]?.trim()) secrets[field.key] = form.secrets[field.key]
|
||||||
|
const fields:PaymentChannelMetadata = {app_id:'',notify_url:''}
|
||||||
|
for (const field of ordinaryFields[form.channel]) fields[field.key] = form.fields[field.key]?.trim() || ''
|
||||||
|
form.saving = true; form.secrets = {}
|
||||||
|
try {
|
||||||
|
const response = await savePaymentChannel(form.channel,{enabled:form.enabled,fields,secrets})
|
||||||
|
if (current !== request) return
|
||||||
|
applyConfiguration(form,response.data.data)
|
||||||
|
form.success = '配置保存成功;配置校验不代表真实交易联调通过'
|
||||||
|
} catch (error) {
|
||||||
|
// Use only fixed allowlisted messages, never server messages or credential values.
|
||||||
|
if (current === request) form.error = configurationError(error, '保存失败:服务端校验未通过或暂不可用,请核对配置与密钥格式后重试')
|
||||||
|
} finally { if (current === request) form.saving = false }
|
||||||
|
}
|
||||||
|
|
||||||
|
const orders = ref<PaymentOrder[]>([])
|
||||||
|
const loading = ref(false), ordersError = ref('')
|
||||||
|
const channelFilter = ref(''), statusFilter = ref(''), query = ref(''), page = ref(1)
|
||||||
|
const channelName = (channel:string) => ({alipay:'支付宝',wechat:'微信支付'} as Record<string,string>)[channel] || '未知渠道'
|
||||||
|
const statusName = (status:string) => ({created:'待支付',pending:'待支付',paid:'已支付',failed:'失败',expired:'已失效',cancelled:'已取消',closed:'已关闭',pending_payment:'待支付',issued:'授权已开通',authorization_removed:'授权已移除'} as Record<string,string>)[status] || '未知状态'
|
||||||
|
const stateClass = (status:string) => ['paid','issued'].includes(status) ? 'is-success' : ['created','pending','pending_payment'].includes(status) ? 'is-pending' : 'is-inactive'
|
||||||
|
const statuses = computed(() => [...new Set(orders.value.map(row => row.status))])
|
||||||
|
const filtered = computed(() => orders.value.filter(row => (!channelFilter.value || row.channel === channelFilter.value) && (!statusFilter.value || row.status === statusFilter.value) && (!query.value.trim() || [row.order_id,row.merchant_order_no,row.channel_trade_no || ''].some(value => String(value).toLowerCase().includes(query.value.trim().toLowerCase())))))
|
||||||
|
const pagedOrders = computed(() => filtered.value.slice((page.value - 1) * 20, page.value * 20))
|
||||||
|
watch([channelFilter, statusFilter, query], () => { page.value = 1 })
|
||||||
|
const amount = (row:PaymentOrder) => `${(row.amount_cents / 100).toFixed(2)} ${row.currency}`
|
||||||
|
const dateColumns = [{key:'paid_at',label:'支付时间'},{key:'created_at',label:'创建时间'},{key:'expires_at',label:'二维码展示期限'}] as const
|
||||||
|
let request = 0
|
||||||
|
async function refresh() {
|
||||||
|
if (saving.value) return
|
||||||
|
const current = ++request
|
||||||
|
page.value = 1; loading.value = true; ordersError.value = ''; orders.value = []
|
||||||
|
const [orderResult] = await Promise.all([
|
||||||
|
Promise.allSettled([listPaymentOrders()]).then(results => results[0]!),
|
||||||
|
Promise.all(channels.value.map(form => loadChannel(form,current))),
|
||||||
|
])
|
||||||
|
if (current !== request) return
|
||||||
|
if (orderResult.status === 'fulfilled') orders.value = orderResult.value.data.data
|
||||||
|
else ordersError.value = '支付流水加载失败,请刷新重试'
|
||||||
|
loading.value = false
|
||||||
|
}
|
||||||
|
function reset() { channelFilter.value = ''; statusFilter.value = ''; query.value = ''; page.value = 1 }
|
||||||
|
onMounted(refresh)
|
||||||
|
onUnmounted(() => { request++; channels.value.forEach(form => { form.secrets = {} }) })
|
||||||
|
</script>
|
||||||
|
<template>
|
||||||
|
<section class="payment-workspace" aria-labelledby="payment-title">
|
||||||
|
<header class="payment-heading"><div><p class="payment-eyebrow">支付管理</p><h2 id="payment-title">支付渠道与流水</h2><p class="payment-description">管理员为已有客户创建订单后,在订单页面生成付款链接。</p></div><el-button :loading="loading" :disabled="loading || saving" @click="refresh"><span aria-hidden="true">↻</span> 刷新支付数据</el-button></header>
|
||||||
|
<section class="payment-config" aria-labelledby="channel-title">
|
||||||
|
<div class="payment-subheading"><h3 id="channel-title">渠道配置</h3><span class="payment-muted">管理员配置 · 密钥不回显</span></div>
|
||||||
|
<p class="payment-description">普通字段可编辑;密钥留空保留现值,填写新值表示替换。配置校验不代表真实交易联调通过。</p>
|
||||||
|
<p v-if="loading" role="status">正在加载支付数据…</p>
|
||||||
|
<div class="channel-grid"><article v-for="form in channels" :key="form.channel" class="channel-card" :data-channel="form.channel">
|
||||||
|
<button type="button" class="channel-toggle" :aria-label="`${channelName(form.channel)}渠道配置`" :aria-expanded="expandedChannels[form.channel]" :aria-controls="`channel-details-${form.channel}`" @click="expandedChannels[form.channel] = !expandedChannels[form.channel]">
|
||||||
|
<span class="channel-toggle-title">{{ channelName(form.channel) }}<span v-if="form.config?.enabled !== undefined" class="payment-state" :class="form.config?.enabled ? 'is-success' : 'is-inactive'"><i aria-hidden="true"></i>{{ form.config?.enabled ? '已启用' : '未启用' }}</span></span>
|
||||||
|
<span class="channel-toggle-action">{{ expandedChannels[form.channel] ? '收起' : '展开配置' }} <span aria-hidden="true">{{ expandedChannels[form.channel] ? '⌃' : '⌄' }}</span></span>
|
||||||
|
</button>
|
||||||
|
<p v-if="form.loading" role="status">正在加载渠道配置…</p>
|
||||||
|
<div v-show="expandedChannels[form.channel]" :id="`channel-details-${form.channel}`" class="channel-details">
|
||||||
|
<template v-if="form.config">
|
||||||
|
<p>配置来源:{{ sourceName(form.config.configuration_source || '') }}</p>
|
||||||
|
<p v-if="form.config.version != null">配置版本:{{ form.config.version }}</p>
|
||||||
|
<p v-if="form.config.effective !== undefined">{{ form.config.effective ? '已生效' : '未生效' }}</p>
|
||||||
|
<p v-if="form.config.can_save === false" class="payment-error" role="alert">当前不能保存配置,请联系管理员检查服务端支付配置加密主密钥及配置服务。</p>
|
||||||
|
<form autocomplete="off" @submit.prevent="saveChannel(form)"><fieldset :disabled="form.saving || loading || form.config.can_save === false">
|
||||||
|
<label class="channel-enabled"><input v-model="form.enabled" type="checkbox" :aria-label="`${channelName(form.channel)}启用渠道`">启用渠道</label>
|
||||||
|
<label v-for="field in ordinaryFields[form.channel]" :key="field.key" class="channel-field"><span>{{ field.label }}</span><small class="channel-help">{{ field.help }}</small><el-input v-model="form.fields[field.key]" :disabled="form.saving || loading || form.config.can_save === false" :aria-label="`${channelName(form.channel)}${field.label}`" autocomplete="off"/></label>
|
||||||
|
<label v-for="field in secretFields[form.channel]" :key="field.key" class="channel-field"><span>{{ field.label }} <small>{{ configured(form,field.key) ? '已配置' : '未配置' }}</small></span><small class="channel-help">{{ field.help }}</small><el-input v-model="form.secrets[field.key]" :disabled="form.saving || loading || form.config.can_save === false" type="password" :aria-label="`${channelName(form.channel)}${field.label}`" autocomplete="new-password" placeholder="留空保留现值;填写新值替换"/></label>
|
||||||
|
<el-button native-type="submit" type="primary" :loading="form.saving" :disabled="form.saving || loading || form.config.can_save === false">{{ form.saving ? '正在保存…' : '保存配置' }}</el-button>
|
||||||
|
</fieldset></form>
|
||||||
|
</template>
|
||||||
|
</div>
|
||||||
|
<p v-if="form.error" class="payment-error" role="alert">{{ form.error }}</p>
|
||||||
|
<p v-if="form.success" class="payment-success" role="status">{{ form.success }}</p>
|
||||||
|
</article></div>
|
||||||
|
</section>
|
||||||
|
<section class="payment-list" aria-label="支付流水列表">
|
||||||
|
<div class="payment-list-toolbar"><div class="payment-list-title"><h3>支付流水</h3><span class="payment-count">{{ filtered.length }} / {{ orders.length }} 条</span></div><router-link class="payment-order-link" to="/orders">去订单创建付款链接 →</router-link></div>
|
||||||
|
<p class="payment-description">最近 100 条支付流水,筛选与分页仅作用于本次加载的数据,数量不代表服务端全部记录。日期为本地时间。</p>
|
||||||
|
<div class="payment-filters"><el-input v-model="query" clearable aria-label="搜索支付流水" placeholder="订单 ID / 商户单号 / 渠道单号"/><label class="payment-filter"><span>渠道</span><el-select v-model="channelFilter" aria-label="支付渠道筛选"><el-option value="" label="全部渠道"/><el-option value="alipay" label="支付宝"/><el-option value="wechat" label="微信支付"/></el-select></label><label class="payment-filter"><span>状态</span><el-select v-model="statusFilter" aria-label="支付状态筛选"><el-option value="" label="全部状态"/><el-option v-for="status in statuses" :key="status" :value="status" :label="statusName(status)"/></el-select></label><el-button @click="reset">重置筛选</el-button></div>
|
||||||
|
<p v-if="ordersError" class="payment-error" role="alert">{{ ordersError }}</p>
|
||||||
|
<div class="payment-table-wrap"><el-table :data="pagedOrders" row-key="id" v-loading="loading" :empty-text="loading ? '正在加载支付数据…' : ordersError ? '支付流水加载失败,请刷新重试' : '暂无符合条件的支付流水'">
|
||||||
|
<el-table-column prop="id" label="支付 ID" width="90"/><el-table-column prop="order_id" label="订单 ID" width="90"/>
|
||||||
|
<el-table-column label="商户单号" min-width="200"><template #default="{ row }"><code class="payment-trade" :title="row.merchant_order_no">{{ row.merchant_order_no }}</code></template></el-table-column>
|
||||||
|
<el-table-column label="渠道" width="100"><template #default="{ row }">{{ channelName(row.channel) }}</template></el-table-column>
|
||||||
|
<el-table-column label="渠道交易号" min-width="200"><template #default="{ row }"><code class="payment-trade" :title="row.channel_trade_no || ''">{{ row.channel_trade_no || '—' }}</code></template></el-table-column>
|
||||||
|
<el-table-column label="金额" width="140"><template #default="{ row }">{{ amount(row) }}</template></el-table-column>
|
||||||
|
<el-table-column label="支付状态" width="130"><template #default="{ row }"><span class="payment-state" :class="stateClass(row.status)"><i aria-hidden="true"></i>{{ statusName(row.status) }}</span></template></el-table-column>
|
||||||
|
<el-table-column label="订单状态" width="150"><template #default="{ row }"><span class="payment-state" :class="stateClass(row.order_status)"><i aria-hidden="true"></i>{{ statusName(row.order_status) }}</span></template></el-table-column>
|
||||||
|
<el-table-column label="授权 ID" width="90"><template #default="{ row }">{{ row.license_id ?? '—' }}</template></el-table-column>
|
||||||
|
<el-table-column v-for="column in dateColumns" :key="column.key" :label="column.label" width="190"><template #default="{ row }">{{ formatDateTime(row[column.key]) }}</template></el-table-column>
|
||||||
|
<el-table-column label="异常" min-width="260"><template #default="{ row }">{{ row.last_error ? '存在支付异常,请核查服务端记录' : '—' }}</template></el-table-column>
|
||||||
|
</el-table></div>
|
||||||
|
<div class="payment-pagination"><span>本次加载 {{ orders.length }} 条 · 筛选后 {{ filtered.length }} 条 · 每页 20 条</span><el-pagination v-model:current-page="page" :total="filtered.length" :page-size="20" layout="prev, pager, next"/></div>
|
||||||
|
</section>
|
||||||
|
</section>
|
||||||
|
</template>
|
||||||
|
<style scoped>
|
||||||
|
.payment-workspace{--payment-line:#e5eaf0;--payment-muted:#687586;color:#17202b}
|
||||||
|
.payment-heading{display:flex;justify-content:space-between;align-items:center;gap:18px;padding-bottom:21px;border-bottom:1px solid var(--payment-line)}.payment-heading h2{margin:0;font-size:20px;line-height:1.35}.payment-eyebrow{margin:0 0 5px;color:#1769e0;font-size:11px;font-weight:700}
|
||||||
|
.payment-description{margin:5px 0 0;color:var(--payment-muted);font-size:13px;line-height:1.6}.payment-config{margin-top:20px;padding:18px 20px;background:#f7f9fc;border:1px solid var(--payment-line);border-radius:7px}
|
||||||
|
.payment-subheading,.payment-list-toolbar,.payment-list-title,.payment-pagination{display:flex;align-items:center;gap:12px}.payment-subheading,.payment-list-toolbar,.payment-pagination{justify-content:space-between}.payment-subheading h3,.payment-subheading h4,.payment-list-title h3{margin:0;font-size:14px;font-weight:650}.payment-muted,.payment-count{color:var(--payment-muted);font-size:12px}
|
||||||
|
.channel-grid{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:16px;margin-top:17px}.channel-card{border:1px solid var(--payment-line);border-radius:6px;padding:16px;background:#fff;min-width:0;overflow-wrap:anywhere}.channel-card p,.channel-card li{color:#526173;font-size:12px}.channel-card ul{margin:8px 0 0;padding-left:18px}.channel-card li{margin:6px 0}
|
||||||
|
.channel-toggle{display:flex;align-items:center;justify-content:space-between;gap:12px;width:100%;padding:0;border:0;background:transparent;color:inherit;font:inherit;text-align:left;cursor:pointer}.channel-toggle-title{display:flex;align-items:center;gap:12px;font-size:14px;font-weight:650}.channel-toggle-action{flex-shrink:0;color:#1769e0;font-size:12px}.channel-toggle:focus-visible{outline:2px solid #1769e0;outline-offset:5px;border-radius:3px}.channel-details{margin-top:14px;padding-top:2px;border-top:1px solid var(--payment-line)}
|
||||||
|
.channel-card fieldset{border:0;padding:0;margin:14px 0 0;min-width:0}.channel-enabled{display:flex;align-items:center;gap:8px;font-size:13px}.channel-field{display:flex;flex-direction:column;gap:6px;margin:13px 0;color:#526173;font-size:12px}.channel-field>span small{margin-left:8px;color:var(--payment-muted)}.channel-help{display:block;margin:0;color:#7a8797;font-size:11px;line-height:1.5}.payment-success{color:#16845b;font-size:13px;line-height:1.6}
|
||||||
|
.payment-list{margin-top:24px}.payment-list-toolbar{min-height:36px;margin-bottom:12px}.payment-count{padding:3px 7px;border-radius:4px;background:#f0f3f7}.payment-order-link{color:#1769e0;font-size:12px;text-decoration:none}.payment-filters{display:flex;align-items:center;gap:12px;flex-wrap:wrap;margin:16px 0 12px}.payment-filters>.el-input{flex:1;min-width:230px}.payment-filter{display:flex;align-items:center;gap:9px;color:#526173;font-size:12px}.payment-filter :deep(.el-select){width:150px}
|
||||||
|
.payment-table-wrap{width:100%;overflow-x:auto;border:1px solid var(--payment-line);border-radius:6px}.payment-table-wrap :deep(.el-table){min-width:850px}.payment-table-wrap :deep(.el-table th.el-table__cell){height:42px;background:#f7f9fc;color:#657387;font-size:12px;font-weight:600}.payment-table-wrap :deep(.el-table td.el-table__cell){height:57px;color:#354255;font-size:13px}
|
||||||
|
.payment-trade,.channel-card code{font-family:ui-monospace,SFMono-Regular,Consolas,monospace;font-size:12px}.payment-trade{display:block;overflow:hidden;color:#526173;text-overflow:ellipsis;white-space:nowrap}.payment-state{display:inline-flex;align-items:center;gap:6px;font-size:12px;font-weight:600;white-space:nowrap}.payment-state i{width:7px;height:7px;border-radius:50%;background:#98a3b2}.payment-state.is-success{color:#16845b}.payment-state.is-success i{background:#20a36a}.payment-state.is-pending{color:#8b640e}.payment-state.is-pending i{background:#d69a28}.payment-state.is-inactive{color:#687586}
|
||||||
|
.payment-error{margin:12px 0;color:#b44830;font-size:13px}.payment-pagination{margin-top:12px;color:var(--payment-muted);font-size:12px}.payment-pagination :deep(.el-pagination){margin-top:0}
|
||||||
|
@media(max-width:900px){.payment-filters>.el-input{flex-basis:100%}}@media(max-width:620px){.payment-heading{align-items:flex-start;flex-wrap:wrap}.payment-config{padding:15px}.payment-subheading{align-items:flex-start;flex-wrap:wrap}.channel-grid{grid-template-columns:minmax(0,1fr)}.payment-list-toolbar,.payment-pagination{align-items:flex-start;flex-direction:column}.payment-filter{justify-content:space-between;width:100%}.payment-filter :deep(.el-select){width:min(72%,280px)}.payment-pagination :deep(.el-pagination){padding-left:0}}
|
||||||
|
</style>
|
||||||
@@ -3,6 +3,14 @@ $ErrorActionPreference = 'Stop'
|
|||||||
$root = Split-Path $PSScriptRoot -Parent
|
$root = Split-Path $PSScriptRoot -Parent
|
||||||
Set-Location $root
|
Set-Location $root
|
||||||
|
|
||||||
|
$localPaymentKey = Join-Path $root 'secrets/payment-config.key'
|
||||||
|
if (-not $env:PAYMENT_CONFIG_ENCRYPTION_KEY_FILE) {
|
||||||
|
if (-not (Test-Path -LiteralPath $localPaymentKey)) {
|
||||||
|
throw "Missing local payment config key: $localPaymentKey"
|
||||||
|
}
|
||||||
|
$env:PAYMENT_CONFIG_ENCRYPTION_KEY_FILE = $localPaymentKey
|
||||||
|
}
|
||||||
|
|
||||||
if ($Mode -eq 'Api') {
|
if ($Mode -eq 'Api') {
|
||||||
Set-Location (Join-Path $root 'backend')
|
Set-Location (Join-Path $root 'backend')
|
||||||
& go run ./cmd/server
|
& go run ./cmd/server
|
||||||
@@ -114,6 +122,7 @@ try {
|
|||||||
$password = $null
|
$password = $null
|
||||||
$env:HTTP_ADDR = '127.0.0.1:18081'
|
$env:HTTP_ADDR = '127.0.0.1:18081'
|
||||||
$env:SESSION_COOKIE_SECURE = 'false'
|
$env:SESSION_COOKIE_SECURE = 'false'
|
||||||
|
$env:PAYMENT_CONFIG_ENCRYPTION_KEY_FILE = $localPaymentKey
|
||||||
$env:ENTRY_LIMIT_MODE = 'local-dev'
|
$env:ENTRY_LIMIT_MODE = 'local-dev'
|
||||||
$env:METRICS_ADDR = ''
|
$env:METRICS_ADDR = ''
|
||||||
# Preserve explicitly supplied protected signing key and keyring paths.
|
# Preserve explicitly supplied protected signing key and keyring paths.
|
||||||
|
|||||||
Reference in New Issue
Block a user