chore(init): 初始化解忧商行项目并完成 Phase 0 基座

This commit is contained in:
yml2213
2026-10-30 11:46:10 +08:00
commit 8d9481c251
689 changed files with 138703 additions and 0 deletions
@@ -0,0 +1,785 @@
package lakala
import (
"bytes"
"context"
"crypto"
"crypto/rand"
"crypto/rsa"
"crypto/sha256"
"crypto/x509"
"encoding/base64"
"encoding/json"
"encoding/pem"
"errors"
"fmt"
"io"
"math"
"net/http"
"strconv"
"strings"
"time"
"hfb_sys/backend/internal/timeutil"
)
var (
ErrConfigIncomplete = errors.New("lakala payment config incomplete")
ErrSignFailed = errors.New("lakala sign failed")
ErrVerifyFailed = errors.New("lakala verify failed")
)
const (
endpointCounterCreate = "/api/v3/ccss/counter/order/special_create"
endpointCounterQuery = "/api/v3/ccss/counter/order/query"
endpointRefund = "/api/v3/labs/relation/refund"
endpointRefundQuery = "/api/v3/labs/query/idmrefundquery"
)
type Config struct {
GatewayURL string
AppID string
SerialNo string
MerchantID string
TermNo string
PrivateKey string
LakalaCert string
NotifyCert string
NotifyURL string
JumpURL string
PayWay string
JSPayFlag string
PayMode string
OrderExpireMinutes int
}
type Client struct {
cfg Config
httpClient *http.Client
privateKey *rsa.PrivateKey
lakalaCert *x509.Certificate
notifyCert *x509.Certificate
}
type CreatePaymentRequest struct {
ThirdOrderID string
AmountCent int64
PayWay string
JSPayFlag string
NotifyURL string
JumpURL string
ClientIP string
Body string
Attach string
}
type CreatePaymentResponse struct {
OK bool
ErrorMessage string
MerchantID string
ThirdOrderID string
ProviderOrderID string
PayWay string
Status string
PayTime string
TDCode string
JSPayURL string
JSPayInfo string
Raw map[string]string
RawRequest map[string]string
}
type QueryPaymentResponse struct {
OK bool
ErrorMessage string
MerchantID string
ThirdOrderID string
ProviderOrderID string
Status string
Amount string
PayWay string
PayTime string
Raw map[string]string
}
type CreateRefundRequest struct {
ThirdOrderID string
ProviderOrderID string
MerchantRefundID string
RefundAmountCent int64
NotifyURL string
Attach string
RefundReason string
ClientIP string
}
type CreateRefundResponse struct {
OK bool
ErrorMessage string
MerchantID string
ThirdOrderID string
ProviderOrderID string
MerchantRefundID string
ProviderRefundID string
Status string
RefundAmount string
Raw map[string]string
RawRequest map[string]string
}
type QueryRefundRequest struct {
ThirdOrderID string
ProviderOrderID string
MerchantRefundID string
ProviderRefundID string
}
type QueryRefundResponse struct {
OK bool
ErrorMessage string
MerchantID string
ThirdOrderID string
ProviderOrderID string
MerchantRefundID string
ProviderRefundID string
Status string
RefundAmount string
RefundTime string
Raw map[string]string
RawRequest map[string]string
}
type VerifyNotifyResult struct {
OK bool
MatchedKey string
Got string
Expected map[string]string
BaseString map[string]string
ParamKeys []string
}
func NewClient(cfg Config) *Client {
return &Client{
cfg: cfg,
httpClient: &http.Client{
Timeout: 15 * time.Second,
},
}
}
func (c *Client) CreatePayment(ctx context.Context, req CreatePaymentRequest) (*CreatePaymentResponse, error) {
if err := c.initCrypto(); err != nil {
return nil, err
}
payWay := firstNonEmpty(req.PayWay, c.cfg.PayWay, "ZFBZF")
payMode := normalizeCounterPayMode(c.cfg.PayMode)
expireMinutes := c.cfg.OrderExpireMinutes
if expireMinutes <= 0 {
expireMinutes = 15
}
now := timeutil.ShanghaiNow()
reqData := map[string]any{
"out_order_no": req.ThirdOrderID,
"merchant_no": c.cfg.MerchantID,
"total_amount": req.AmountCent,
"order_efficient_time": now.Add(time.Duration(expireMinutes) * time.Minute).Format("20060102150405"),
"notify_url": firstNonEmpty(req.NotifyURL, c.cfg.NotifyURL),
"support_refund": 1,
"support_repeat_pay": 1,
"support_cancel": 0,
"order_info": sanitizeText(req.Body, 128),
}
if payMode != "" {
reqData["counter_param"] = fmt.Sprintf(`{"pay_mode":"%s"}`, payMode)
}
if c.cfg.TermNo != "" {
reqData["term_no"] = c.cfg.TermNo
}
if jumpURL := firstNonEmpty(req.JumpURL, c.cfg.JumpURL); jumpURL != "" {
reqData["callback_url"] = jumpURL
}
if req.Attach != "" {
reqData["counter_remark"] = sanitizeText(req.Attach, 128)
}
rawReq := stringifyMap(reqData)
raw, err := c.post(ctx, endpointCounterCreate, reqData)
if err != nil {
return nil, err
}
return &CreatePaymentResponse{
OK: responseOK(raw),
ErrorMessage: responseMessage(raw),
MerchantID: firstNonEmpty(raw["merchant_no"], c.cfg.MerchantID),
ThirdOrderID: firstNonEmpty(raw["out_order_no"], req.ThirdOrderID),
ProviderOrderID: firstNonEmpty(raw["pay_order_no"], raw["trade_no"], raw["log_no"]),
PayWay: payWay,
Status: normalizePaymentStatus(raw),
PayTime: firstNonEmpty(raw["pay_time"], raw["trade_time"], raw["finish_time"]),
TDCode: firstNonEmpty(raw["qr_code"], raw["code_url"], raw["pay_url"], raw["counter_url"]),
JSPayURL: firstNonEmpty(raw["counter_url"], raw["pay_url"], raw["qr_code"], raw["code_url"]),
JSPayInfo: firstNonEmpty(raw["pay_info"], raw["credential"], raw["credential_json"], raw["req_data"]),
Raw: raw,
RawRequest: rawReq,
}, nil
}
func (c *Client) QueryPayment(ctx context.Context, thirdOrderID, providerOrderID string) (*QueryPaymentResponse, error) {
if err := c.initCrypto(); err != nil {
return nil, err
}
reqData := map[string]any{
"merchant_no": c.cfg.MerchantID,
}
if providerOrderID != "" {
reqData["pay_order_no"] = providerOrderID
} else {
reqData["out_order_no"] = thirdOrderID
}
raw, err := c.post(ctx, endpointCounterQuery, reqData)
if err != nil {
return nil, err
}
return &QueryPaymentResponse{
OK: responseOK(raw),
ErrorMessage: responseMessage(raw),
MerchantID: firstNonEmpty(raw["merchant_no"], c.cfg.MerchantID),
ThirdOrderID: firstNonEmpty(raw["out_order_no"], thirdOrderID),
ProviderOrderID: firstNonEmpty(raw["pay_order_no"], raw["trade_no"], providerOrderID),
Status: normalizePaymentStatus(raw),
Amount: firstNonEmpty(raw["total_amount"], raw["amount"], raw["trade_amount"]),
PayWay: firstNonEmpty(raw["pay_mode"], raw["account_type"]),
PayTime: firstNonEmpty(raw["pay_time"], raw["trade_time"], raw["finish_time"]),
Raw: raw,
}, nil
}
func (c *Client) CreateRefund(ctx context.Context, req CreateRefundRequest) (*CreateRefundResponse, error) {
if err := c.initCrypto(); err != nil {
return nil, err
}
reqData := map[string]any{
"merchant_no": c.cfg.MerchantID,
"term_no": c.cfg.TermNo,
"out_trade_no": req.MerchantRefundID,
"refund_amount": strconv.FormatInt(req.RefundAmountCent, 10),
"refund_reason": firstNonEmpty(req.RefundReason, "订单退款"),
"origin_out_trade_no": req.ThirdOrderID,
"origin_trade_no": req.ProviderOrderID,
"location_info": defaultLocationInfo(req.ClientIP),
}
if c.cfg.TermNo == "" {
delete(reqData, "term_no")
}
if req.ProviderOrderID == "" {
delete(reqData, "origin_trade_no")
}
rawReq := stringifyMap(reqData)
raw, err := c.post(ctx, endpointRefund, reqData)
if err != nil {
return &CreateRefundResponse{
MerchantID: c.cfg.MerchantID,
ThirdOrderID: req.ThirdOrderID,
ProviderOrderID: req.ProviderOrderID,
MerchantRefundID: req.MerchantRefundID,
RefundAmount: strconv.FormatInt(req.RefundAmountCent, 10),
RawRequest: rawReq,
}, err
}
return &CreateRefundResponse{
OK: responseOK(raw),
ErrorMessage: responseMessage(raw),
MerchantID: firstNonEmpty(raw["merchant_no"], c.cfg.MerchantID),
ThirdOrderID: firstNonEmpty(raw["origin_out_trade_no"], req.ThirdOrderID),
ProviderOrderID: firstNonEmpty(raw["origin_trade_no"], req.ProviderOrderID),
MerchantRefundID: firstNonEmpty(raw["out_trade_no"], req.MerchantRefundID),
ProviderRefundID: firstNonEmpty(raw["refund_trade_no"], raw["trade_no"], raw["log_no"]),
Status: normalizeRefundStatus(raw),
RefundAmount: firstNonEmpty(raw["refund_amount"], strconv.FormatInt(req.RefundAmountCent, 10)),
Raw: raw,
RawRequest: rawReq,
}, nil
}
func (c *Client) QueryRefund(ctx context.Context, req QueryRefundRequest) (*QueryRefundResponse, error) {
if err := c.initCrypto(); err != nil {
return nil, err
}
reqData := map[string]any{
"merchant_no": c.cfg.MerchantID,
"term_no": c.cfg.TermNo,
}
if req.MerchantRefundID != "" {
reqData["out_trade_no"] = req.MerchantRefundID
}
if req.ThirdOrderID != "" {
reqData["origin_out_trade_no"] = req.ThirdOrderID
}
if req.ProviderOrderID != "" {
reqData["origin_trade_no"] = req.ProviderOrderID
}
if c.cfg.TermNo == "" {
delete(reqData, "term_no")
}
rawReq := stringifyMap(reqData)
raw, err := c.post(ctx, endpointRefundQuery, reqData)
if err != nil {
return &QueryRefundResponse{
MerchantID: c.cfg.MerchantID,
ThirdOrderID: req.ThirdOrderID,
ProviderOrderID: req.ProviderOrderID,
MerchantRefundID: req.MerchantRefundID,
ProviderRefundID: req.ProviderRefundID,
RawRequest: rawReq,
}, err
}
return &QueryRefundResponse{
OK: responseOK(raw),
ErrorMessage: responseMessage(raw),
MerchantID: firstNonEmpty(raw["merchant_no"], c.cfg.MerchantID),
ThirdOrderID: firstNonEmpty(raw["origin_out_trade_no"], req.ThirdOrderID),
ProviderOrderID: firstNonEmpty(raw["origin_trade_no"], req.ProviderOrderID),
MerchantRefundID: firstNonEmpty(raw["out_trade_no"], req.MerchantRefundID),
ProviderRefundID: firstNonEmpty(raw["refund_trade_no"], raw["trade_no"], req.ProviderRefundID),
Status: normalizeRefundStatus(raw),
RefundAmount: raw["refund_amount"],
RefundTime: firstNonEmpty(raw["refund_time"], raw["trade_time"], raw["finish_time"]),
Raw: raw,
RawRequest: rawReq,
}, nil
}
func (c *Client) VerifyNotifyDetail(rawPayload string, authorization string) VerifyNotifyResult {
result := VerifyNotifyResult{
Expected: map[string]string{},
BaseString: map[string]string{},
}
if err := c.initCrypto(); err != nil {
result.Expected["error"] = err.Error()
return result
}
signature, base, err := parseAuthorization(authorization)
result.Got = signature
result.BaseString["notify_cert"] = base.message(rawPayload)
if err != nil {
result.Expected["error"] = err.Error()
return result
}
ok := verifyRSA(c.notifyCert, []byte(base.message(rawPayload)), signature)
result.OK = ok
if ok {
result.MatchedKey = "notify_cert"
}
return result
}
func ParsePayload(body []byte) (map[string]string, error) {
var payload any
if err := json.Unmarshal(body, &payload); err != nil {
return nil, err
}
raw := flattenJSON(payload)
normalizeNotifyAliases(raw)
return raw, nil
}
func (c *Client) post(ctx context.Context, endpoint string, reqData map[string]any) (map[string]string, error) {
body, err := json.Marshal(map[string]any{
"req_time": timeutil.ShanghaiNow().Format("20060102150405"),
"version": "3.0",
"req_data": reqData,
})
if err != nil {
return nil, err
}
url := strings.TrimRight(strings.TrimSpace(c.cfg.GatewayURL), "/") + endpoint
req, err := http.NewRequestWithContext(ctx, http.MethodPost, url, bytes.NewReader(body))
if err != nil {
return nil, err
}
req.Header.Set("Content-Type", "application/json;charset=UTF-8")
req.Header.Set("Accept", "application/json")
req.Header.Set("Authorization", c.authorization(string(body)))
req.Header.Set("lkl-op-sdk", "hfb-go-lakala")
req.Header.Set("lkl-op-flowgroup", "NORMAL")
req.Header.Set("lkl-op-appid", c.cfg.AppID)
resp, err := c.httpClient.Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
respBody, err := io.ReadAll(io.LimitReader(resp.Body, 4<<20))
if err != nil {
return nil, err
}
if resp.StatusCode < 200 || resp.StatusCode >= 300 {
return nil, fmt.Errorf("lakala http status %d: %s", resp.StatusCode, string(respBody))
}
if err := c.verifyResponse(resp.Header, string(respBody)); err != nil {
return nil, err
}
var payload any
if len(respBody) == 0 {
return map[string]string{}, nil
}
if err := json.Unmarshal(respBody, &payload); err != nil {
return nil, err
}
raw := flattenJSON(payload)
normalizeNotifyAliases(raw)
return raw, nil
}
func (c *Client) authorization(body string) string {
nonce := Nonce(32)
timestamp := strconv.FormatInt(time.Now().Unix(), 10)
message := strings.Join([]string{c.cfg.AppID, c.cfg.SerialNo, timestamp, nonce, body, ""}, "\n")
signature, err := signRSA(c.privateKey, []byte(message))
if err != nil {
return ""
}
return fmt.Sprintf(
`LKLAPI-SHA256withRSA appid="%s",nonce_str="%s",timestamp="%s",serial_no="%s",signature="%s"`,
c.cfg.AppID,
nonce,
timestamp,
c.cfg.SerialNo,
signature,
)
}
func (c *Client) verifyResponse(header http.Header, body string) error {
signature := header.Get("Lklapi-Signature")
if signature == "" {
return nil
}
appID := header.Get("Lklapi-Appid")
if appID == "" {
appID = c.cfg.AppID
}
serial := header.Get("Lklapi-Serial")
timestamp := header.Get("Lklapi-Timestamp")
nonce := header.Get("Lklapi-Nonce")
if serial == "" || timestamp == "" || nonce == "" {
return ErrVerifyFailed
}
message := strings.Join([]string{appID, serial, timestamp, nonce, body, ""}, "\n")
if !verifyRSA(c.lakalaCert, []byte(message), signature) {
return ErrVerifyFailed
}
return nil
}
func (c *Client) initCrypto() error {
if strings.TrimSpace(c.cfg.GatewayURL) == "" ||
strings.TrimSpace(c.cfg.AppID) == "" ||
strings.TrimSpace(c.cfg.SerialNo) == "" ||
strings.TrimSpace(c.cfg.MerchantID) == "" ||
strings.TrimSpace(c.cfg.PrivateKey) == "" ||
strings.TrimSpace(c.cfg.NotifyCert) == "" {
return ErrConfigIncomplete
}
if c.privateKey == nil {
key, err := parsePrivateKey(c.cfg.PrivateKey)
if err != nil {
return err
}
c.privateKey = key
}
if c.notifyCert == nil {
cert, err := parseCertificate(c.cfg.NotifyCert)
if err != nil {
return err
}
c.notifyCert = cert
}
if c.lakalaCert == nil && c.cfg.LakalaCert != "" {
cert, err := parseCertificate(c.cfg.LakalaCert)
if err != nil {
return err
}
c.lakalaCert = cert
}
if c.lakalaCert == nil {
c.lakalaCert = c.notifyCert
}
return nil
}
type authorizationBase struct {
timestamp string
nonce string
}
func (b authorizationBase) message(body string) string {
return strings.Join([]string{b.timestamp, b.nonce, body, ""}, "\n")
}
func parseAuthorization(value string) (string, authorizationBase, error) {
value = strings.TrimSpace(value)
if value == "" {
return "", authorizationBase{}, errors.New("empty authorization")
}
space := strings.Index(value, " ")
if space < 0 {
return "", authorizationBase{}, errors.New("invalid authorization")
}
items := strings.Split(value[space+1:], ",")
params := map[string]string{}
for _, item := range items {
parts := strings.SplitN(strings.TrimSpace(item), "=", 2)
if len(parts) != 2 {
continue
}
params[parts[0]] = strings.Trim(parts[1], `"`)
}
signature := params["signature"]
base := authorizationBase{
timestamp: params["timestamp"],
nonce: params["nonce_str"],
}
if signature == "" || base.timestamp == "" || base.nonce == "" {
return signature, base, errors.New("authorization missing signature fields")
}
return signature, base, nil
}
func parsePrivateKey(value string) (*rsa.PrivateKey, error) {
block, _ := pem.Decode([]byte(value))
if block == nil {
return nil, errors.New("invalid private key pem")
}
if key, err := x509.ParsePKCS1PrivateKey(block.Bytes); err == nil {
return key, nil
}
parsed, err := x509.ParsePKCS8PrivateKey(block.Bytes)
if err != nil {
return nil, err
}
key, ok := parsed.(*rsa.PrivateKey)
if !ok {
return nil, errors.New("private key is not rsa")
}
return key, nil
}
func parseCertificate(value string) (*x509.Certificate, error) {
block, _ := pem.Decode([]byte(value))
if block == nil {
return nil, errors.New("invalid certificate pem")
}
return x509.ParseCertificate(block.Bytes)
}
func signRSA(key *rsa.PrivateKey, message []byte) (string, error) {
if key == nil {
return "", ErrSignFailed
}
digest := sha256.Sum256(message)
signature, err := rsa.SignPKCS1v15(rand.Reader, key, crypto.SHA256, digest[:])
if err != nil {
return "", err
}
return base64.StdEncoding.EncodeToString(signature), nil
}
func verifyRSA(cert *x509.Certificate, message []byte, signature string) bool {
if cert == nil || signature == "" {
return false
}
sig, err := base64.StdEncoding.DecodeString(signature)
if err != nil {
return false
}
pub, ok := cert.PublicKey.(*rsa.PublicKey)
if !ok {
return false
}
digest := sha256.Sum256(message)
return rsa.VerifyPKCS1v15(pub, crypto.SHA256, digest[:], sig) == nil
}
func normalizeNotifyAliases(raw map[string]string) {
raw["third_order_id"] = firstNonEmpty(raw["third_order_id"], raw["out_order_no"], raw["out_trade_no"])
raw["provider_order_id"] = firstNonEmpty(raw["provider_order_id"], raw["pay_order_no"], raw["trade_no"], raw["log_no"])
raw["amount"] = firstNonEmpty(raw["amount"], raw["total_amount"], raw["trade_amount"])
raw["status"] = normalizePaymentStatus(raw)
raw["pay_time"] = firstNonEmpty(raw["pay_time"], raw["trade_time"], raw["finish_time"])
if raw["refund_amount"] != "" || raw["origin_out_trade_no"] != "" {
raw["merchant_refund_id"] = firstNonEmpty(raw["merchant_refund_id"], raw["out_trade_no"])
raw["provider_refund_id"] = firstNonEmpty(raw["provider_refund_id"], raw["refund_trade_no"], raw["trade_no"], raw["log_no"])
raw["status"] = normalizeRefundStatus(raw)
}
}
func normalizePaymentStatus(raw map[string]string) string {
value := strings.ToUpper(firstNonEmpty(raw["trade_state"], raw["order_status"], raw["trade_status"], raw["status"], raw["pay_status"]))
switch value {
case "SUCCESS", "PAY_SUCCESS", "TRADE_SUCCESS", "PAID", "S", "2", "30":
return "paid"
case "CLOSED", "CLOSE", "CANCEL", "CANCELED", "CANCELLED", "6":
return "closed"
case "FAIL", "FAILED", "PAY_FAIL", "TRADE_FAIL", "F", "8":
return "failed"
case "REFUND", "REFUNDED":
return "refunded"
default:
return "paying"
}
}
func normalizeRefundStatus(raw map[string]string) string {
value := strings.ToUpper(firstNonEmpty(raw["refund_status"], raw["trade_state"], raw["trade_status"], raw["status"]))
switch value {
case "SUCCESS", "REFUND_SUCCESS", "TRADE_SUCCESS", "REFUNDED", "S", "11":
return "refunded"
case "FAIL", "FAILED", "REFUND_FAIL", "TRADE_FAIL", "F", "12":
return "failed"
}
if hasSuccessResponseCode(raw) {
return "refunded"
}
return "refunding"
}
func hasSuccessResponseCode(raw map[string]string) bool {
code := firstNonEmpty(raw["code"], raw["resp_code"], raw["result_code"], raw["return_code"])
return code != "" && responseOK(raw)
}
func responseOK(raw map[string]string) bool {
code := strings.ToUpper(firstNonEmpty(raw["code"], raw["resp_code"], raw["result_code"], raw["return_code"]))
if code == "" {
return true
}
return code == "0" || code == "000000" || code == "SUCCESS" || code == "BBS00000"
}
func responseMessage(raw map[string]string) string {
return firstNonEmpty(raw["message"], raw["msg"], raw["error_msg"], raw["resp_msg"], raw["return_msg"])
}
func flattenJSON(value any) map[string]string {
out := map[string]string{}
var walk func(prefix string, v any)
walk = func(prefix string, v any) {
switch item := v.(type) {
case map[string]any:
for key, child := range item {
if key == "req_data" || key == "resp_data" || key == "data" {
walk("", child)
continue
}
walk(key, child)
}
case []any:
raw, _ := json.Marshal(item)
if prefix != "" {
out[prefix] = string(raw)
}
case nil:
if prefix != "" {
out[prefix] = ""
}
case string:
if prefix != "" {
out[prefix] = item
}
case float64:
if prefix != "" {
if math.Trunc(item) == item {
out[prefix] = strconv.FormatInt(int64(item), 10)
} else {
out[prefix] = strconv.FormatFloat(item, 'f', -1, 64)
}
}
case bool:
if prefix != "" {
out[prefix] = strconv.FormatBool(item)
}
default:
if prefix != "" {
raw, _ := json.Marshal(item)
out[prefix] = string(raw)
}
}
}
walk("", value)
return out
}
func stringifyMap(value map[string]any) map[string]string {
out := map[string]string{}
for key, item := range value {
switch typed := item.(type) {
case string:
out[key] = typed
default:
raw, _ := json.Marshal(typed)
out[key] = string(raw)
}
}
return out
}
func defaultLocationInfo(clientIP string) map[string]string {
info := map[string]string{
"request_ip": firstNonEmpty(clientIP, "127.0.0.1"),
}
return info
}
func payModeFromPayWay(payWay string) string {
switch strings.ToUpper(payWay) {
case "WXZF", "WECHAT", "WECHATPAY":
return "WECHAT"
case "UNIONPAY", "UQRCODEPAY":
return "UQRCODEPAY"
default:
return "ALIPAY"
}
}
func normalizeCounterPayMode(value string) string {
switch strings.ToUpper(strings.TrimSpace(value)) {
case "", "AUTO", "ALL", "NONE", "UNLIMITED":
return ""
default:
return strings.ToUpper(strings.TrimSpace(value))
}
}
func sanitizeText(value string, maxRunes int) string {
value = strings.TrimSpace(value)
if value == "" || maxRunes <= 0 {
return value
}
runes := []rune(value)
if len(runes) <= maxRunes {
return value
}
return string(runes[:maxRunes])
}
func Nonce(length int) string {
const chars = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
if length <= 0 {
length = 32
}
buf := make([]byte, length)
if _, err := rand.Read(buf); err != nil {
return strconv.FormatInt(time.Now().UnixNano(), 36)
}
for i := range buf {
buf[i] = chars[int(buf[i])%len(chars)]
}
return string(buf)
}
func firstNonEmpty(values ...string) string {
for _, value := range values {
if strings.TrimSpace(value) != "" {
return value
}
}
return ""
}
@@ -0,0 +1,280 @@
package lakala
import (
"context"
"crypto/rand"
"crypto/rsa"
"crypto/x509"
"encoding/json"
"encoding/pem"
"net/http"
"net/http/httptest"
"strings"
"testing"
"time"
"hfb_sys/backend/internal/timeutil"
)
func TestVerifyNotifyDetail(t *testing.T) {
key, err := rsa.GenerateKey(rand.Reader, 2048)
if err != nil {
t.Fatalf("generate key: %v", err)
}
privatePEM, certPEM := testKeyPairPEM(t, key)
client := NewClient(Config{
GatewayURL: "https://example.com",
AppID: "app-1",
SerialNo: "serial-1",
MerchantID: "merchant-1",
PrivateKey: privatePEM,
NotifyCert: certPEM,
})
body := `{"req_data":{"out_order_no":"NO1","total_amount":100,"trade_state":"SUCCESS"}}`
message := "1710000000\nabc123\n" + body + "\n"
signature, err := signRSA(key, []byte(message))
if err != nil {
t.Fatalf("signRSA: %v", err)
}
authorization := `LKLAPI-SHA256withRSA timestamp="1710000000",nonce_str="abc123",signature="` + signature + `"`
result := client.VerifyNotifyDetail(body, authorization)
if !result.OK {
t.Fatalf("VerifyNotifyDetail().OK = false, got=%s expected=%v base=%v", result.Got, result.Expected, result.BaseString)
}
tampered := client.VerifyNotifyDetail(strings.Replace(body, "100", "101", 1), authorization)
if tampered.OK {
t.Fatal("VerifyNotifyDetail() = true after body changed, want false")
}
}
func TestParsePayloadNormalizesAliases(t *testing.T) {
params, err := ParsePayload([]byte(`{
"req_data": {
"out_order_no": "ORDER1",
"pay_order_no": "PAY1",
"total_amount": 88,
"trade_state": "SUCCESS",
"trade_time": "20240521101010"
}
}`))
if err != nil {
t.Fatalf("ParsePayload error = %v", err)
}
if params["third_order_id"] != "ORDER1" {
t.Fatalf("third_order_id = %q, want ORDER1", params["third_order_id"])
}
if params["provider_order_id"] != "PAY1" {
t.Fatalf("provider_order_id = %q, want PAY1", params["provider_order_id"])
}
if params["amount"] != "88" {
t.Fatalf("amount = %q, want 88", params["amount"])
}
if params["status"] != "paid" {
t.Fatalf("status = %q, want paid", params["status"])
}
}
func TestNormalizeRefundStatusTreatsSuccessCodeAsRefunded(t *testing.T) {
status := normalizeRefundStatus(map[string]string{
"code": "BBS00000",
"msg": "成功",
})
if status != "refunded" {
t.Fatalf("normalizeRefundStatus() = %q, want refunded", status)
}
}
func TestNormalizeRefundStatusTreatsSuccessCodeWithRefundingAsRefunded(t *testing.T) {
status := normalizeRefundStatus(map[string]string{
"code": "BBS00000",
"msg": "成功",
"status": "refunding",
"refund_amount": "960",
"trade_no": "20260610110110001231120132051564",
})
if status != "refunded" {
t.Fatalf("normalizeRefundStatus() = %q, want refunded", status)
}
}
func TestNormalizeRefundStatusKeepsUnknownWithoutCodeAsRefunding(t *testing.T) {
status := normalizeRefundStatus(map[string]string{
"status": "processing",
})
if status != "refunding" {
t.Fatalf("normalizeRefundStatus() = %q, want refunding", status)
}
}
func TestCreatePaymentOmitsCounterParamWhenPayModeBlank(t *testing.T) {
body := captureCreatePaymentBody(t, "")
reqData := body["req_data"].(map[string]any)
if _, ok := reqData["counter_param"]; ok {
t.Fatalf("counter_param exists when pay_mode is blank: %#v", reqData["counter_param"])
}
}
func TestCreatePaymentSetsCounterParamWhenPayModeConfigured(t *testing.T) {
body := captureCreatePaymentBody(t, "WECHAT")
reqData := body["req_data"].(map[string]any)
if reqData["counter_param"] != `{"pay_mode":"WECHAT"}` {
t.Fatalf("counter_param = %#v, want WECHAT", reqData["counter_param"])
}
}
func TestCreatePaymentTrimsGatewayURLWhitespace(t *testing.T) {
body := captureCreatePaymentBody(t, "", "\t")
reqData := body["req_data"].(map[string]any)
if reqData["out_order_no"] != "ORDER1" {
t.Fatalf("out_order_no = %#v, want ORDER1", reqData["out_order_no"])
}
}
func TestCreatePaymentUsesShanghaiTimeWhenLocalIsUTC(t *testing.T) {
oldLocal := time.Local
time.Local = time.UTC
defer func() {
time.Local = oldLocal
}()
loc := timeutil.ShanghaiLocation()
before := time.Now().In(loc)
body := captureCreatePaymentBody(t, "")
after := time.Now().In(loc)
reqData := body["req_data"].(map[string]any)
reqTime := parseLakalaTestTime(t, body["req_time"].(string))
if reqTime.Before(before.Add(-2*time.Second)) || reqTime.After(after.Add(2*time.Second)) {
t.Fatalf("req_time = %s, want between %s and %s", reqTime, before, after)
}
efficientTime := parseLakalaTestTime(t, reqData["order_efficient_time"].(string))
wantMin := before.Add(15*time.Minute - 2*time.Second)
wantMax := after.Add(15*time.Minute + 2*time.Second)
if efficientTime.Before(wantMin) || efficientTime.After(wantMax) {
t.Fatalf("order_efficient_time = %s, want between %s and %s", efficientTime, wantMin, wantMax)
}
}
func TestCreateRefundReturnsRawRequestOnHTTPError(t *testing.T) {
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.URL.Path != endpointRefund {
t.Fatalf("path = %s, want %s", r.URL.Path, endpointRefund)
}
w.WriteHeader(http.StatusBadRequest)
_, _ = w.Write([]byte(`{"code":"OP90001","msg":"请求服务失败"}`))
}))
defer server.Close()
key, err := rsa.GenerateKey(rand.Reader, 2048)
if err != nil {
t.Fatalf("generate key: %v", err)
}
privatePEM, certPEM := testKeyPairPEM(t, key)
client := NewClient(Config{
GatewayURL: server.URL,
AppID: "app-1",
SerialNo: "serial-1",
MerchantID: "merchant-1",
TermNo: "term-1",
PrivateKey: privatePEM,
NotifyCert: certPEM,
})
resp, err := client.CreateRefund(context.Background(), CreateRefundRequest{
ThirdOrderID: "PAY123",
ProviderOrderID: "TRADE123",
MerchantRefundID: "REF123",
RefundAmountCent: 99,
RefundReason: "结账退款",
})
if err == nil {
t.Fatal("CreateRefund error = nil, want HTTP error")
}
if resp == nil {
t.Fatal("CreateRefund response = nil, want raw request")
}
if resp.RawRequest["merchant_no"] != "merchant-1" ||
resp.RawRequest["term_no"] != "term-1" ||
resp.RawRequest["out_trade_no"] != "REF123" ||
resp.RawRequest["refund_amount"] != "99" ||
resp.RawRequest["origin_out_trade_no"] != "PAY123" ||
resp.RawRequest["origin_trade_no"] != "TRADE123" {
t.Fatalf("raw request = %#v", resp.RawRequest)
}
}
func parseLakalaTestTime(t *testing.T, value string) time.Time {
t.Helper()
parsed, err := time.ParseInLocation("20060102150405", value, timeutil.ShanghaiLocation())
if err != nil {
t.Fatalf("parse lakala time %q: %v", value, err)
}
return parsed
}
func testKeyPairPEM(t *testing.T, key *rsa.PrivateKey) (string, string) {
t.Helper()
privateDER := x509.MarshalPKCS1PrivateKey(key)
privatePEM := string(pem.EncodeToMemory(&pem.Block{
Type: "RSA PRIVATE KEY",
Bytes: privateDER,
}))
template := &x509.Certificate{}
certDER, err := x509.CreateCertificate(rand.Reader, template, template, &key.PublicKey, key)
if err != nil {
t.Fatalf("create certificate: %v", err)
}
certPEM := string(pem.EncodeToMemory(&pem.Block{
Type: "CERTIFICATE",
Bytes: certDER,
}))
return privatePEM, certPEM
}
func captureCreatePaymentBody(t *testing.T, payMode string, gatewaySuffix ...string) map[string]any {
t.Helper()
var captured map[string]any
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.URL.Path != endpointCounterCreate {
t.Fatalf("path = %s, want %s", r.URL.Path, endpointCounterCreate)
}
if err := json.NewDecoder(r.Body).Decode(&captured); err != nil {
t.Fatalf("decode request: %v", err)
}
w.Header().Set("Content-Type", "application/json")
_, _ = w.Write([]byte(`{"resp_code":"0","result_code":"0","pay_order_no":"LK1"}`))
}))
defer server.Close()
key, err := rsa.GenerateKey(rand.Reader, 2048)
if err != nil {
t.Fatalf("generate key: %v", err)
}
privatePEM, certPEM := testKeyPairPEM(t, key)
gatewayURL := server.URL
if len(gatewaySuffix) > 0 {
gatewayURL += gatewaySuffix[0]
}
client := NewClient(Config{
GatewayURL: gatewayURL,
AppID: "app-1",
SerialNo: "serial-1",
MerchantID: "merchant-1",
PrivateKey: privatePEM,
NotifyCert: certPEM,
PayMode: payMode,
})
_, err = client.CreatePayment(context.Background(), CreatePaymentRequest{
ThirdOrderID: "ORDER1",
AmountCent: 100,
NotifyURL: "https://example.com/notify",
Body: "测试订单",
})
if err != nil {
t.Fatalf("CreatePayment error = %v", err)
}
return captured
}
@@ -0,0 +1,583 @@
package leshua
import (
"bytes"
"context"
"crypto/md5"
"crypto/rand"
"encoding/hex"
"encoding/json"
"encoding/xml"
"errors"
"fmt"
"io"
"net/http"
"net/url"
"sort"
"strings"
"time"
)
var (
ErrConfigIncomplete = errors.New("leshua payment config incomplete")
ErrUnsupportedSign = errors.New("unsupported leshua sign type")
)
type Client struct {
cfg Config
httpClient *http.Client
}
type Config struct {
GatewayURL string
MerchantID string
SignKey string
NotifyKey string
NotifyURL string
JumpURL string
PayWay string
JSPayFlag string
SignType string
}
type CreatePaymentRequest struct {
ThirdOrderID string
AmountCent int64
PayWay string
JSPayFlag string
NotifyURL string
JumpURL string
ClientIP string
Body string
Attach string
}
type CreatePaymentResponse struct {
RespCode string
ResultCode string
ErrorCode string
ErrorMessage string
MerchantID string
ThirdOrderID string
ProviderOrderID string
PayWay string
TDCode string
JSPayURL string
JSPayInfo string
Raw map[string]string
}
type QueryPaymentResponse struct {
RespCode string
ResultCode string
ErrorCode string
ErrorMessage string
MerchantID string
ThirdOrderID string
ProviderOrderID string
Status string
Amount string
PayWay string
PayTime string
Raw map[string]string
}
type CreateRefundRequest struct {
ThirdOrderID string // 原支付商户订单号
LeshuaOrderID string // 原支付乐刷订单号(优先使用)
MerchantRefundID string // 商户退款单号(唯一)
RefundAmountCent int64 // 退款金额(分)
NotifyURL string
Attach string
}
type CreateRefundResponse struct {
RespCode string
ResultCode string
ErrorCode string
ErrorMessage string
MerchantID string
ThirdOrderID string
LeshuaOrderID string
MerchantRefundID string
LeshuaRefundID string
RefundAmount string
TotalAmount string
OrderBalance string
Status string
Raw map[string]string
}
type QueryRefundRequest struct {
ThirdOrderID string
LeshuaOrderID string
MerchantRefundID string
LeshuaRefundID string
}
type QueryRefundResponse struct {
RespCode string
ResultCode string
ErrorCode string
ErrorMessage string
MerchantID string
ThirdOrderID string
LeshuaOrderID string
MerchantRefundID string
LeshuaRefundID string
Status string
RefundAmount string
TotalAmount string
RefundTime string
Raw map[string]string
}
type VerifyNotifyResult struct {
OK bool
MatchedKey string
Got string
Expected map[string]string
BaseString map[string]string
ParamKeys []string
}
func NewClient(cfg Config) *Client {
return &Client{
cfg: cfg,
httpClient: &http.Client{
Timeout: 10 * time.Second,
},
}
}
func (c *Client) CreatePayment(ctx context.Context, req CreatePaymentRequest) (*CreatePaymentResponse, map[string]string, error) {
if err := c.validate(); err != nil {
return nil, nil, err
}
payWay := firstNonEmpty(req.PayWay, c.cfg.PayWay, "ZFBZF")
jsPayFlag := firstNonEmpty(req.JSPayFlag, c.cfg.JSPayFlag, "2")
params := map[string]string{
"service": "get_tdcode",
"merchant_id": c.cfg.MerchantID,
"third_order_id": req.ThirdOrderID,
"amount": fmt.Sprintf("%d", req.AmountCent),
"pay_way": payWay,
"jspay_flag": jsPayFlag,
"nonce_str": Nonce(32),
"body": sanitizeText(req.Body, 128),
"attach": sanitizeText(req.Attach, 64),
}
if c.cfg.SignType != "" && !strings.EqualFold(c.cfg.SignType, "MD5") {
params["sign_type"] = c.cfg.SignType
}
if req.NotifyURL != "" {
params["notify_url"] = req.NotifyURL
}
if req.JumpURL != "" {
params["jump_url"] = req.JumpURL
}
if req.ClientIP != "" {
params["client_ip"] = req.ClientIP
}
params["sign"] = Sign(params, c.cfg.SignKey, SignOptions{})
raw, err := c.post(ctx, params)
if err != nil {
return nil, params, err
}
resp := &CreatePaymentResponse{
RespCode: raw["resp_code"],
ResultCode: raw["result_code"],
ErrorCode: raw["error_code"],
ErrorMessage: firstNonEmpty(raw["error_msg"], raw["resp_msg"]),
MerchantID: raw["merchant_id"],
ThirdOrderID: raw["third_order_id"],
ProviderOrderID: raw["leshua_order_id"],
PayWay: raw["pay_way"],
TDCode: raw["td_code"],
JSPayURL: raw["jspay_url"],
JSPayInfo: raw["jspay_info"],
Raw: raw,
}
return resp, params, nil
}
func (c *Client) QueryPayment(ctx context.Context, thirdOrderID, providerOrderID string) (*QueryPaymentResponse, error) {
if err := c.validate(); err != nil {
return nil, err
}
params := map[string]string{
"service": "query_status",
"merchant_id": c.cfg.MerchantID,
"nonce_str": Nonce(32),
}
if providerOrderID != "" {
params["leshua_order_id"] = providerOrderID
} else {
params["third_order_id"] = thirdOrderID
}
if c.cfg.SignType != "" && !strings.EqualFold(c.cfg.SignType, "MD5") {
params["sign_type"] = c.cfg.SignType
}
params["sign"] = Sign(params, c.cfg.SignKey, SignOptions{})
raw, err := c.post(ctx, params)
if err != nil {
return nil, err
}
return &QueryPaymentResponse{
RespCode: raw["resp_code"],
ResultCode: raw["result_code"],
ErrorCode: raw["error_code"],
ErrorMessage: firstNonEmpty(raw["error_msg"], raw["resp_msg"]),
MerchantID: raw["merchant_id"],
ThirdOrderID: raw["third_order_id"],
ProviderOrderID: raw["leshua_order_id"],
Status: raw["status"],
Amount: raw["amount"],
PayWay: raw["pay_way"],
PayTime: raw["pay_time"],
Raw: raw,
}, nil
}
func (c *Client) CreateRefund(ctx context.Context, req CreateRefundRequest) (*CreateRefundResponse, map[string]string, error) {
if err := c.validate(); err != nil {
return nil, nil, err
}
params := map[string]string{
"service": "unified_refund",
"merchant_id": c.cfg.MerchantID,
"merchant_refund_id": req.MerchantRefundID,
"refund_amount": fmt.Sprintf("%d", req.RefundAmountCent),
"nonce_str": Nonce(32),
}
if req.LeshuaOrderID != "" {
params["leshua_order_id"] = req.LeshuaOrderID
} else if req.ThirdOrderID != "" {
params["third_order_id"] = req.ThirdOrderID
}
if req.Attach != "" {
params["attach"] = sanitizeText(req.Attach, 64)
}
if c.cfg.SignType != "" && !strings.EqualFold(c.cfg.SignType, "MD5") {
params["sign_type"] = c.cfg.SignType
}
if req.NotifyURL != "" {
params["notify_url"] = req.NotifyURL
}
params["sign"] = Sign(params, c.cfg.SignKey, SignOptions{})
raw, err := c.post(ctx, params)
if err != nil {
return nil, params, err
}
resp := &CreateRefundResponse{
RespCode: raw["resp_code"],
ResultCode: raw["result_code"],
ErrorCode: raw["error_code"],
ErrorMessage: firstNonEmpty(raw["error_msg"], raw["resp_msg"]),
MerchantID: raw["merchant_id"],
ThirdOrderID: raw["third_order_id"],
LeshuaOrderID: raw["leshua_order_id"],
MerchantRefundID: raw["merchant_refund_id"],
LeshuaRefundID: raw["leshua_refund_id"],
RefundAmount: raw["refund_amount"],
TotalAmount: raw["total_amount"],
OrderBalance: raw["order_balance"],
Status: raw["status"],
Raw: raw,
}
return resp, params, nil
}
func (c *Client) QueryRefund(ctx context.Context, req QueryRefundRequest) (*QueryRefundResponse, error) {
if err := c.validate(); err != nil {
return nil, err
}
params := map[string]string{
"service": "unified_query_refund",
"merchant_id": c.cfg.MerchantID,
"nonce_str": Nonce(32),
}
if req.LeshuaOrderID != "" {
params["leshua_order_id"] = req.LeshuaOrderID
} else if req.ThirdOrderID != "" {
params["third_order_id"] = req.ThirdOrderID
}
if req.LeshuaRefundID != "" {
params["leshua_refund_id"] = req.LeshuaRefundID
} else if req.MerchantRefundID != "" {
params["merchant_refund_id"] = req.MerchantRefundID
}
if c.cfg.SignType != "" && !strings.EqualFold(c.cfg.SignType, "MD5") {
params["sign_type"] = c.cfg.SignType
}
params["sign"] = Sign(params, c.cfg.SignKey, SignOptions{})
raw, err := c.post(ctx, params)
if err != nil {
return nil, err
}
return &QueryRefundResponse{
RespCode: raw["resp_code"],
ResultCode: raw["result_code"],
ErrorCode: raw["error_code"],
ErrorMessage: firstNonEmpty(raw["error_msg"], raw["resp_msg"]),
MerchantID: raw["merchant_id"],
ThirdOrderID: raw["third_order_id"],
LeshuaOrderID: raw["leshua_order_id"],
MerchantRefundID: raw["merchant_refund_id"],
LeshuaRefundID: raw["leshua_refund_id"],
Status: raw["status"],
RefundAmount: raw["refund_amount"],
TotalAmount: raw["total_amount"],
RefundTime: raw["refund_time"],
Raw: raw,
}, nil
}
func (c *Client) VerifyNotify(params map[string]string) bool {
return c.VerifyNotifyDetail(params).OK
}
func (c *Client) VerifyNotifyDetail(params map[string]string) VerifyNotifyResult {
got := strings.ToUpper(params["sign"])
result := VerifyNotifyResult{
Got: got,
Expected: map[string]string{},
BaseString: map[string]string{},
ParamKeys: notifyParamKeys(params),
}
if got == "" {
return result
}
for _, item := range c.notifyKeyCandidates() {
expected := Sign(params, item.key, notifySignOptions())
baseString := SignBaseString(params, notifySignOptions())
result.Expected[item.name] = expected
result.BaseString[item.name] = baseString
if got == expected {
result.OK = true
result.MatchedKey = item.name
return result
}
}
return result
}
func notifySignOptions() SignOptions {
return SignOptions{
IncludeEmpty: true,
ExcludeKeys: []string{"error_code", "leshua", "sign"},
}
}
type notifyKeyCandidate struct {
name string
key string
}
func (c *Client) notifyKeyCandidates() []notifyKeyCandidate {
candidates := []notifyKeyCandidate{}
if c.cfg.NotifyKey != "" {
candidates = append(candidates, notifyKeyCandidate{name: "notify_key", key: c.cfg.NotifyKey})
}
return candidates
}
func notifyParamKeys(params map[string]string) []string {
keys := make([]string, 0, len(params))
for key := range params {
if key == "sign" || key == "error_code" || key == "leshua" {
continue
}
keys = append(keys, key)
}
sort.Strings(keys)
return keys
}
func (c *Client) validate() error {
if strings.TrimSpace(c.cfg.GatewayURL) == "" || c.cfg.MerchantID == "" || c.cfg.SignKey == "" {
return ErrConfigIncomplete
}
if c.cfg.SignType != "" && !strings.EqualFold(c.cfg.SignType, "MD5") {
return ErrUnsupportedSign
}
return nil
}
func (c *Client) post(ctx context.Context, params map[string]string) (map[string]string, error) {
values := url.Values{}
for key, value := range params {
values.Set(key, value)
}
httpReq, err := http.NewRequestWithContext(ctx, http.MethodPost, strings.TrimSpace(c.cfg.GatewayURL), strings.NewReader(values.Encode()))
if err != nil {
return nil, err
}
httpReq.Header.Set("Content-Type", "application/x-www-form-urlencoded")
httpResp, err := c.httpClient.Do(httpReq)
if err != nil {
return nil, err
}
defer httpResp.Body.Close()
body, err := io.ReadAll(io.LimitReader(httpResp.Body, 1<<20))
if err != nil {
return nil, err
}
if httpResp.StatusCode < 200 || httpResp.StatusCode >= 300 {
return nil, fmt.Errorf("leshua http status %d: %s", httpResp.StatusCode, string(body))
}
return ParsePayload(body)
}
type SignOptions struct {
IncludeEmpty bool
ExcludeKeys []string
}
func Sign(params map[string]string, key string, opts SignOptions) string {
baseString := SignBaseString(params, opts)
stringSignTemp := "key=" + key
if baseString != "" {
stringSignTemp = baseString + "&key=" + key
}
sum := md5.Sum([]byte(stringSignTemp))
return strings.ToUpper(hex.EncodeToString(sum[:]))
}
func SignBaseString(params map[string]string, opts SignOptions) string {
excluded := map[string]bool{}
for _, item := range opts.ExcludeKeys {
excluded[item] = true
}
if len(opts.ExcludeKeys) == 0 {
excluded["sign"] = true
}
keys := make([]string, 0, len(params))
for name, value := range params {
if excluded[name] {
continue
}
if !opts.IncludeEmpty && value == "" {
continue
}
keys = append(keys, name)
}
sort.Strings(keys)
parts := make([]string, 0, len(keys)+1)
for _, name := range keys {
parts = append(parts, name+"="+params[name])
}
return strings.Join(parts, "&")
}
func ParsePayload(body []byte) (map[string]string, error) {
trimmed := bytes.TrimSpace(body)
if len(trimmed) == 0 {
return map[string]string{}, nil
}
if trimmed[0] == '<' {
return parseXMLPayload(trimmed)
}
if trimmed[0] == '{' {
var raw map[string]any
if err := json.Unmarshal(trimmed, &raw); err != nil {
return nil, err
}
out := map[string]string{}
for key, value := range raw {
out[key] = fmt.Sprint(value)
}
return out, nil
}
values, err := url.ParseQuery(string(trimmed))
if err != nil {
return nil, err
}
out := map[string]string{}
for key, item := range values {
if len(item) > 0 {
out[key] = item[0]
}
}
if len(out) == 0 {
return nil, fmt.Errorf("unsupported leshua payload: %s", string(trimmed))
}
return out, nil
}
func parseXMLPayload(body []byte) (map[string]string, error) {
decoder := xml.NewDecoder(bytes.NewReader(body))
out := map[string]string{}
var current string
depth := 0
for {
token, err := decoder.Token()
if err == io.EOF {
break
}
if err != nil {
return nil, err
}
switch item := token.(type) {
case xml.StartElement:
depth++
if depth > 1 {
current = item.Name.Local
if _, exists := out[current]; !exists {
out[current] = ""
}
}
case xml.CharData:
value := strings.TrimSpace(string(item))
if current != "" && value != "" {
out[current] = value
}
case xml.EndElement:
if current == item.Name.Local {
current = ""
}
if depth > 0 {
depth--
}
}
}
return out, nil
}
func Nonce(length int) string {
const alphabet = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
if length <= 0 {
length = 32
}
buf := make([]byte, length)
random := make([]byte, length)
if _, err := rand.Read(random); err != nil {
for i := range buf {
buf[i] = alphabet[int(time.Now().UnixNano())%len(alphabet)]
}
return string(buf)
}
for i, item := range random {
buf[i] = alphabet[int(item)%len(alphabet)]
}
return string(buf)
}
func firstNonEmpty(values ...string) string {
for _, value := range values {
if value != "" {
return value
}
}
return ""
}
func sanitizeText(value string, max int) string {
value = strings.ReplaceAll(value, "\n", " ")
value = strings.ReplaceAll(value, "\r", " ")
value = strings.TrimSpace(value)
if max > 0 && len([]rune(value)) > max {
return string([]rune(value)[:max])
}
return value
}
@@ -0,0 +1,216 @@
package leshua
import (
"strings"
"testing"
)
func TestSignUsesASCIISortedNonEmptyParams(t *testing.T) {
params := map[string]string{
"service": "get_tdcode",
"merchant_id": "1234567890",
"third_order_id": "NO1",
"amount": "100",
"nonce_str": "abc",
"empty": "",
"sign": "ignored",
}
got := Sign(params, "secret", SignOptions{})
want := "1E7892034AA77899E8DD609C4FA09E76"
if got != want {
t.Fatalf("Sign() = %s, want %s", got, want)
}
baseString := SignBaseString(params, SignOptions{})
wantBaseString := "amount=100&merchant_id=1234567890&nonce_str=abc&service=get_tdcode&third_order_id=NO1"
if baseString != wantBaseString {
t.Fatalf("SignBaseString() = %s, want %s", baseString, wantBaseString)
}
}
func TestVerifyNotifyIncludesEmptyAndExcludesErrorCode(t *testing.T) {
client := NewClient(Config{NotifyKey: "notify-secret"})
params := map[string]string{
"merchant_id": "1234567890",
"third_order_id": "NO1",
"leshua_order_id": "LS1",
"amount": "100",
"status": "2",
"attach": "",
"leshua": "",
"error_code": "-20001",
}
params["sign"] = Sign(params, "notify-secret", SignOptions{
IncludeEmpty: true,
ExcludeKeys: []string{"error_code", "leshua", "sign"},
})
if !client.VerifyNotify(params) {
t.Fatal("VerifyNotify() = false, want true")
}
params["amount"] = "101"
if client.VerifyNotify(params) {
t.Fatal("VerifyNotify() = true after amount changed, want false")
}
}
func TestVerifyNotifyDoesNotFallBackToSignKey(t *testing.T) {
client := NewClient(Config{
NotifyKey: "wrong-notify-secret",
SignKey: "sign-secret",
})
params := map[string]string{
"merchant_id": "1234567890",
"third_order_id": "NO1",
"leshua_order_id": "LS1",
"amount": "100",
"status": "2",
}
params["sign"] = Sign(params, "sign-secret", SignOptions{
IncludeEmpty: true,
ExcludeKeys: []string{"error_code", "sign"},
})
result := client.VerifyNotifyDetail(params)
if result.OK {
t.Fatal("VerifyNotifyDetail().OK = true, want false")
}
if _, ok := result.Expected["sign_key"]; ok {
t.Fatal("VerifyNotifyDetail() unexpectedly used sign_key fallback")
}
}
func TestVerifyNotifyUsesDocumentedNotifySignature(t *testing.T) {
client := NewClient(Config{NotifyKey: "notify-secret"})
params := map[string]string{
"merchant_id": "1234567890",
"third_order_id": "NO1",
"leshua_order_id": "LS1",
"amount": "100",
"status": "2",
"sign_type": "MD5",
}
params["sign"] = Sign(params, "notify-secret", SignOptions{
IncludeEmpty: true,
ExcludeKeys: []string{"error_code", "leshua", "sign"},
})
result := client.VerifyNotifyDetail(params)
if !result.OK {
t.Fatal("VerifyNotifyDetail().OK = false, want true")
}
if result.MatchedKey != "notify_key" {
t.Fatalf("MatchedKey = %s, want notify_key", result.MatchedKey)
}
}
func TestVerifyNotifyKeepsEmptyXMLFieldsInSignature(t *testing.T) {
client := NewClient(Config{NotifyKey: "notify-secret"})
params, err := ParsePayload([]byte(`<leshua>
<amount>100</amount>
<goods_tag></goods_tag>
<merchant_id>1234567890</merchant_id>
<sign_type>MD5</sign_type>
<status>2</status>
<third_order_id>NO1</third_order_id>
</leshua>`))
if err != nil {
t.Fatalf("ParsePayload(xml) error = %v", err)
}
params["sign"] = Sign(params, "notify-secret", SignOptions{
IncludeEmpty: true,
ExcludeKeys: []string{"error_code", "leshua", "sign"},
})
result := client.VerifyNotifyDetail(params)
if !result.OK {
t.Fatal("VerifyNotifyDetail().OK = false, want true")
}
baseString := result.BaseString[result.MatchedKey]
if !strings.Contains(baseString, "goods_tag=") {
t.Fatalf("baseString = %s, want goods_tag included", baseString)
}
}
func TestParsePayloadSupportsFormAndXML(t *testing.T) {
form, err := ParsePayload([]byte("third_order_id=NO1&status=2&amount=100"))
if err != nil {
t.Fatalf("ParsePayload(form) error = %v", err)
}
if form["third_order_id"] != "NO1" || form["status"] != "2" || form["amount"] != "100" {
t.Fatalf("ParsePayload(form) = %#v", form)
}
xml, err := ParsePayload([]byte("<xml><third_order_id>NO2</third_order_id><status>6</status><goods_tag></goods_tag><coupon/></xml>"))
if err != nil {
t.Fatalf("ParsePayload(xml) error = %v", err)
}
if xml["third_order_id"] != "NO2" || xml["status"] != "6" {
t.Fatalf("ParsePayload(xml) = %#v", xml)
}
if value, ok := xml["goods_tag"]; !ok || value != "" {
t.Fatalf("ParsePayload(xml).goods_tag = %q, exists=%v; want empty value", value, ok)
}
if value, ok := xml["coupon"]; !ok || value != "" {
t.Fatalf("ParsePayload(xml).coupon = %q, exists=%v; want empty value", value, ok)
}
}
func TestSignRefundUsesSameAlgorithm(t *testing.T) {
params := map[string]string{
"service": "unified_refund",
"merchant_id": "1234567890",
"merchant_refund_id": "REF001",
"refund_amount": "100",
"leshua_order_id": "LS1",
"nonce_str": "abc",
"sign": "ignored",
}
got := Sign(params, "secret", SignOptions{})
baseString := SignBaseString(params, SignOptions{})
wantBaseString := "leshua_order_id=LS1&merchant_id=1234567890&merchant_refund_id=REF001&nonce_str=abc&refund_amount=100&service=unified_refund"
if baseString != wantBaseString {
t.Fatalf("SignBaseString() = %s, want %s", baseString, wantBaseString)
}
want := Sign(map[string]string{
"service": "unified_refund",
"merchant_id": "1234567890",
"merchant_refund_id": "REF001",
"refund_amount": "100",
"leshua_order_id": "LS1",
"nonce_str": "abc",
}, "secret", SignOptions{})
if got != want {
t.Fatalf("Sign() = %s, want %s", got, want)
}
}
func TestVerifyRefundNotify(t *testing.T) {
client := NewClient(Config{NotifyKey: "notify-secret"})
params := map[string]string{
"merchant_id": "1234567890",
"third_order_id": "NO1",
"leshua_order_id": "LS1",
"merchant_refund_id": "REF001",
"leshua_refund_id": "LREF001",
"refund_amount": "100",
"total_amount": "200",
"status": "11",
"attach": "",
}
params["sign"] = Sign(params, "notify-secret", SignOptions{
IncludeEmpty: true,
ExcludeKeys: []string{"error_code", "leshua", "sign"},
})
if !client.VerifyNotify(params) {
t.Fatal("VerifyNotify() = false, want true for refund notify")
}
params["status"] = "12"
if client.VerifyNotify(params) {
t.Fatal("VerifyNotify() = true after status changed without re-sign, want false")
}
}
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,266 @@
package shuncheng
import (
"context"
"encoding/json"
"net/http"
"net/http/httptest"
"strconv"
"testing"
)
func TestSignUsesDocumentedBase64LowerMD5(t *testing.T) {
params := map[string]string{
"service": "get_tdcode",
"merchant_id": "1234567890",
"third_order_id": "NO1",
"amount": "100",
"nonce_str": "abc",
"req_serial_no": "req001",
"empty": "",
"sign": "ignored",
}
got := SignStrings(params, "secret")
want := "ZTM5YTQ1NDk4YmRhODJlYTYyOWQzMGI2N2M5YzFjYjQ="
if got != want {
t.Fatalf("SignStrings() = %s, want %s", got, want)
}
baseString := SignBaseString(stringMapToAny(params))
wantBaseString := "amount=100&merchant_id=1234567890&nonce_str=abc&req_serial_no=req001&service=get_tdcode&third_order_id=NO1"
if baseString != wantBaseString {
t.Fatalf("SignBaseString() = %s, want %s", baseString, wantBaseString)
}
}
func TestSignSortsNestedObjectLikeDocs(t *testing.T) {
params := map[string]any{
"reqSerialNo": "20260318110810747",
"data": map[string]any{
"merchantId": "M1",
"applyAmount": 10000,
"reqId": "R1",
"ignored": nil,
},
}
baseString := SignBaseString(params)
wantBaseString := `data={"applyAmount":10000,"merchantId":"M1","reqId":"R1"}&reqSerialNo=20260318110810747`
if baseString != wantBaseString {
t.Fatalf("SignBaseString() = %s, want %s", baseString, wantBaseString)
}
got := Sign(params, "secret")
want := "N2VlOWY3OWJlZmU4YThiNjEwN2Y1NWYxNzI0ZjY0NTY="
if got != want {
t.Fatalf("Sign() = %s, want %s", got, want)
}
}
func TestParsePayloadNormalizesXMLAliases(t *testing.T) {
params, err := ParsePayload([]byte(`<schc>
<resp_code><![CDATA[200]]></resp_code>
<result_code><![CDATA[0]]></result_code>
<third_order_id><![CDATA[PAY1]]></third_order_id>
<schc_order_id><![CDATA[SC1]]></schc_order_id>
<schc_refund_id><![CDATA[RF1]]></schc_refund_id>
<refund_amount><![CDATA[100]]></refund_amount>
<status><![CDATA[11]]></status>
</schc>`))
if err != nil {
t.Fatalf("ParsePayload() error = %v", err)
}
if params["provider_order_id"] != "SC1" {
t.Fatalf("provider_order_id = %q, want SC1", params["provider_order_id"])
}
if params["provider_refund_id"] != "RF1" {
t.Fatalf("provider_refund_id = %q, want RF1", params["provider_refund_id"])
}
}
func TestParsePayloadExtractsEscapedXMLFromHTML(t *testing.T) {
params, err := ParsePayload([]byte(`<html><body>&lt;schc&gt;&lt;resp_code&gt;200&lt;/resp_code&gt;&lt;result_code&gt;0&lt;/result_code&gt;&lt;third_order_id&gt;PAY1&lt;/third_order_id&gt;&lt;schc_order_id&gt;SC1&lt;/schc_order_id&gt;&lt;jspay_url&gt;https://pay.example/sc1&lt;/jspay_url&gt;&lt;/schc&gt;</body></html>`))
if err != nil {
t.Fatalf("ParsePayload() error = %v", err)
}
if params["provider_order_id"] != "SC1" || params["jspay_url"] != "https://pay.example/sc1" {
t.Fatalf("ParsePayload() = %#v, want extracted shuncheng xml", params)
}
}
func TestParsePayloadAcceptsEscapedURLQueryInHTMLXML(t *testing.T) {
params, err := ParsePayload([]byte(`<html><body>&lt;schc&gt;&lt;resp_code&gt;200&lt;/resp_code&gt;&lt;result_code&gt;0&lt;/result_code&gt;&lt;third_order_id&gt;PAY1&lt;/third_order_id&gt;&lt;schc_order_id&gt;SC1&lt;/schc_order_id&gt;&lt;jspay_url&gt;https://pay.example/sc1?mid=1&amp;pu=2&lt;/jspay_url&gt;&lt;/schc&gt;</body></html>`))
if err != nil {
t.Fatalf("ParsePayload() error = %v", err)
}
if params["jspay_url"] != "https://pay.example/sc1?mid=1&pu=2" {
t.Fatalf("jspay_url = %q, want query decoded", params["jspay_url"])
}
}
func TestParsePayloadAcceptsJSONStringXML(t *testing.T) {
xmlText := `<?xml version="1.0" encoding="utf-16"?><schc xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"><resp_code>200</resp_code><merchant_id>5169118450</merchant_id><sign>00EFB11258D694634F727A8FCCF92290</sign><cost_time>4</cost_time><sign_type>MD5</sign_type><third_order_id>PAY1</third_order_id><jspay_url>https://pay.example/sc1?mid=1&amp;pu=2</jspay_url><result_code>0</result_code><schc_order_id>SC1</schc_order_id></schc>`
body, err := json.Marshal(xmlText)
if err != nil {
t.Fatalf("json marshal xml text: %v", err)
}
params, err := ParsePayload(body)
if err != nil {
t.Fatalf("ParsePayload() error = %v", err)
}
if params["provider_order_id"] != "SC1" || params["jspay_url"] != "https://pay.example/sc1?mid=1&pu=2" {
t.Fatalf("ParsePayload() = %#v, want xml string decoded", params)
}
}
func TestParsePayloadTrimsBOMBeforeXML(t *testing.T) {
params, err := ParsePayload([]byte("\xef\xbb\xbf<schc><resp_code>200</resp_code><result_code>0</result_code><third_order_id>PAY1</third_order_id><schc_order_id>SC1</schc_order_id></schc>"))
if err != nil {
t.Fatalf("ParsePayload() error = %v", err)
}
if params["provider_order_id"] != "SC1" {
t.Fatalf("provider_order_id = %q, want SC1", params["provider_order_id"])
}
}
func TestParsePayloadRejectsPlainHTML(t *testing.T) {
if _, err := ParsePayload([]byte(`<html><body>invalid semicolon; separator</body></html>`)); err == nil {
t.Fatal("ParsePayload() error = nil, want unsupported html error")
}
}
func TestVerifyNotifyAcceptsDocumentedAndLegacySignatures(t *testing.T) {
client := NewClient(Config{NotifyKey: "notify-secret"})
params := map[string]string{
"merchant_id": "1234567890",
"third_order_id": "NO1",
"schc_order_id": "SC1",
"amount": "100",
"status": "2",
"sign_type": "MD5",
}
params["sign"] = SignStrings(params, "notify-secret")
if result := client.VerifyNotifyDetail(params); !result.OK {
t.Fatalf("VerifyNotifyDetail().OK = false, got=%s expected=%v", result.Got, result.Expected)
}
params["sign"] = SignStringsUpperMD5(params, "notify-secret")
if result := client.VerifyNotifyDetail(params); !result.OK {
t.Fatalf("VerifyNotifyDetail() legacy upper md5 OK = false, got=%s expected=%v", result.Got, result.Expected)
}
params["amount"] = "101"
if client.VerifyNotify(params) {
t.Fatal("VerifyNotify() = true after amount changed, want false")
}
}
func TestCreatePaymentFetchesTokenOnceAndPostsSignedJSON(t *testing.T) {
resetTokenCacheForTest()
var tokenCount int
var createCount int
var captured map[string]string
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
switch r.URL.Path {
case endpointToken:
tokenCount++
w.Header().Set("Content-Type", "application/json")
_, _ = w.Write([]byte(`{"respCode":"200","data":"token-1"}`))
case endpointSimplePay:
createCount++
if r.Header.Get("Authorization") != "Bearer token-1" {
t.Fatalf("Authorization = %q, want Bearer token-1", r.Header.Get("Authorization"))
}
if err := json.NewDecoder(r.Body).Decode(&captured); err != nil {
t.Fatalf("decode create payment request: %v", err)
}
if captured["sign"] != SignStrings(captured, "secret-key") {
t.Fatalf("sign = %q, want recalculated %q", captured["sign"], SignStrings(captured, "secret-key"))
}
w.Header().Set("Content-Type", "application/xml")
_, _ = w.Write([]byte(`<schc><resp_code>200</resp_code><result_code>0</result_code><third_order_id>PAY1</third_order_id><schc_order_id>SC1</schc_order_id><jspay_url>https://pay.example/sc1</jspay_url></schc>`))
default:
t.Fatalf("unexpected path %s", r.URL.Path)
}
}))
defer server.Close()
client := NewClient(Config{
GatewayURL: server.URL,
MerchantID: "merchant-1",
SecretID: "secret-id",
SecretKey: "secret-key",
NotifyURL: "https://example.com/notify",
})
for i := 0; i < 2; i++ {
resp, err := client.CreatePayment(context.Background(), CreatePaymentRequest{
ThirdOrderID: "PAY1",
AmountCent: 100,
Body: "租号订单",
})
if err != nil {
t.Fatalf("CreatePayment() error = %v", err)
}
if !resp.OK || resp.ProviderOrderID != "SC1" || resp.JSPayURL == "" {
t.Fatalf("CreatePayment() response = %+v", resp)
}
}
if tokenCount != 1 {
t.Fatalf("tokenCount = %d, want 1", tokenCount)
}
if createCount != 2 {
t.Fatalf("createCount = %d, want 2", createCount)
}
if captured["notify_url"] != "https://example.com/notify" {
t.Fatalf("notify_url = %q, want configured notify url", captured["notify_url"])
}
}
func TestUnauthorizedRefreshesTokenOnce(t *testing.T) {
resetTokenCacheForTest()
var tokenCount int
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
switch r.URL.Path {
case endpointToken:
tokenCount++
w.Header().Set("Content-Type", "application/json")
_, _ = w.Write([]byte(`{"respCode":"200","data":"token-` + strconv.Itoa(tokenCount) + `"}`))
case endpointPaymentQuery:
if r.Header.Get("Authorization") == "Bearer token-1" {
w.WriteHeader(http.StatusUnauthorized)
return
}
if r.Header.Get("Authorization") != "Bearer token-2" {
t.Fatalf("Authorization = %q, want Bearer token-2", r.Header.Get("Authorization"))
}
w.Header().Set("Content-Type", "application/xml")
_, _ = w.Write([]byte(`<schc><resp_code>200</resp_code><result_code>0</result_code><third_order_id>PAY1</third_order_id><schc_order_id>SC1</schc_order_id><status>2</status></schc>`))
default:
t.Fatalf("unexpected path %s", r.URL.Path)
}
}))
defer server.Close()
client := NewClient(Config{
GatewayURL: server.URL,
MerchantID: "merchant-1",
SecretID: "secret-id",
SecretKey: "secret-key",
})
resp, err := client.QueryPayment(context.Background(), "PAY1", "")
if err != nil {
t.Fatalf("QueryPayment() error = %v", err)
}
if !resp.OK || resp.Status != "paid" || resp.ProviderOrderID != "SC1" {
t.Fatalf("QueryPayment() response = %+v", resp)
}
if tokenCount != 2 {
t.Fatalf("tokenCount = %d, want 2", tokenCount)
}
}
func resetTokenCacheForTest() {
tokenCache.Lock()
tokenCache.items = map[string]tokenEntry{}
tokenCache.Unlock()
}
@@ -0,0 +1,69 @@
package push
import (
"context"
"fmt"
"io"
"net/http"
"net/url"
"strings"
"time"
)
const defaultBarkServer = "https://api.day.app"
// BarkConfig 是 iOS Bark 推送的配置。
type BarkConfig struct {
DeviceKey string
Server string // 可选,默认 https://api.day.app
}
// BarkProvider 实现了通过 Bark 发送 iOS 推送。
type BarkProvider struct {
deviceKey string
server string
client *http.Client
}
// NewBarkProvider 创建 Bark 推送 Provider。
// DeviceKey 为空时返回 ErrProviderConfigInvalid。
func NewBarkProvider(cfg BarkConfig) (*BarkProvider, error) {
if strings.TrimSpace(cfg.DeviceKey) == "" {
return nil, ErrProviderConfigInvalid
}
server := strings.TrimSpace(cfg.Server)
if server == "" {
server = defaultBarkServer
}
server = strings.TrimRight(server, "/")
return &BarkProvider{
deviceKey: strings.TrimSpace(cfg.DeviceKey),
server: server,
client: &http.Client{Timeout: 10 * time.Second},
}, nil
}
func (p *BarkProvider) Name() string { return "bark" }
func (p *BarkProvider) Send(ctx context.Context, msg Message) error {
title := url.PathEscape(msg.Title)
body := url.PathEscape(msg.Content)
reqURL := fmt.Sprintf("%s/%s/%s/%s", p.server, p.deviceKey, title, body)
req, err := http.NewRequestWithContext(ctx, http.MethodPost, reqURL, nil)
if err != nil {
return fmt.Errorf("bark: create request: %w", err)
}
resp, err := p.client.Do(req)
if err != nil {
return fmt.Errorf("bark: send failed: %w", err)
}
defer resp.Body.Close()
if resp.StatusCode >= 400 {
bodyBytes, _ := io.ReadAll(resp.Body)
return fmt.Errorf("bark: http %d: %s", resp.StatusCode, string(bodyBytes))
}
return nil
}
@@ -0,0 +1,12 @@
package push
import "context"
// NoopProvider 是一个空实现,未配置任何推送渠道时使用。
type NoopProvider struct{}
func NewNoopProvider() *NoopProvider { return &NoopProvider{} }
func (p *NoopProvider) Name() string { return "noop" }
func (p *NoopProvider) Send(_ context.Context, _ Message) error { return nil }
@@ -0,0 +1,23 @@
package push
import (
"context"
"errors"
)
var ErrProviderConfigInvalid = errors.New("push provider config invalid")
// Message 描述一条待发送的推送消息。
type Message struct {
Title string
Content string
}
// Provider 是站外推送渠道的统一接口。
// 实现方负责具体的 HTTP 调用(Bark、WPush 等)。
type Provider interface {
// Name 返回渠道标识,用于日志。
Name() string
// Send 发送一条推送消息。失败时返回 error。
Send(ctx context.Context, msg Message) error
}
@@ -0,0 +1,73 @@
package push
import (
"context"
"encoding/json"
"fmt"
"io"
"net/http"
"net/url"
"strings"
"time"
)
const wpushAPIURL = "https://api.wpush.cn/api/v1/send"
// WPushConfig 是 WPush 推送的配置。
type WPushConfig struct {
APIKey string
}
// WPushProvider 实现了通过 WPush 发送推送。
// 支持微信公众号、飞书、钉钉、企业微信等多种渠道,取决于用户在 WPush 侧的配置。
type WPushProvider struct {
apiKey string
client *http.Client
}
// NewWPushProvider 创建 WPush 推送 Provider。
// APIKey 为空时返回 ErrProviderConfigInvalid。
func NewWPushProvider(cfg WPushConfig) (*WPushProvider, error) {
if strings.TrimSpace(cfg.APIKey) == "" {
return nil, ErrProviderConfigInvalid
}
return &WPushProvider{
apiKey: strings.TrimSpace(cfg.APIKey),
client: &http.Client{Timeout: 10 * time.Second},
}, nil
}
func (p *WPushProvider) Name() string { return "wpush" }
func (p *WPushProvider) Send(ctx context.Context, msg Message) error {
form := url.Values{}
form.Set("apikey", p.apiKey)
form.Set("title", msg.Title)
form.Set("content", msg.Content)
req, err := http.NewRequestWithContext(ctx, http.MethodPost, wpushAPIURL, strings.NewReader(form.Encode()))
if err != nil {
return fmt.Errorf("wpush: create request: %w", err)
}
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
resp, err := p.client.Do(req)
if err != nil {
return fmt.Errorf("wpush: send failed: %w", err)
}
defer resp.Body.Close()
bodyBytes, _ := io.ReadAll(resp.Body)
var result struct {
Code int `json:"code"`
Message string `json:"message"`
}
if err := json.Unmarshal(bodyBytes, &result); err != nil {
return fmt.Errorf("wpush: parse response: %w (body: %s)", err, string(bodyBytes))
}
if result.Code != 0 {
return fmt.Errorf("wpush: api error code=%d: %s", result.Code, result.Message)
}
return nil
}
+132
View File
@@ -0,0 +1,132 @@
package sms
import (
"context"
"encoding/json"
"fmt"
"strings"
openapi "github.com/alibabacloud-go/darabonba-openapi/v2/utils"
dysms "github.com/alibabacloud-go/dysmsapi-20170525/v5/client"
"github.com/alibabacloud-go/tea/dara"
"go.uber.org/zap"
)
type AliyunConfig struct {
AccessKeyID string
AccessKeySecret string
Endpoint string
SignName string
LoginTemplateCode string
}
type AliyunProvider struct {
client *dysms.Client
signName string
loginTemplateCode string
log *zap.Logger
}
func NewAliyunProvider(cfg AliyunConfig, log *zap.Logger) (*AliyunProvider, error) {
cfg.Endpoint = strings.TrimSpace(cfg.Endpoint)
if cfg.Endpoint == "" {
cfg.Endpoint = "dysmsapi.aliyuncs.com"
}
if strings.TrimSpace(cfg.AccessKeyID) == "" ||
strings.TrimSpace(cfg.AccessKeySecret) == "" ||
strings.TrimSpace(cfg.SignName) == "" ||
strings.TrimSpace(cfg.LoginTemplateCode) == "" {
return nil, ErrProviderConfigInvalid
}
client, err := dysms.NewClient(&openapi.Config{
AccessKeyId: dara.String(strings.TrimSpace(cfg.AccessKeyID)),
AccessKeySecret: dara.String(strings.TrimSpace(cfg.AccessKeySecret)),
Endpoint: dara.String(cfg.Endpoint),
})
if err != nil {
return nil, err
}
return &AliyunProvider{
client: client,
signName: strings.TrimSpace(cfg.SignName),
loginTemplateCode: strings.TrimSpace(cfg.LoginTemplateCode),
log: log,
}, nil
}
func (p *AliyunProvider) SendLoginCode(ctx context.Context, phone string, code string) error {
return p.SendTemplate(ctx, TemplateRequest{
Phone: phone,
TemplateCode: p.loginTemplateCode,
Params: map[string]string{"code": code},
})
}
// SendTemplate 发送已报备的模板短信。req.SignName 为空时回退到 Provider 默认签名。
// 模板无变量时按阿里云要求传空 JSON,避免拼接文案导致模板不匹配。
func (p *AliyunProvider) SendTemplate(ctx context.Context, req TemplateRequest) error {
phone := strings.TrimSpace(req.Phone)
if phone == "" {
return ErrProviderConfigInvalid
}
signName := strings.TrimSpace(req.SignName)
if signName == "" {
signName = p.signName
}
templateCode := strings.TrimSpace(req.TemplateCode)
if templateCode == "" {
return ErrProviderConfigInvalid
}
params := "{}"
if len(req.Params) > 0 {
raw, err := json.Marshal(req.Params)
if err != nil {
return err
}
params = string(raw)
}
apiReq := &dysms.SendSmsRequest{}
apiReq.SetPhoneNumbers(phone)
apiReq.SetSignName(signName)
apiReq.SetTemplateCode(templateCode)
apiReq.SetTemplateParam(params)
resp, err := p.client.SendSmsWithContext(ctx, apiReq, &dara.RuntimeOptions{})
if err != nil {
return fmt.Errorf("aliyun sms send failed: %w", err)
}
if resp == nil || resp.Body == nil {
return fmt.Errorf("aliyun sms empty response")
}
resultCode := dara.StringValue(resp.Body.Code)
if resultCode != "OK" {
resultMessage := dara.StringValue(resp.Body.Message)
providerErr := &ProviderError{Code: resultCode, Message: resultMessage}
if resultCode == "isv.BUSINESS_LIMIT_CONTROL" {
providerErr.Err = ErrProviderRateLimited
}
return providerErr
}
if p.log != nil {
p.log.Debug(
"短信发送成功",
zap.String("phone", maskPhone(phone)),
zap.String("template_code", templateCode),
zap.String("provider_request_id", dara.StringValue(resp.Body.RequestId)),
)
}
return nil
}
func maskPhone(phone string) string {
if len(phone) < 7 {
return phone
}
return phone[:3] + "****" + phone[len(phone)-4:]
}
+39
View File
@@ -0,0 +1,39 @@
package sms
import (
"context"
"go.uber.org/zap"
)
type MockProvider struct {
log *zap.Logger
}
func NewMockProvider(log *zap.Logger) *MockProvider {
return &MockProvider{log: log}
}
func (p *MockProvider) SendLoginCode(ctx context.Context, phone string, code string) error {
if err := ctx.Err(); err != nil {
return err
}
if p.log != nil {
p.log.Info("本地短信验证码", zap.String("phone", maskPhone(phone)), zap.String("code", code))
}
return nil
}
func (p *MockProvider) SendTemplate(ctx context.Context, req TemplateRequest) error {
if err := ctx.Err(); err != nil {
return err
}
if p.log != nil {
p.log.Info("本地模板短信(未真实发送)",
zap.String("phone", maskPhone(req.Phone)),
zap.String("template_code", req.TemplateCode),
zap.Any("params", req.Params),
)
}
return nil
}
@@ -0,0 +1,51 @@
package sms
import (
"context"
"errors"
"fmt"
)
var (
ErrProviderConfigInvalid = errors.New("sms provider config invalid")
ErrProviderRateLimited = errors.New("sms provider rate limited")
)
// TemplateRequest 描述一条模板短信。SignName 留空时使用 Provider 自身配置的默认签名。
type TemplateRequest struct {
Phone string
SignName string
TemplateCode string
Params map[string]string
}
type Provider interface {
SendLoginCode(ctx context.Context, phone string, code string) error
// SendTemplate 发送模板短信,用于登录验证码以外的业务节点触达。
// 阿里云要求模板必须提前报备审核,因此调用方只传模板 CODE 与变量,不拼接文案。
SendTemplate(ctx context.Context, req TemplateRequest) error
}
type ProviderError struct {
Code string
Message string
Err error
}
func (e *ProviderError) Error() string {
if e.Message != "" {
return fmt.Sprintf("sms provider rejected: %s: %s", e.Code, e.Message)
}
if e.Code != "" {
return fmt.Sprintf("sms provider rejected: %s", e.Code)
}
return "sms provider rejected"
}
func (e *ProviderError) Unwrap() error {
return e.Err
}
func IsProviderRateLimited(err error) bool {
return errors.Is(err, ErrProviderRateLimited)
}
@@ -0,0 +1,29 @@
package sms
import (
"errors"
"testing"
)
func TestIsProviderRateLimited(t *testing.T) {
err := &ProviderError{
Code: "isv.BUSINESS_LIMIT_CONTROL",
Message: "触发小时级流控Permits:5",
Err: ErrProviderRateLimited,
}
if !IsProviderRateLimited(err) {
t.Fatalf("expected provider rate limit error")
}
if !errors.Is(err, ErrProviderRateLimited) {
t.Fatalf("expected errors.Is to match provider rate limit")
}
}
func TestProviderErrorMessage(t *testing.T) {
err := &ProviderError{Code: "isv.INVALID_PARAMETERS", Message: "参数错误"}
if got := err.Error(); got != "sms provider rejected: isv.INVALID_PARAMETERS: 参数错误" {
t.Fatalf("unexpected error message: %s", got)
}
}
@@ -0,0 +1,25 @@
package sms
import "context"
type UnavailableProvider struct {
err error
}
func NewUnavailableProvider(err error) *UnavailableProvider {
return &UnavailableProvider{err: err}
}
func (p *UnavailableProvider) SendLoginCode(ctx context.Context, phone string, code string) error {
if err := ctx.Err(); err != nil {
return err
}
if p.err != nil {
return p.err
}
return ErrProviderConfigInvalid
}
func (p *UnavailableProvider) SendTemplate(ctx context.Context, req TemplateRequest) error {
return p.SendLoginCode(ctx, req.Phone, "")
}