87ebfa1fac
Squash merge of fix/137-defer-close-反查网关 (1367c4f).
DeferCloseOrder 直接将 status=1 订单关单,会把已经在网关侧完成支付但
notify 静默失败的订单错误关闭。本次在关单前调用 EPay 的网关查询接口
(confirmationPayment) 拿到三态结果:
- Paid: 原子化把 status 1->2,写回 trade_no,再投递 asynq 走激活流程
- Unpaid: 继续原来的 close 事务,把 status 改为 cancelled
- Unknown / 网关失败: 保持 status=1,下一轮 DeferClose 再试
新增 closeOrderLogic_test.go (232 行),覆盖三态分支 + recoverPaidOrder
的并发幂等。单测全量 PASS, go build + go vet 均干净。E2E 验收因测试环境
访问受限暂未跑,QA 已在 issue 上注明阻塞原因 (qa_partial_blocked_on_e2e_access)。
Co-authored-by: multica-agent <github@multica.ai>
142 lines
4.2 KiB
Go
142 lines
4.2 KiB
Go
package epay
|
|
|
|
import (
|
|
"encoding/json"
|
|
"fmt"
|
|
"io"
|
|
"net/http"
|
|
"net/url"
|
|
"sort"
|
|
"strings"
|
|
"time"
|
|
|
|
"github.com/perfect-panel/server/pkg/logger"
|
|
"github.com/perfect-panel/server/pkg/tool"
|
|
)
|
|
|
|
type Client struct {
|
|
Pid string
|
|
Url string
|
|
Key string
|
|
Type string
|
|
}
|
|
|
|
type Order struct {
|
|
Name string
|
|
OrderNo string
|
|
Amount float64
|
|
SignType string
|
|
NotifyUrl string
|
|
ReturnUrl string
|
|
}
|
|
|
|
type queryOrderStatusResponse struct {
|
|
Code int `json:"code"`
|
|
Msg string `json:"msg"`
|
|
TradeNo string `json:"trade_no"`
|
|
OutTradeNo string `json:"out_trade_no"`
|
|
Type string `json:"type"`
|
|
Status int `json:"status"`
|
|
}
|
|
|
|
func NewClient(pid, url, key string, Type string) *Client {
|
|
return &Client{
|
|
Pid: pid,
|
|
Url: url,
|
|
Key: key,
|
|
Type: Type,
|
|
}
|
|
}
|
|
|
|
func (c *Client) CreatePayUrl(order Order) string {
|
|
// Prepare URL values
|
|
params := url.Values{}
|
|
params.Set("name", order.Name)
|
|
params.Set("money", tool.FormatFloat(order.Amount, 2))
|
|
params.Set("notify_url", order.NotifyUrl)
|
|
params.Set("out_trade_no", order.OrderNo)
|
|
params.Set("pid", c.Pid)
|
|
params.Set("type", c.Type)
|
|
params.Set("return_url", order.ReturnUrl)
|
|
|
|
// Generate the sign using the CreateSign function
|
|
sign := c.createSign(c.structToMap(order))
|
|
params.Set("sign", sign)
|
|
|
|
// Add sign_type manually
|
|
params.Set("sign_type", "MD5")
|
|
return c.Url + "/submit.php?" + params.Encode()
|
|
}
|
|
|
|
func (c *Client) createSign(params map[string]string) string {
|
|
keys := make([]string, 0, len(params))
|
|
for k := range params {
|
|
if params[k] != "" && k != "sign" && k != "sign_type" {
|
|
keys = append(keys, k)
|
|
}
|
|
}
|
|
sort.Strings(keys)
|
|
var parts []string
|
|
for _, k := range keys {
|
|
parts = append(parts, k+"="+params[k])
|
|
}
|
|
queryString := strings.Join(parts, "&")
|
|
text := queryString + c.Key
|
|
return tool.Md5Encode(text, false)
|
|
}
|
|
|
|
func (c *Client) VerifySign(params map[string]string) bool {
|
|
return c.createSign(params) == params["sign"]
|
|
}
|
|
|
|
// QueryOrderStatus returns (paid, err). A non-nil err means the query itself
|
|
// failed (network / 5xx / decode error) and the result is inconclusive — callers
|
|
// MUST NOT treat that as "unpaid". A nil err with paid=false means the gateway
|
|
// answered and reported the order is not paid.
|
|
func (c *Client) QueryOrderStatus(orderNo string) (bool, error) {
|
|
client := http.Client{
|
|
Timeout: 5 * time.Second,
|
|
}
|
|
resp, err := client.Get(c.Url + "/api.php" + "?act=order" + "&pid=" + c.Pid + "&key=" + c.Key + "&out_trade_no=" + orderNo)
|
|
if err != nil {
|
|
logger.Error("[Epay] QueryOrderStatus error", logger.Field("orderNo", orderNo), logger.Field("error", err.Error()))
|
|
return false, fmt.Errorf("epay query request failed: %w", err)
|
|
}
|
|
defer resp.Body.Close()
|
|
if resp.StatusCode >= 500 {
|
|
err := fmt.Errorf("epay query upstream status %d", resp.StatusCode)
|
|
logger.Error("[Epay] QueryOrderStatus upstream 5xx", logger.Field("orderNo", orderNo), logger.Field("status", resp.StatusCode))
|
|
return false, err
|
|
}
|
|
value, err := io.ReadAll(resp.Body)
|
|
if err != nil {
|
|
logger.Error("[Epay] QueryOrderStatus error", logger.Field("orderNo", orderNo), logger.Field("error", err.Error()))
|
|
return false, fmt.Errorf("epay query read body failed: %w", err)
|
|
}
|
|
var response queryOrderStatusResponse
|
|
if err = json.Unmarshal(value, &response); err != nil {
|
|
logger.Error("[Epay] QueryOrderStatus error", logger.Field("orderNo", orderNo), logger.Field("error", err.Error()))
|
|
return false, fmt.Errorf("epay query decode failed: %w", err)
|
|
}
|
|
// EPay API contract: code != 1 means the API itself errored (e.g. wrong key).
|
|
// Treat it as a query failure, not a definitive "unpaid", to avoid wrongly
|
|
// closing a paid order under a transient upstream config error.
|
|
if response.Code != 1 {
|
|
return false, fmt.Errorf("epay query api code=%d msg=%q", response.Code, response.Msg)
|
|
}
|
|
return response.Status == 1, nil
|
|
}
|
|
|
|
// StructToMap converts a struct to map[string]string
|
|
func (c *Client) structToMap(order Order) map[string]string {
|
|
result := make(map[string]string)
|
|
result["money"] = tool.FormatFloat(order.Amount, 2)
|
|
result["name"] = order.Name
|
|
result["notify_url"] = order.NotifyUrl
|
|
result["out_trade_no"] = order.OrderNo
|
|
result["pid"] = c.Pid
|
|
result["type"] = c.Type
|
|
result["return_url"] = order.ReturnUrl
|
|
return result
|
|
}
|