80 lines
2.6 KiB
Go
80 lines
2.6 KiB
Go
package payment
|
|
|
|
import (
|
|
"crypto/aes"
|
|
"crypto/cipher"
|
|
"encoding/base64"
|
|
"encoding/json"
|
|
"net/http"
|
|
"net/http/httptest"
|
|
"strings"
|
|
"testing"
|
|
"time"
|
|
)
|
|
|
|
func TestWechatV3WithoutPlatformCertificateLoadsVerificationKey(t *testing.T) {
|
|
_, merchantPrivatePEM, _ := testRSAKeyPair(t)
|
|
_, _, platformPublicPEM := testRSAKeyPair(t)
|
|
apiV3Key := "01234567890123456789012345678901"
|
|
block, err := aes.NewCipher([]byte(apiV3Key))
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
gcm, err := cipher.NewGCM(block)
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
nonce, associatedData := "0123456789ab", "certificate"
|
|
ciphertext := base64.StdEncoding.EncodeToString(gcm.Seal(nil, []byte(nonce), []byte(platformPublicPEM), []byte(associatedData)))
|
|
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
if r.URL.Path != "/v3/certificates" {
|
|
t.Errorf("unexpected path %q", r.URL.Path)
|
|
}
|
|
w.Header().Set("Content-Type", "application/json")
|
|
_ = json.NewEncoder(w).Encode(map[string]any{"data": []any{map[string]any{
|
|
"serial_no": "platform-serial",
|
|
"effective_time": time.Now().Add(-time.Hour).Format(time.RFC3339),
|
|
"expire_time": time.Now().Add(24 * time.Hour).Format(time.RFC3339),
|
|
"encrypt_certificate": map[string]any{
|
|
"algorithm": "AEAD_AES_256_GCM", "nonce": nonce,
|
|
"associated_data": associatedData, "ciphertext": ciphertext,
|
|
},
|
|
}}})
|
|
}))
|
|
defer server.Close()
|
|
|
|
client, err := newWechatV3Client(map[string]any{
|
|
"merchant_id": "merchant", "serial_no": "merchant-serial",
|
|
"api_v3_key": apiV3Key, "private_key": merchantPrivatePEM,
|
|
"create_url": server.URL,
|
|
}, "create_url")
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if client.WxPublicKeyMap()["platform-serial"] == nil {
|
|
t.Fatal("fetched platform key was not installed for signature verification")
|
|
}
|
|
}
|
|
|
|
func TestWechatV3WithoutPlatformCertificateFetchesFromConfiguredEndpoint(t *testing.T) {
|
|
_, merchantPrivatePEM, _ := testRSAKeyPair(t)
|
|
requestPath := ""
|
|
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
requestPath = r.URL.Path
|
|
w.WriteHeader(http.StatusServiceUnavailable)
|
|
}))
|
|
defer server.Close()
|
|
|
|
_, err := newWechatV3Client(map[string]any{
|
|
"merchant_id": "merchant", "serial_no": "merchant-serial",
|
|
"api_v3_key": "01234567890123456789012345678901",
|
|
"private_key": merchantPrivatePEM, "create_url": server.URL,
|
|
}, "create_url")
|
|
if requestPath != "/v3/certificates" {
|
|
t.Fatalf("certificate request path = %q", requestPath)
|
|
}
|
|
if err == nil || !strings.Contains(err.Error(), "自动获取平台证书失败") {
|
|
t.Fatalf("certificate fetch error = %v", err)
|
|
}
|
|
}
|