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