修复拉卡拉支付时间偏差

This commit is contained in:
yml2213
2026-06-07 20:42:57 +08:00
parent 44747e7bae
commit 954c3d6be3
10 changed files with 169 additions and 5 deletions
@@ -19,6 +19,8 @@ import (
"strconv"
"strings"
"time"
"hfb_sys/backend/internal/timeutil"
)
var (
@@ -174,11 +176,12 @@ func (c *Client) CreatePayment(ctx context.Context, req CreatePaymentRequest) (*
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": time.Now().Add(time.Duration(expireMinutes) * time.Minute).Format("20060102150405"),
"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,
@@ -364,7 +367,7 @@ func ParsePayload(body []byte) (map[string]string, error) {
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": time.Now().Format("20060102150405"),
"req_time": timeutil.ShanghaiNow().Format("20060102150405"),
"version": "3.0",
"req_data": reqData,
})
@@ -11,6 +11,9 @@ import (
"net/http/httptest"
"strings"
"testing"
"time"
"hfb_sys/backend/internal/timeutil"
)
func TestVerifyNotifyDetail(t *testing.T) {
@@ -90,6 +93,41 @@ func TestCreatePaymentSetsCounterParamWhenPayModeConfigured(t *testing.T) {
}
}
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 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)