feat: add client self-service purchases and integration kit
Co-Authored-By: Craft Agent <agents-noreply@craft.do>
This commit is contained in:
269
backend/internal/httpapi/purchase_admin.go
Normal file
269
backend/internal/httpapi/purchase_admin.go
Normal file
@@ -0,0 +1,269 @@
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"github.com/gin-gonic/gin"
|
||||
"strconv"
|
||||
"strings"
|
||||
)
|
||||
|
||||
type paymentPlan struct {
|
||||
ID uint64 `json:"id"`
|
||||
ProductID uint64 `json:"product_id"`
|
||||
Code string `json:"code"`
|
||||
Name string `json:"name"`
|
||||
AmountCents uint64 `json:"amount_cents"`
|
||||
Currency string `json:"currency"`
|
||||
LicenseDays int `json:"license_days"`
|
||||
Enabled bool `json:"enabled"`
|
||||
Version uint64 `json:"version"`
|
||||
}
|
||||
|
||||
const planColumns = "id,product_id,code,name,amount_cents,currency,license_days,enabled,version"
|
||||
|
||||
func scanPlan(row interface{ Scan(...any) error }, p *paymentPlan) error {
|
||||
return row.Scan(&p.ID, &p.ProductID, &p.Code, &p.Name, &p.AmountCents, &p.Currency, &p.LicenseDays, &p.Enabled, &p.Version)
|
||||
}
|
||||
func visibleASCII(s string, max int) bool {
|
||||
if len(s) < 1 || len(s) > max {
|
||||
return false
|
||||
}
|
||||
for _, r := range s {
|
||||
if r < 33 || r > 126 {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
func validPlan(p paymentPlan) bool {
|
||||
return p.ProductID > 0 && visibleASCII(p.Code, 64) && strings.TrimSpace(p.Name) != "" && len(p.Name) <= 190 && p.AmountCents > 0 && p.AmountCents <= 100000000000 && p.Currency == "CNY" && p.LicenseDays >= 1 && p.LicenseDays <= 3650
|
||||
}
|
||||
func purchaseAdminBoundary(c *gin.Context) {
|
||||
c.Header("Cache-Control", "no-store")
|
||||
if !paymentConfigOriginAllowed(c) {
|
||||
apiError(c, 403, "origin_forbidden", "请求来源不允许")
|
||||
c.Abort()
|
||||
return
|
||||
}
|
||||
c.Next()
|
||||
}
|
||||
func (a *BusinessAPI) listPaymentPlans(c *gin.Context) {
|
||||
rows, e := a.db.QueryContext(c, "SELECT "+planColumns+" FROM payment_plans ORDER BY id DESC LIMIT 1000")
|
||||
if e != nil {
|
||||
purchaseFailure(c)
|
||||
return
|
||||
}
|
||||
defer rows.Close()
|
||||
out := []paymentPlan{}
|
||||
for rows.Next() {
|
||||
var p paymentPlan
|
||||
if scanPlan(rows, &p) != nil {
|
||||
purchaseFailure(c)
|
||||
return
|
||||
}
|
||||
out = append(out, p)
|
||||
}
|
||||
if rows.Err() != nil {
|
||||
purchaseFailure(c)
|
||||
return
|
||||
}
|
||||
c.JSON(200, gin.H{"data": out})
|
||||
}
|
||||
func (a *BusinessAPI) savePaymentPlan(c *gin.Context) {
|
||||
var p paymentPlan
|
||||
c.Request.Body = limitedPurchaseBody(c, 8192)
|
||||
if c.ShouldBindJSON(&p) != nil || !validPlan(p) {
|
||||
apiError(c, 400, "invalid_request", "套餐字段无效")
|
||||
return
|
||||
}
|
||||
tx, e := a.db.BeginTx(c, nil)
|
||||
if e != nil {
|
||||
purchaseFailure(c)
|
||||
return
|
||||
}
|
||||
defer tx.Rollback()
|
||||
var actor uint64
|
||||
if tx.QueryRowContext(c, "SELECT id FROM admins WHERE id=? AND active=1 AND role='admin' FOR UPDATE", c.MustGet("admin_id")).Scan(&actor) != nil {
|
||||
apiError(c, 403, "forbidden", "管理员无效")
|
||||
return
|
||||
}
|
||||
var active bool
|
||||
if tx.QueryRowContext(c, "SELECT active FROM products WHERE id=? FOR UPDATE", p.ProductID).Scan(&active) != nil || !active {
|
||||
apiError(c, 409, "product_unavailable", "产品不可用")
|
||||
return
|
||||
}
|
||||
if c.Param("id") == "" {
|
||||
p.Version = 1
|
||||
r, err := tx.ExecContext(c, "INSERT INTO payment_plans(product_id,code,name,amount_cents,currency,license_days,enabled,version) VALUES(?,?,?,?,?,?,?,1)", p.ProductID, p.Code, p.Name, p.AmountCents, p.Currency, p.LicenseDays, p.Enabled)
|
||||
if err != nil {
|
||||
apiError(c, 409, "plan_conflict", "套餐代码冲突")
|
||||
return
|
||||
}
|
||||
id, _ := r.LastInsertId()
|
||||
p.ID = uint64(id)
|
||||
} else {
|
||||
id, err := strconv.ParseUint(c.Param("id"), 10, 64)
|
||||
if err != nil || id == 0 || p.Version == 0 {
|
||||
apiError(c, 400, "invalid_request", "须提供套餐版本")
|
||||
return
|
||||
}
|
||||
var old paymentPlan
|
||||
if scanPlan(tx.QueryRowContext(c, "SELECT "+planColumns+" FROM payment_plans WHERE id=? FOR UPDATE", id), &old) != nil {
|
||||
apiError(c, 404, "not_found", "套餐不存在")
|
||||
return
|
||||
}
|
||||
if p.Version != old.Version {
|
||||
apiError(c, 409, "plan_version_conflict", "套餐版本已变化")
|
||||
return
|
||||
}
|
||||
if p.ProductID != old.ProductID || p.Code != old.Code {
|
||||
apiError(c, 409, "plan_identity_conflict", "套餐产品和代码不可变更")
|
||||
return
|
||||
}
|
||||
p.ID = id
|
||||
p.Version++
|
||||
_, e = tx.ExecContext(c, "UPDATE payment_plans SET name=?,amount_cents=?,currency=?,license_days=?,enabled=?,version=? WHERE id=?", p.Name, p.AmountCents, p.Currency, p.LicenseDays, p.Enabled, p.Version, id)
|
||||
if e != nil {
|
||||
purchaseFailure(c)
|
||||
return
|
||||
}
|
||||
}
|
||||
_, e = tx.ExecContext(c, "INSERT INTO payment_plan_versions(plan_id,version,product_id,code,name,amount_cents,currency,license_days,enabled,created_by) VALUES(?,?,?,?,?,?,?,?,?,?)", p.ID, p.Version, p.ProductID, p.Code, p.Name, p.AmountCents, p.Currency, p.LicenseDays, p.Enabled, actor)
|
||||
details, _ := json.Marshal(p)
|
||||
if e == nil {
|
||||
_, e = tx.ExecContext(c, "INSERT INTO audit_events(actor_admin_id,action,resource_type,resource_id,details) VALUES(?,'payment.plan.saved','payment_plan',?,?)", actor, p.ID, details)
|
||||
}
|
||||
if e != nil || tx.Commit() != nil {
|
||||
purchaseFailure(c)
|
||||
return
|
||||
}
|
||||
c.JSON(200, gin.H{"data": p})
|
||||
}
|
||||
func (a *BusinessAPI) listPurchaseCredentials(c *gin.Context) {
|
||||
rows, e := a.db.QueryContext(c, "SELECT id,customer_id,product_id,label,enabled,created_by FROM purchase_credentials ORDER BY id DESC LIMIT 1000")
|
||||
if e != nil {
|
||||
purchaseFailure(c)
|
||||
return
|
||||
}
|
||||
defer rows.Close()
|
||||
out := []gin.H{}
|
||||
for rows.Next() {
|
||||
var id, customer, product, actor uint64
|
||||
var label string
|
||||
var enabled bool
|
||||
if rows.Scan(&id, &customer, &product, &label, &enabled, &actor) != nil {
|
||||
purchaseFailure(c)
|
||||
return
|
||||
}
|
||||
out = append(out, gin.H{"id": id, "customer_id": customer, "product_id": product, "label": label, "enabled": enabled, "created_by": actor})
|
||||
}
|
||||
if rows.Err() != nil {
|
||||
purchaseFailure(c)
|
||||
return
|
||||
}
|
||||
c.JSON(200, gin.H{"data": out})
|
||||
}
|
||||
func (a *BusinessAPI) updatePurchaseCredential(c *gin.Context) {
|
||||
id, err := strconv.ParseUint(c.Param("id"), 10, 64)
|
||||
if err != nil || id == 0 {
|
||||
apiError(c, 400, "invalid_request", "凭据 ID 无效")
|
||||
return
|
||||
}
|
||||
var in struct {
|
||||
Enabled *bool `json:"enabled"`
|
||||
}
|
||||
c.Request.Body = limitedPurchaseBody(c, 1024)
|
||||
if c.ShouldBindJSON(&in) != nil || in.Enabled == nil {
|
||||
apiError(c, 400, "invalid_request", "enabled 必须为布尔值")
|
||||
return
|
||||
}
|
||||
tx, err := a.db.BeginTx(c, nil)
|
||||
if err != nil {
|
||||
purchaseFailure(c)
|
||||
return
|
||||
}
|
||||
defer tx.Rollback()
|
||||
var actor uint64
|
||||
if tx.QueryRowContext(c, "SELECT id FROM admins WHERE id=? AND active=1 AND role='admin' FOR UPDATE", c.MustGet("admin_id")).Scan(&actor) != nil {
|
||||
apiError(c, 403, "forbidden", "管理员无效")
|
||||
return
|
||||
}
|
||||
var customer, product uint64
|
||||
var label string
|
||||
var created bool
|
||||
if tx.QueryRowContext(c, "SELECT customer_id,product_id,label,enabled FROM purchase_credentials WHERE id=? FOR UPDATE", id).Scan(&customer, &product, &label, &created) != nil {
|
||||
apiError(c, 404, "not_found", "购买凭据不存在")
|
||||
return
|
||||
}
|
||||
if _, err = tx.ExecContext(c, "UPDATE purchase_credentials SET enabled=? WHERE id=?", *in.Enabled, id); err != nil {
|
||||
purchaseFailure(c)
|
||||
return
|
||||
}
|
||||
details, _ := json.Marshal(gin.H{"enabled": *in.Enabled})
|
||||
if _, err = tx.ExecContext(c, "INSERT INTO audit_events(actor_admin_id,action,resource_type,resource_id,details) VALUES(?,'purchase.credential.updated','purchase_credential',?,?)", actor, id, details); err != nil || tx.Commit() != nil {
|
||||
purchaseFailure(c)
|
||||
return
|
||||
}
|
||||
c.JSON(200, gin.H{"data": gin.H{"id": id, "customer_id": customer, "product_id": product, "label": label, "enabled": *in.Enabled}})
|
||||
}
|
||||
|
||||
func (a *BusinessAPI) createPurchaseCredential(c *gin.Context) {
|
||||
var in struct {
|
||||
CustomerID uint64 `json:"customer_id"`
|
||||
ProductID uint64 `json:"product_id"`
|
||||
Label string `json:"label"`
|
||||
Enabled *bool `json:"enabled"`
|
||||
}
|
||||
c.Request.Body = limitedPurchaseBody(c, 4096)
|
||||
if c.ShouldBindJSON(&in) != nil || in.CustomerID == 0 || in.ProductID == 0 || strings.TrimSpace(in.Label) == "" || len(in.Label) > 190 {
|
||||
apiError(c, 400, "invalid_request", "凭据字段无效")
|
||||
return
|
||||
}
|
||||
token, e := randomPaymentToken(32)
|
||||
if e != nil {
|
||||
purchaseFailure(c)
|
||||
return
|
||||
}
|
||||
raw, _ := hex.DecodeString(token)
|
||||
hash := sha256.Sum256(raw)
|
||||
tx, e := a.db.BeginTx(c, nil)
|
||||
if e != nil {
|
||||
purchaseFailure(c)
|
||||
return
|
||||
}
|
||||
defer tx.Rollback()
|
||||
var actor uint64
|
||||
var state string
|
||||
var active bool
|
||||
if tx.QueryRowContext(c, "SELECT id FROM admins WHERE id=? AND active=1 AND role='admin' FOR UPDATE", c.MustGet("admin_id")).Scan(&actor) != nil {
|
||||
apiError(c, 403, "forbidden", "管理员无效")
|
||||
return
|
||||
}
|
||||
if tx.QueryRowContext(c, "SELECT status FROM customers WHERE id=? FOR UPDATE", in.CustomerID).Scan(&state) != nil || state != "active" || tx.QueryRowContext(c, "SELECT active FROM products WHERE id=? FOR UPDATE", in.ProductID).Scan(&active) != nil || !active {
|
||||
apiError(c, 409, "scope_unavailable", "请先由管理员配置有效客户及产品")
|
||||
return
|
||||
}
|
||||
enabled := true
|
||||
if in.Enabled != nil {
|
||||
enabled = *in.Enabled
|
||||
}
|
||||
res, e := tx.ExecContext(c, "INSERT INTO purchase_credentials(token_hash,customer_id,product_id,label,enabled,created_by) VALUES(?,?,?,?,?,?)", hash[:], in.CustomerID, in.ProductID, in.Label, enabled, actor)
|
||||
if e != nil {
|
||||
purchaseFailure(c)
|
||||
return
|
||||
}
|
||||
id, _ := res.LastInsertId()
|
||||
_, e = tx.ExecContext(c, "INSERT INTO audit_events(actor_admin_id,action,resource_type,resource_id,details) VALUES(?,'purchase.credential.created','purchase_credential',?,'{}')", actor, id)
|
||||
if e != nil || tx.Commit() != nil {
|
||||
purchaseFailure(c)
|
||||
return
|
||||
}
|
||||
c.JSON(201, gin.H{"data": gin.H{"id": id, "customer_id": in.CustomerID, "product_id": in.ProductID, "label": in.Label, "enabled": enabled, "token": token}})
|
||||
}
|
||||
|
||||
// Keep SQL errors and credentials out of public error bodies.
|
||||
func purchaseFailure(c *gin.Context) {
|
||||
apiError(c, 503, "purchase_unavailable", "购买服务暂时不可用")
|
||||
}
|
||||
Reference in New Issue
Block a user