feat: add online payment management and checkout
Co-Authored-By: Craft Agent <agents-noreply@craft.do>
This commit is contained in:
250
backend/internal/payments/protocol_test.go
Normal file
250
backend/internal/payments/protocol_test.go
Normal file
@@ -0,0 +1,250 @@
|
||||
package payments
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/aes"
|
||||
"crypto/cipher"
|
||||
"crypto/rand"
|
||||
"crypto/rsa"
|
||||
"encoding/base64"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"net/url"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func testKey(t *testing.T) *rsa.PrivateKey {
|
||||
t.Helper()
|
||||
k, e := rsa.GenerateKey(rand.Reader, 2048)
|
||||
if e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
return k
|
||||
}
|
||||
func TestAlipaySignedResponse(t *testing.T) {
|
||||
k := testKey(t)
|
||||
for _, mode := range []string{"valid", "tamper", "unsigned"} {
|
||||
t.Run(mode, func(t *testing.T) {
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
r.ParseForm()
|
||||
if r.PostForm.Get("notify_url") != "https://example.com/notify" {
|
||||
t.Error("notify_url missing")
|
||||
}
|
||||
payload := `{"code":"10000","qr_code":"https://qr.example","out_trade_no":"order"}`
|
||||
sig, _ := signRSA(k, payload)
|
||||
if mode == "tamper" {
|
||||
payload = strings.ReplaceAll(payload, "qr.example", "evil.example")
|
||||
}
|
||||
if mode == "unsigned" {
|
||||
sig = ""
|
||||
}
|
||||
fmt.Fprintf(w, `{"alipay_trade_precreate_response":%s,"sign":%q}`, payload, sig)
|
||||
}))
|
||||
defer srv.Close()
|
||||
a := alipay{priv: k, alipayPub: &k.PublicKey, client: srv.Client(), endpoint: srv.URL, notify: "https://example.com/notify"}
|
||||
_, e := a.Create(context.Background(), "order", 150, "title")
|
||||
if (e == nil) != (mode == "valid") {
|
||||
t.Fatalf("unexpected error %v", e)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
func TestAlipayNotification(t *testing.T) {
|
||||
k := testKey(t)
|
||||
a := alipay{app: "app", seller: "seller", alipayPub: &k.PublicKey}
|
||||
for _, mode := range []string{"valid", "tamper", "identity", "duplicate"} {
|
||||
t.Run(mode, func(t *testing.T) {
|
||||
f := url.Values{"app_id": {"app"}, "seller_id": {"seller"}, "notify_id": {"evt"}, "out_trade_no": {"order"}, "trade_no": {"trade"}, "trade_status": {"TRADE_SUCCESS"}, "total_amount": {"1.5"}}
|
||||
if mode == "identity" {
|
||||
f.Set("seller_id", "other")
|
||||
}
|
||||
sig, _ := signRSA(k, canonicalValues(f, ""))
|
||||
f.Set("sign_type", "RSA2")
|
||||
f.Set("sign", sig)
|
||||
if mode == "tamper" {
|
||||
f.Set("total_amount", "9.00")
|
||||
}
|
||||
if mode == "duplicate" {
|
||||
f.Add("total_amount", "1.5")
|
||||
}
|
||||
r := httptest.NewRequest("POST", "https://example.com", strings.NewReader(f.Encode()))
|
||||
r.Header.Set("Content-Type", "application/x-www-form-urlencoded")
|
||||
n, e := a.Verify(r)
|
||||
if (e == nil) != (mode == "valid") {
|
||||
t.Fatalf("unexpected error %v", e)
|
||||
}
|
||||
if e == nil && (!n.Paid || n.AmountCents != 150) {
|
||||
t.Fatal(n)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
func TestWechatSignedQuery(t *testing.T) {
|
||||
k := testKey(t)
|
||||
for _, mode := range []string{"valid", "public", "unknown", "tamper", "unsigned", "identity"} {
|
||||
t.Run(mode, func(t *testing.T) {
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
payload := `{"mchid":"merchant","appid":"app","out_trade_no":"order","trade_state":"NOTPAY","amount":{"total":150,"currency":"CNY"}}`
|
||||
if mode == "identity" {
|
||||
payload = strings.ReplaceAll(payload, "merchant", "other")
|
||||
}
|
||||
stamp := fmt.Sprint(time.Now().Unix())
|
||||
sig, _ := signRSA(k, stamp+"\nnonce\n"+payload+"\n")
|
||||
w.Header().Set("Wechatpay-Timestamp", stamp)
|
||||
w.Header().Set("Wechatpay-Nonce", "nonce")
|
||||
w.Header().Set("Wechatpay-Serial", "platform")
|
||||
if mode == "public" || mode == "unknown" {
|
||||
if r.Header.Get("Wechatpay-Serial") != "PUB_KEY_ID_test" || !strings.Contains(r.Header.Get("Authorization"), `serial_no="merchant-cert"`) {
|
||||
t.Error("incorrect merchant certificate or public key request header")
|
||||
}
|
||||
w.Header().Set("Wechatpay-Serial", "PUB_KEY_ID_test")
|
||||
if mode == "unknown" {
|
||||
w.Header().Set("Wechatpay-Serial", "unknown")
|
||||
}
|
||||
}
|
||||
if mode != "unsigned" {
|
||||
w.Header().Set("Wechatpay-Signature", sig)
|
||||
}
|
||||
if mode == "tamper" {
|
||||
payload = strings.ReplaceAll(payload, "150", "999")
|
||||
}
|
||||
fmt.Fprint(w, payload)
|
||||
}))
|
||||
defer srv.Close()
|
||||
w := wechat{mchid: "merchant", appid: "app", serial: "merchant-cert", platformSerial: "platform", priv: k, platform: &k.PublicKey, client: srv.Client(), endpoint: srv.URL}
|
||||
if mode == "public" || mode == "unknown" {
|
||||
w.publicKeyID = "PUB_KEY_ID_test"
|
||||
w.verificationKeys = map[string]*rsa.PublicKey{"PUB_KEY_ID_test": &k.PublicKey}
|
||||
}
|
||||
n, e := w.Query(context.Background(), "order")
|
||||
if (e == nil) != (mode == "valid" || mode == "public") {
|
||||
t.Fatalf("unexpected error %v", e)
|
||||
}
|
||||
if e == nil && n.Paid {
|
||||
t.Fatal("NOTPAY marked paid")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
func TestWechatNotification(t *testing.T) {
|
||||
k := testKey(t)
|
||||
key := "01234567890123456789012345678901"
|
||||
public := testKey(t)
|
||||
w := wechat{mchid: "merchant", appid: "app", platformSerial: "platform", platform: &k.PublicKey, key: key, verificationKeys: map[string]*rsa.PublicKey{"platform": &k.PublicKey, "PUB_KEY_ID_test": &public.PublicKey}}
|
||||
for _, mode := range []string{"valid", "public", "unknown", "wrong-key", "tamper", "identity", "appid", "decrypt", "expired"} {
|
||||
t.Run(mode, func(t *testing.T) {
|
||||
plain := `{"mchid":"merchant","appid":"app","out_trade_no":"order","transaction_id":"trade","trade_state":"SUCCESS","amount":{"total":150,"currency":"CNY"}}`
|
||||
if mode == "identity" {
|
||||
plain = strings.ReplaceAll(plain, "merchant", "other")
|
||||
}
|
||||
if mode == "appid" {
|
||||
plain = strings.ReplaceAll(plain, `"appid":"app"`, `"appid":"other"`)
|
||||
}
|
||||
block, _ := aes.NewCipher([]byte(key))
|
||||
g, _ := cipher.NewGCM(block)
|
||||
ct := g.Seal(nil, []byte("123456789012"), []byte(plain), []byte("ad"))
|
||||
if mode == "decrypt" {
|
||||
ct[0] ^= 1
|
||||
}
|
||||
obj := map[string]any{"id": "evt", "event_type": "TRANSACTION.SUCCESS", "resource": map[string]string{"algorithm": "AEAD_AES_256_GCM", "nonce": "123456789012", "associated_data": "ad", "ciphertext": base64.StdEncoding.EncodeToString(ct)}}
|
||||
body, _ := json.Marshal(obj)
|
||||
stamp := fmt.Sprint(time.Now().Unix())
|
||||
if mode == "expired" {
|
||||
stamp = "1"
|
||||
}
|
||||
signer := k
|
||||
if mode == "public" {
|
||||
signer = public
|
||||
}
|
||||
sig, _ := signRSA(signer, stamp+"\nnonce\n"+string(body)+"\n")
|
||||
if mode == "tamper" {
|
||||
body = append(body, ' ')
|
||||
}
|
||||
r := httptest.NewRequest("POST", "https://example.com", strings.NewReader(string(body)))
|
||||
r.Header.Set("Wechatpay-Timestamp", stamp)
|
||||
r.Header.Set("Wechatpay-Nonce", "nonce")
|
||||
r.Header.Set("Wechatpay-Serial", "platform")
|
||||
if mode == "public" || mode == "wrong-key" {
|
||||
r.Header.Set("Wechatpay-Serial", "PUB_KEY_ID_test")
|
||||
}
|
||||
if mode == "unknown" {
|
||||
r.Header.Set("Wechatpay-Serial", "unknown")
|
||||
}
|
||||
r.Header.Set("Wechatpay-Signature", sig)
|
||||
n, e := w.Verify(r)
|
||||
if (e == nil) != (mode == "valid" || mode == "public") {
|
||||
t.Fatalf("unexpected error %v", e)
|
||||
}
|
||||
if e == nil && (!n.Paid || n.AmountCents != 150) {
|
||||
t.Fatal(n)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
func TestInvalidConfig(t *testing.T) {
|
||||
for _, k := range []string{"ALIPAY_APP_ID", "ALIPAY_PRIVATE_KEY", "WECHAT_MCH_ID", "WECHAT_PRIVATE_KEY"} {
|
||||
t.Setenv(k, "")
|
||||
}
|
||||
m, e := LoadFromEnv()
|
||||
if e != nil || len(m) != 0 {
|
||||
t.Fatal(m, e)
|
||||
}
|
||||
t.Setenv("ALIPAY_APP_ID", "configured")
|
||||
if _, e = LoadFromEnv(); e == nil {
|
||||
t.Fatal("incomplete config accepted")
|
||||
}
|
||||
}
|
||||
|
||||
func TestAlreadyClosedOrders(t *testing.T) {
|
||||
k := testKey(t)
|
||||
t.Run("alipay", func(t *testing.T) {
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
r.ParseForm()
|
||||
if r.Form.Get("method") != "alipay.trade.query" {
|
||||
t.Error("unexpected close request")
|
||||
}
|
||||
payload := `{"code":"10000","out_trade_no":"order","trade_status":"TRADE_CLOSED"}`
|
||||
sig, _ := signRSA(k, payload)
|
||||
fmt.Fprintf(w, `{"alipay_trade_query_response":%s,"sign":%q}`, payload, sig)
|
||||
}))
|
||||
defer srv.Close()
|
||||
a := alipay{priv: k, alipayPub: &k.PublicKey, client: srv.Client(), endpoint: srv.URL}
|
||||
if e := a.Close(context.Background(), "order"); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
})
|
||||
t.Run("wechat", func(t *testing.T) {
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Method != "GET" {
|
||||
t.Error("unexpected close request")
|
||||
}
|
||||
payload := `{"mchid":"merchant","out_trade_no":"order","trade_state":"CLOSED"}`
|
||||
stamp := fmt.Sprint(time.Now().Unix())
|
||||
sig, _ := signRSA(k, stamp+"\nnonce\n"+payload+"\n")
|
||||
w.Header().Set("Wechatpay-Timestamp", stamp)
|
||||
w.Header().Set("Wechatpay-Nonce", "nonce")
|
||||
w.Header().Set("Wechatpay-Serial", "platform")
|
||||
w.Header().Set("Wechatpay-Signature", sig)
|
||||
fmt.Fprint(w, payload)
|
||||
}))
|
||||
defer srv.Close()
|
||||
w := wechat{mchid: "merchant", priv: k, platform: &k.PublicKey, platformSerial: "platform", endpoint: srv.URL, client: srv.Client()}
|
||||
if e := w.Close(context.Background(), "order"); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
})
|
||||
}
|
||||
func TestAmountRejectsMalformedAndOverflow(t *testing.T) {
|
||||
for _, s := range []string{"1x.00", "+1.00", "1.-1", "9223372036854775807.00", "1.001", "NaN", "1e2.00"} {
|
||||
if _, e := parseAlipayAmount(s); e == nil {
|
||||
t.Fatalf("accepted %q", s)
|
||||
}
|
||||
}
|
||||
if _, e := cents(float64(150)); e == nil {
|
||||
t.Fatal("accepted floating amount")
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user