diff --git a/example_test.go b/example_test.go new file mode 100644 index 0000000..210f1eb --- /dev/null +++ b/example_test.go @@ -0,0 +1,105 @@ +package xyshanghai + +import ( + "context" + "encoding/hex" + "encoding/json" + "testing" + "time" +) + +// 测试用的密钥和盐值(实际使用时需替换为双方约定的值) +var ( + testSM4Key, _ = hex.DecodeString("0123456789abcdef0123456789abcdef") // 16字节 + testSM3Salt = []byte("test-salt") +) + +func TestCreateOrder(t *testing.T) { + apiKey := NewAPIKey(testSM4Key, testSM3Salt) + client := NewClient(apiKey, WithBaseURL("https://api.example.com"), WithTimeout(10*time.Second)) + + req := &CreateOrderRequest{ + ActCode: "ACT001", + GoodsCode: "123456", + ActOrderNum: "00001", + Account: "19912345678", + CallbackURL: "https://xxx/notice", + } + + resp, err := client.CreateOrder(context.Background(), req) + if err != nil { + t.Logf("CreateOrder error: %v", err) + // 实际测试中可能因为网络原因失败,这里仅验证逻辑 + return + } + t.Logf("CreateOrder response: %+v", resp) +} + +func TestQueryOrder(t *testing.T) { + apiKey := NewAPIKey(testSM4Key, testSM3Salt) + client := NewClient(apiKey, WithBaseURL("https://api.example.com")) + + req := &QueryOrderRequest{ + ActCode: "FBG6vdYqGE4mGX7EH/woEg==", + OrderNo: "HM1757046717684000102707339840b23222", + } + + resp, err := client.QueryOrder(context.Background(), req) + if err != nil { + t.Logf("QueryOrder error: %v", err) + return + } + t.Logf("QueryOrder response: %+v", resp) +} + +func TestRechargeOrder(t *testing.T) { + apiKey := NewAPIKey(testSM4Key, testSM3Salt) + client := NewClient(apiKey, WithBaseURL("https://api.example.com")) + + req := &RechargeOrderRequest{ + ActCode: "FBG6vdYqGE4mGX7EH/woEg==", + GoodsCode: "0001", + ActOrderNum: "0001", + OpenID: "0001", + AppID: "00001", + } + + resp, err := client.RechargeOrder(context.Background(), req) + if err != nil { + t.Logf("RechargeOrder error: %v", err) + return + } + t.Logf("RechargeOrder response: %+v", resp) +} + +func TestParseCallbackRequest(t *testing.T) { + // 模拟回调请求的构造和解析 + apiKey := NewAPIKey(testSM4Key, testSM3Salt) + client := NewClient(apiKey) + + // 构造回调业务数据 + callbackReq := &CallbackRequest{ + OrderNo: "HM202509291010001", + ActOrderNum: "XY2025092910100001", + Status: 3, + Account: "19912345678", + } + + // 加密 + plaintext, _ := json.Marshal(callbackReq) + encryptedData, _ := SM4Encrypt(apiKey.SM4Key, plaintext) + timestamp := "1700000000000" + sign := SM3Sign(apiKey.SM3Salt, timestamp+encryptedData) + + // 构造HTTP请求(简化,实际测试需使用httptest) + // 这里仅验证加密解密和签名逻辑 + t.Logf("Encrypted data: %s", encryptedData) + t.Logf("Sign: %s", sign) + + // 验证解密 + decrypted, err := SM4Decrypt(apiKey.SM4Key, encryptedData) + if err != nil { + t.Fatalf("decrypt error: %v", err) + } + t.Logf("Decrypted: %s", string(decrypted)) +} \ No newline at end of file