feat: add client self-service purchases and integration kit
Co-Authored-By: Craft Agent <agents-noreply@craft.do>
This commit is contained in:
312
backend/internal/httpapi/purchase_client.go
Normal file
312
backend/internal/httpapi/purchase_client.go
Normal file
@@ -0,0 +1,312 @@
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"database/sql"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"github.com/gin-gonic/gin"
|
||||
"io"
|
||||
"license-platform/backend/internal/payments"
|
||||
"net/http"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
type purchaseScope struct{ ID, Customer, Product, Actor uint64 }
|
||||
|
||||
func limitedPurchaseBody(c *gin.Context, n int64) io.ReadCloser {
|
||||
return http.MaxBytesReader(c.Writer, c.Request.Body, n)
|
||||
}
|
||||
func (a *BusinessAPI) purchaseAuthenticated(c *gin.Context) {
|
||||
c.Header("Cache-Control", "no-store")
|
||||
auth := c.GetHeader("Authorization")
|
||||
if !strings.HasPrefix(auth, "Bearer ") {
|
||||
apiError(c, 401, "invalid_purchase_credential", "购买凭据无效")
|
||||
c.Abort()
|
||||
return
|
||||
}
|
||||
raw, e := hex.DecodeString(strings.TrimPrefix(auth, "Bearer "))
|
||||
if e != nil || len(raw) != 32 {
|
||||
apiError(c, 401, "invalid_purchase_credential", "购买凭据无效")
|
||||
c.Abort()
|
||||
return
|
||||
}
|
||||
sum := sha256.Sum256(raw)
|
||||
var s purchaseScope
|
||||
e = a.db.QueryRowContext(c, `SELECT pc.id,pc.customer_id,pc.product_id,pc.created_by FROM purchase_credentials pc JOIN customers cu ON cu.id=pc.customer_id JOIN products p ON p.id=pc.product_id JOIN admins ad ON ad.id=pc.created_by WHERE pc.token_hash=? AND pc.enabled=1 AND cu.status='active' AND p.active=1 AND ad.active=1 AND ad.role='admin'`, sum[:]).Scan(&s.ID, &s.Customer, &s.Product, &s.Actor)
|
||||
if e != nil {
|
||||
apiError(c, 401, "invalid_purchase_credential", "购买凭据无效")
|
||||
c.Abort()
|
||||
return
|
||||
}
|
||||
c.Set("purchase_scope", s)
|
||||
c.Next()
|
||||
}
|
||||
func scopeOf(c *gin.Context) purchaseScope { return c.MustGet("purchase_scope").(purchaseScope) }
|
||||
func (a *BusinessAPI) clientPlans(c *gin.Context) {
|
||||
s := scopeOf(c)
|
||||
rows, e := a.db.QueryContext(c, "SELECT "+planColumns+" FROM payment_plans WHERE product_id=? AND enabled=1 ORDER BY id LIMIT 1000", s.Product)
|
||||
if e != nil {
|
||||
purchaseFailure(c)
|
||||
return
|
||||
}
|
||||
out := []paymentPlan{}
|
||||
for rows.Next() {
|
||||
var p paymentPlan
|
||||
if scanPlan(rows, &p) != nil {
|
||||
rows.Close()
|
||||
purchaseFailure(c)
|
||||
return
|
||||
}
|
||||
out = append(out, p)
|
||||
}
|
||||
e = rows.Err()
|
||||
rows.Close()
|
||||
if e != nil {
|
||||
purchaseFailure(c)
|
||||
return
|
||||
}
|
||||
channels := []string{}
|
||||
for _, channel := range []string{"alipay", "wechat"} {
|
||||
var v sql.NullInt64
|
||||
var enabled bool
|
||||
if a.db.QueryRowContext(c, "SELECT c.active_version,v.enabled FROM payment_channel_configs c JOIN payment_channel_config_versions v ON v.channel=c.channel AND v.version=c.active_version WHERE c.channel=?", channel).Scan(&v, &enabled) == nil && enabled {
|
||||
channels = append(channels, channel)
|
||||
}
|
||||
}
|
||||
c.JSON(200, gin.H{"data": gin.H{"plans": out, "channels": channels, "license_duration": "fixed_days_from_payment", "purchase_mode": "new_purchase", "customer_setup": "由管理员在客户管理中预配置既有客户,并为该客户及产品创建购买凭据"}})
|
||||
}
|
||||
|
||||
type clientPurchaseInput struct {
|
||||
PlanID uint64 `json:"plan_id"`
|
||||
PlanVersion uint64 `json:"plan_version"`
|
||||
Installation string `json:"installation_id"`
|
||||
Channel string `json:"channel"`
|
||||
}
|
||||
|
||||
// A restricted service context, never an admin Gin context. Creator is audit attribution only.
|
||||
func lockPurchaseScope(ctx context.Context, tx *sql.Tx, s purchaseScope) error {
|
||||
var id uint64
|
||||
return tx.QueryRowContext(ctx, `SELECT pc.id FROM purchase_credentials pc JOIN admins a ON a.id=pc.created_by JOIN customers c ON c.id=pc.customer_id JOIN products p ON p.id=pc.product_id WHERE pc.id=? AND pc.customer_id=? AND pc.product_id=? AND pc.enabled=1 AND a.active=1 AND a.role='admin' AND c.status='active' AND p.active=1 FOR UPDATE`, s.ID, s.Customer, s.Product).Scan(&id)
|
||||
}
|
||||
func (a *BusinessAPI) clientCreatePurchase(c *gin.Context) {
|
||||
var in clientPurchaseInput
|
||||
key := c.GetHeader("Idempotency-Key")
|
||||
c.Request.Body = limitedPurchaseBody(c, 4096)
|
||||
if c.ShouldBindJSON(&in) != nil || in.PlanID == 0 || in.PlanVersion == 0 || !visibleASCII(in.Installation, 128) || !visibleASCII(key, 128) || (in.Channel != "alipay" && in.Channel != "wechat") {
|
||||
apiError(c, 400, "invalid_request", "购买参数或幂等键无效")
|
||||
return
|
||||
}
|
||||
if len(a.credentialEncryptionKey) != 32 {
|
||||
apiError(c, 503, "credentials_unavailable", "请配置独立实例凭据加密密钥")
|
||||
return
|
||||
}
|
||||
s := scopeOf(c)
|
||||
payload, _ := json.Marshal(in)
|
||||
fp := sha256.Sum256(payload)
|
||||
tx, e := a.db.BeginTx(c, nil)
|
||||
if e != nil {
|
||||
purchaseFailure(c)
|
||||
return
|
||||
}
|
||||
defer tx.Rollback()
|
||||
if lockPurchaseScope(c, tx, s) != nil {
|
||||
apiError(c, 401, "invalid_purchase_credential", "购买凭据无效")
|
||||
return
|
||||
}
|
||||
var old []byte
|
||||
var order uint64
|
||||
e = tx.QueryRowContext(c, "SELECT order_id,request_fingerprint FROM client_purchases WHERE credential_id=? AND idempotency_key=?", s.ID, key).Scan(&order, &old)
|
||||
if e == nil {
|
||||
if !bytesEqual(old, fp[:]) {
|
||||
apiError(c, 409, "idempotency_conflict", "幂等键请求冲突")
|
||||
return
|
||||
}
|
||||
if tx.Commit() != nil {
|
||||
purchaseFailure(c)
|
||||
return
|
||||
}
|
||||
a.respondPurchase(c, s, order, true)
|
||||
return
|
||||
}
|
||||
if !errors.Is(e, sql.ErrNoRows) {
|
||||
purchaseFailure(c)
|
||||
return
|
||||
}
|
||||
var p paymentPlan
|
||||
e = scanPlan(tx.QueryRowContext(c, "SELECT "+planColumns+" FROM payment_plans WHERE id=? AND product_id=? FOR UPDATE", in.PlanID, s.Product), &p)
|
||||
if e != nil {
|
||||
apiError(c, 404, "not_found", "套餐不存在")
|
||||
return
|
||||
}
|
||||
if !p.Enabled {
|
||||
apiError(c, 409, "plan_disabled", "套餐已停用")
|
||||
return
|
||||
}
|
||||
if p.Version != in.PlanVersion {
|
||||
apiError(c, 409, "plan_version_conflict", "套餐版本已变化,请刷新套餐")
|
||||
return
|
||||
}
|
||||
if !validPlan(p) || !time.Now().UTC().Add(time.Duration(p.LicenseDays)*24*time.Hour).Before(time.Date(2038, 1, 19, 3, 14, 7, 0, time.UTC)) {
|
||||
apiError(c, 409, "invalid_plan", "套餐期限无效")
|
||||
return
|
||||
}
|
||||
var version sql.NullInt64
|
||||
if tx.QueryRowContext(c, "SELECT active_version FROM payment_channel_configs WHERE channel=? FOR UPDATE", in.Channel).Scan(&version) != nil || !version.Valid {
|
||||
apiError(c, 503, "channel_unavailable", "请由管理员发布支付渠道配置")
|
||||
return
|
||||
}
|
||||
var enabled bool
|
||||
var encrypted []byte
|
||||
if tx.QueryRowContext(c, "SELECT enabled,config_encrypted FROM payment_channel_config_versions WHERE channel=? AND version=?", in.Channel, version.Int64).Scan(&enabled, &encrypted) != nil || !enabled {
|
||||
apiError(c, 503, "channel_unavailable", "支付渠道未启用")
|
||||
return
|
||||
}
|
||||
config, e := decryptPaymentConfig(a.paymentConfigEncryptionKey, in.Channel, version.Int64, encrypted)
|
||||
if e != nil {
|
||||
apiError(c, 503, "configuration_unavailable", "支付配置不可用")
|
||||
return
|
||||
}
|
||||
if _, e = payments.NewProvider(in.Channel, config); e != nil {
|
||||
apiError(c, 503, "channel_unavailable", "支付渠道不可用")
|
||||
return
|
||||
}
|
||||
orderNo, e := randomPaymentToken(16)
|
||||
if e != nil {
|
||||
purchaseFailure(c)
|
||||
return
|
||||
}
|
||||
merchant, e := randomPaymentToken(16)
|
||||
if e != nil {
|
||||
purchaseFailure(c)
|
||||
return
|
||||
}
|
||||
checkout, e := randomPaymentToken(32)
|
||||
if e != nil {
|
||||
purchaseFailure(c)
|
||||
return
|
||||
}
|
||||
expires := time.Now().UTC().Add(30 * time.Minute)
|
||||
res, e := tx.ExecContext(c, "INSERT INTO offline_orders(order_no,customer_id,product_id,amount_cents,currency,created_by,payment_channel,payment_expires_at) VALUES(?,?,?,?,?,?,?,?)", orderNo, s.Customer, s.Product, p.AmountCents, p.Currency, s.Actor, in.Channel, expires)
|
||||
if e != nil {
|
||||
purchaseFailure(c)
|
||||
return
|
||||
}
|
||||
oid, e := res.LastInsertId()
|
||||
if e != nil {
|
||||
purchaseFailure(c)
|
||||
return
|
||||
}
|
||||
order = uint64(oid)
|
||||
_, e = tx.ExecContext(c, "INSERT INTO payment_orders(order_id,merchant_order_no,channel,amount_cents,currency,license_days,checkout_token,expires_at,provider_config_version,plan_id,plan_version) VALUES(?,?,?,?,?,?,?,?,?,?,?)", order, merchant, in.Channel, p.AmountCents, p.Currency, p.LicenseDays, checkout, expires, version, p.ID, p.Version)
|
||||
if e == nil {
|
||||
_, e = tx.ExecContext(c, "INSERT INTO client_purchases(order_id,credential_id,installation_id,idempotency_key,request_fingerprint) VALUES(?,?,?,?,?)", order, s.ID, in.Installation, key, fp[:])
|
||||
}
|
||||
if e == nil {
|
||||
_, e = tx.ExecContext(c, "INSERT INTO audit_events(actor_admin_id,action,resource_type,resource_id,details) VALUES(?,'purchase.created','order',?,'{}')", s.Actor, order)
|
||||
}
|
||||
if e != nil || tx.Commit() != nil {
|
||||
purchaseFailure(c)
|
||||
return
|
||||
}
|
||||
a.respondPurchase(c, s, order, true)
|
||||
}
|
||||
|
||||
type purchaseLookup struct {
|
||||
OrderNo string `json:"order_no"`
|
||||
Installation string `json:"installation_id"`
|
||||
Key string `json:"idempotency_key"`
|
||||
}
|
||||
|
||||
func (a *BusinessAPI) lookupClientPurchase(c *gin.Context, claim bool) (purchaseScope, uint64, bool) {
|
||||
s := scopeOf(c)
|
||||
var in purchaseLookup
|
||||
c.Request.Body = limitedPurchaseBody(c, 4096)
|
||||
if c.ShouldBindJSON(&in) != nil || !visibleASCII(in.Installation, 128) || (claim && len(in.OrderNo) != 32) || (in.OrderNo == "" && !visibleASCII(in.Key, 128)) || (in.OrderNo != "" && len(in.OrderNo) != 32) {
|
||||
apiError(c, 400, "invalid_request", "订单查询参数无效")
|
||||
return s, 0, false
|
||||
}
|
||||
var order uint64
|
||||
query := "SELECT cp.order_id FROM client_purchases cp JOIN offline_orders o ON o.id=cp.order_id WHERE cp.credential_id=? AND cp.installation_id=? AND "
|
||||
var e error
|
||||
if in.OrderNo != "" {
|
||||
e = a.db.QueryRowContext(c, query+"o.order_no=?", s.ID, in.Installation, in.OrderNo).Scan(&order)
|
||||
} else {
|
||||
e = a.db.QueryRowContext(c, query+"cp.idempotency_key=?", s.ID, in.Installation, in.Key).Scan(&order)
|
||||
}
|
||||
if errors.Is(e, sql.ErrNoRows) {
|
||||
apiError(c, 404, "not_found", "订单不存在")
|
||||
return s, 0, false
|
||||
}
|
||||
if e != nil {
|
||||
purchaseFailure(c)
|
||||
return s, 0, false
|
||||
}
|
||||
return s, order, true
|
||||
}
|
||||
func (a *BusinessAPI) clientPurchaseStatus(c *gin.Context) {
|
||||
s, order, ok := a.lookupClientPurchase(c, false)
|
||||
if ok {
|
||||
a.respondPurchase(c, s, order, false)
|
||||
}
|
||||
}
|
||||
func (a *BusinessAPI) respondPurchase(c *gin.Context, s purchaseScope, order uint64, create bool) {
|
||||
var no, merchant, channel, status, orderStatus, currency, title string
|
||||
var amount uint64
|
||||
var days int
|
||||
var code sql.NullString
|
||||
var expires time.Time
|
||||
var version sql.NullInt64
|
||||
e := a.db.QueryRowContext(c, `SELECT o.order_no,p.merchant_order_no,p.channel,p.status,o.status,p.currency,p.amount_cents,p.license_days,p.code_url,p.expires_at,p.provider_config_version,pv.name FROM client_purchases cp JOIN offline_orders o ON o.id=cp.order_id JOIN payment_orders p ON p.order_id=o.id JOIN payment_plan_versions pv ON pv.plan_id=p.plan_id AND pv.version=p.plan_version WHERE cp.order_id=? AND cp.credential_id=?`, order, s.ID).Scan(&no, &merchant, &channel, &status, &orderStatus, ¤cy, &amount, &days, &code, &expires, &version, &title)
|
||||
if e != nil {
|
||||
purchaseFailure(c)
|
||||
return
|
||||
}
|
||||
if create && status == "created" && !code.Valid && time.Now().Before(expires) {
|
||||
provider, err := a.providerForPaymentVersion(c, channel, version)
|
||||
if err != nil {
|
||||
apiError(c, 503, "channel_unavailable", "历史支付配置不可用")
|
||||
return
|
||||
}
|
||||
url, err := provider.Create(c, merchant, int64(amount), title)
|
||||
if err != nil || url == "" {
|
||||
apiError(c, 502, "channel_error", "渠道下单未完成,请使用相同参数和幂等键重试")
|
||||
return
|
||||
}
|
||||
if _, err = a.db.ExecContext(c, "UPDATE payment_orders SET code_url=? WHERE order_id=? AND status='created'", url, order); err != nil {
|
||||
purchaseFailure(c)
|
||||
return
|
||||
}
|
||||
code = sql.NullString{String: url, Valid: true}
|
||||
}
|
||||
if status == "created" {
|
||||
now := time.Now().UTC()
|
||||
res, err := a.db.ExecContext(c, "UPDATE payment_orders SET last_queried_at=? WHERE order_id=? AND (last_queried_at IS NULL OR last_queried_at<?)", now, order, now.Add(-15*time.Second))
|
||||
if err == nil {
|
||||
n, _ := res.RowsAffected()
|
||||
if n == 1 {
|
||||
if provider, err := a.providerForPaymentVersion(c, channel, version); err == nil {
|
||||
notification, err := provider.Query(c, merchant)
|
||||
if err == nil && notification.Paid && notification.MerchantOrderNo == merchant {
|
||||
if a.applyPayment(c, channel, notification, version) != nil {
|
||||
apiError(c, 503, "authorization_pending", "支付已完成,授权处理中")
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if a.db.QueryRowContext(c, "SELECT p.status,o.status FROM payment_orders p JOIN offline_orders o ON o.id=p.order_id WHERE p.order_id=?", order).Scan(&status, &orderStatus) != nil {
|
||||
purchaseFailure(c)
|
||||
return
|
||||
}
|
||||
qrExpired := !time.Now().Before(expires)
|
||||
if qrExpired || status != "created" {
|
||||
code.String = ""
|
||||
}
|
||||
c.JSON(200, gin.H{"data": gin.H{"order_no": no, "status": status, "order_status": orderStatus, "code_url": code.String, "qr_expired": qrExpired, "expires_at": expires, "amount_cents": amount, "currency": currency, "license_days": days, "channel": channel}})
|
||||
}
|
||||
Reference in New Issue
Block a user