feat: add online payment management and checkout
Some checks failed
Check / delivery-static (push) Has been cancelled
Check / api (push) Has been cancelled
Check / web (push) Has been cancelled

Co-Authored-By: Craft Agent <agents-noreply@craft.do>
This commit is contained in:
2026-10-15 09:26:40 +08:00
parent 5353a4a128
commit dc2efcde08
41 changed files with 4855 additions and 21 deletions

View File

@@ -0,0 +1,24 @@
# Payments
Use `NewProvider(channel string, config Config) (Provider, error)` to construct a channel from explicit settings without reading or modifying the process environment. `Config` is `map[string]string`, keyed by the environment variable names below. Supported channel names are `alipay` and `wechat`. `RequiredSettings(channel)` returns a fresh slice of required keys; `ConfigFromEnv(channel)` returns a snapshot of nonempty environment values. Unknown channels are rejected by `NewProvider`.
`LoadFromEnv` remains a compatibility entry point: it builds providers from `ConfigFromEnv` when any setting for that channel is present, rejects partial/invalid configurations, and returns no provider when all its settings are absent. No constructor creates fake credentials or test payments. `NewProvider` makes no network request during validation.
## Alipay
Required: `ALIPAY_APP_ID`, `ALIPAY_SELLER_ID`, `ALIPAY_PRIVATE_KEY`, `ALIPAY_PUBLIC_KEY`, `ALIPAY_NOTIFY_URL`.
`ALIPAY_PRIVATE_KEY` and `ALIPAY_PUBLIC_KEY` accept PEM text or `@path/to/key.pem`. The notification URL must be HTTPS. `ALIPAY_ENDPOINT`, when present, must equal `https://openapi.alipay.com/gateway.do`; arbitrary gateway overrides are rejected.
The provider uses the official Alipay gateway protocol with RSA2 signing, precreate/query/close/refund, strict integer-cent parsing, merchant identity checks, and notification signature verification.
## WeChat Pay API v3
Required base settings: `WECHAT_MCH_ID`, `WECHAT_APP_ID`, `WECHAT_SERIAL_NO`, `WECHAT_PRIVATE_KEY`, `WECHAT_API_V3_KEY`, `WECHAT_NOTIFY_URL`. For new integrations, configure `WECHAT_PUBLIC_KEY_ID` (must start with `PUB_KEY_ID_`) and `WECHAT_PUBLIC_KEY`. During migration, configure `WECHAT_PLATFORM_SERIAL` and `WECHAT_PLATFORM_PUBLIC_KEY` as an additional trusted pair; both pairs may coexist and callbacks select the key by the incoming `Wechatpay-Serial` header. `WECHAT_SERIAL_NO` identifies the merchant API certificate used to sign requests, while `Wechatpay-Serial` identifies the platform verification key requested for responses. Keys accept PEM text or `@path/to/key.pem`; API v3 key is exactly 32 bytes. The notification URL must be HTTPS. `WECHAT_ENDPOINT`, when present, must equal `https://api.mch.weixin.qq.com`; arbitrary gateway overrides are rejected.
The provider uses API v3 Native endpoints and RSA-2048/SHA-256 request/response authentication, AES-256-GCM notification decryption, merchant/app/currency checks, and a five-minute notification timestamp window.
`Refund` requires an integer amount in cents. WeChat queries the original order total before refunding, so partial refunds use the correct total. Callers must provide the original merchant order number and a stable refund number; repeated calls with the same refund number are idempotent at the channel.
Notifications authenticate channel data, but the provider has no access to the order database. The business layer must compare MerchantOrderNo, AmountCents and Currency with the stored order before crediting it. Query event IDs use `query-` plus the channel transaction ID when available, otherwise the merchant order number for unpaid orders. Alipay retries reuse out_trade_no; refund retries reuse out_request_no/out_refund_no. Close returns success for an already closed order after an authenticated status query. Errors never imply a successful payment.
Run `go test ./internal/payments` and `go vet ./internal/payments` from backend. Offline tests use local RSA keys and signed HTTP fixtures; real merchant credentials and channel connectivity are still required for live acceptance.

View File

@@ -0,0 +1,330 @@
package payments
import (
"context"
"crypto"
"crypto/rsa"
"crypto/sha256"
"encoding/base64"
"encoding/json"
"errors"
"fmt"
"math"
"net"
"net/http"
"net/url"
"sort"
"strconv"
"strings"
"time"
)
type alipay struct {
app, seller, notify string
priv *rsa.PrivateKey
alipayPub *rsa.PublicKey
endpoint string
client *http.Client
}
func newAlipayFromEnv() (Provider, error) { return NewProvider("alipay", ConfigFromEnv("alipay")) }
func newAlipay(config Config) (Provider, error) {
app, e := config.required("ALIPAY_APP_ID")
if e != nil {
return nil, e
}
seller, e := config.required("ALIPAY_SELLER_ID")
if e != nil {
return nil, e
}
notify, e := config.required("ALIPAY_NOTIFY_URL")
if e != nil {
return nil, e
}
if e = validateNotifyURL("ALIPAY_NOTIFY_URL", notify); e != nil {
return nil, e
}
pk, e := config.required("ALIPAY_PRIVATE_KEY")
if e != nil {
return nil, e
}
priv, e := privateKey(pk)
if e != nil {
return nil, e
}
pubs, e := config.required("ALIPAY_PUBLIC_KEY")
if e != nil {
return nil, e
}
pub, e := publicKey(pubs)
if e != nil {
return nil, e
}
return &alipay{app: app, seller: seller, notify: notify, priv: priv, alipayPub: pub, endpoint: alipayEndpoint, client: &http.Client{Timeout: 15 * time.Second, Transport: &http.Transport{DialContext: (&net.Dialer{Timeout: 5 * time.Second}).DialContext}}}, nil
}
func (a *alipay) call(ctx context.Context, method string, args map[string]string) (map[string]any, error) {
v := url.Values{"app_id": {a.app}, "method": {method}, "format": {"JSON"}, "charset": {"utf-8"}, "sign_type": {"RSA2"}, "timestamp": {time.Now().Format("2006-01-02 15:04:05")}, "version": {"1.0"}}
if method == "alipay.trade.precreate" {
v.Set("notify_url", a.notify)
}
for k, x := range args {
v.Set(k, x)
}
sig, e := signRSA(a.priv, canonicalValues(v, "sign"))
if e != nil {
return nil, e
}
v.Set("sign", sig)
req, e := http.NewRequestWithContext(ctx, "POST", a.endpoint, strings.NewReader(v.Encode()))
if e != nil {
return nil, e
}
req.Header.Set("Content-Type", "application/x-www-form-urlencoded;charset=utf-8")
resp, e := a.client.Do(req)
if e != nil {
return nil, e
}
defer resp.Body.Close()
raw, e := readLimited(resp.Body)
if e != nil {
return nil, e
}
var envelope map[string]json.RawMessage
if e = json.Unmarshal(raw, &envelope); e != nil {
return nil, e
}
payload := envelope[strings.ReplaceAll(method, ".", "_")+"_response"]
var signature string
if e = json.Unmarshal(envelope["sign"], &signature); e != nil {
return nil, errors.New("missing alipay response signature")
}
if e = verifyRSA(a.alipayPub, string(payload), signature); e != nil {
return nil, e
}
var out map[string]any
if e = json.Unmarshal(raw, &out); e != nil {
return nil, e
}
if resp.StatusCode/100 != 2 {
return nil, fmt.Errorf("alipay HTTP %d", resp.StatusCode)
}
return out, nil
}
func (a *alipay) verifyResponse(r map[string]any) error {
if r == nil {
return errors.New("missing alipay response")
}
return nil
}
func (a *alipay) Create(ctx context.Context, no string, amount int64, title string) (string, error) {
if amount <= 0 {
return "", errors.New("invalid amount")
}
raw, _ := json.Marshal(map[string]any{"out_trade_no": no, "total_amount": fmt.Sprintf("%d.%02d", amount/100, amount%100), "subject": title, "product_code": "FACE_TO_FACE_PAYMENT"})
o, e := a.call(ctx, "alipay.trade.precreate", map[string]string{"biz_content": string(raw)})
if e != nil {
return "", e
}
r, _ := o["alipay_trade_precreate_response"].(map[string]any)
if e = a.verifyResponse(r); e != nil {
return "", e
}
if r["code"] != "10000" {
return "", fmt.Errorf("alipay: %v", r["sub_msg"])
}
q, _ := r["qr_code"].(string)
if q == "" {
return "", errors.New("missing qr_code")
}
return q, nil
}
func (a *alipay) Query(ctx context.Context, no string) (Notification, error) {
raw, _ := json.Marshal(map[string]string{"out_trade_no": no})
o, e := a.call(ctx, "alipay.trade.query", map[string]string{"biz_content": string(raw)})
if e != nil {
return Notification{}, e
}
r, _ := o["alipay_trade_query_response"].(map[string]any)
if e = a.verifyResponse(r); e != nil {
return Notification{}, e
}
if r["code"] != "10000" {
return Notification{}, fmt.Errorf("alipay query: %v", r["sub_msg"])
}
if got, _ := r["out_trade_no"].(string); got != no {
return Notification{}, errors.New("merchant order mismatch")
}
n := Notification{EventID: "query-" + no, MerchantOrderNo: no, Currency: "CNY"}
n.TradeNo, _ = r["trade_no"].(string)
if n.TradeNo != "" {
n.EventID = "query-" + n.TradeNo
}
st, _ := r["trade_status"].(string)
n.Paid = st == "TRADE_SUCCESS" || st == "TRADE_FINISHED"
if v, ok := r["total_amount"].(string); ok {
n.AmountCents, e = parseAlipayAmount(v)
}
if n.Paid && (n.AmountCents <= 0 || n.TradeNo == "") {
return Notification{}, errors.New("incomplete paid query")
}
return n, e
}
func (a *alipay) Close(ctx context.Context, no string) error {
rawQuery, _ := json.Marshal(map[string]string{"out_trade_no": no})
o, e := a.call(ctx, "alipay.trade.query", map[string]string{"biz_content": string(rawQuery)})
if e != nil {
return e
}
r, _ := o["alipay_trade_query_response"].(map[string]any)
if r == nil {
return errors.New("missing close query response")
}
if r["code"] != "10000" {
return fmt.Errorf("alipay close query: %v", r["sub_code"])
}
if r["out_trade_no"] != no {
return errors.New("close identity mismatch")
}
if r["trade_status"] == "TRADE_CLOSED" {
return nil
}
raw, _ := json.Marshal(map[string]string{"out_trade_no": no})
return a.simple(ctx, "alipay.trade.close", map[string]string{"biz_content": string(raw)})
}
func (a *alipay) Refund(ctx context.Context, no, refund string, amount int64) error {
if amount <= 0 {
return errors.New("invalid refund amount")
}
raw, _ := json.Marshal(map[string]any{"out_trade_no": no, "refund_amount": fmt.Sprintf("%d.%02d", amount/100, amount%100), "out_request_no": refund})
return a.simple(ctx, "alipay.trade.refund", map[string]string{"biz_content": string(raw)})
}
func (a *alipay) simple(ctx context.Context, m string, p map[string]string) error {
o, e := a.call(ctx, m, p)
if e != nil {
return e
}
var r map[string]any
for _, x := range o {
if z, ok := x.(map[string]any); ok {
r = z
break
}
}
if e = a.verifyResponse(r); e != nil {
return e
}
if m == "alipay.trade.close" && r["sub_code"] == "ACQ.TRADE_HAS_CLOSE" {
return nil
}
if r != nil && r["code"] != "10000" {
return fmt.Errorf("alipay: %v", r["sub_msg"])
}
return nil
}
func (a *alipay) Verify(req *http.Request) (Notification, error) {
if req == nil {
return Notification{}, errors.New("nil request")
}
if req.URL.RawQuery != "" {
return Notification{}, errors.New("query parameters not allowed")
}
if e := req.ParseForm(); e != nil {
return Notification{}, e
}
if hasDuplicate(req.PostForm) {
return Notification{}, errors.New("duplicate field")
}
f := req.PostForm
if f.Get("app_id") != a.app || f.Get("seller_id") != a.seller || f.Get("sign_type") != "RSA2" {
return Notification{}, errors.New("merchant identity mismatch")
}
sig := f.Get("sign")
if sig == "" {
return Notification{}, errors.New("missing sign")
}
b, e := base64.StdEncoding.DecodeString(sig)
if e != nil {
return Notification{}, e
}
m := url.Values{}
for k, v := range f {
if k != "sign" && k != "sign_type" {
m[k] = v
}
}
h := sha256.Sum256([]byte(canonicalValues(m, "")))
if e = rsa.VerifyPKCS1v15(a.alipayPub, crypto.SHA256, h[:], b); e != nil {
return Notification{}, errors.New("invalid alipay signature")
}
n := Notification{EventID: f.Get("notify_id"), MerchantOrderNo: f.Get("out_trade_no"), TradeNo: f.Get("trade_no"), Currency: "CNY", Paid: f.Get("trade_status") == "TRADE_SUCCESS" || f.Get("trade_status") == "TRADE_FINISHED"}
n.AmountCents, e = parseAlipayAmount(f.Get("total_amount"))
if e == nil && (n.AmountCents <= 0 || n.EventID == "" || n.MerchantOrderNo == "" || n.TradeNo == "") {
return Notification{}, errors.New("incomplete payment notification")
}
if c := f.Get("currency"); c != "" && c != "CNY" {
return Notification{}, errors.New("currency mismatch")
}
return n, e
}
func canonicalValues(v url.Values, skip string) string {
keys := make([]string, 0, len(v))
for k := range v {
if k != skip {
keys = append(keys, k)
}
}
sort.Strings(keys)
p := make([]string, 0, len(keys))
for _, k := range keys {
p = append(p, k+"="+v.Get(k))
}
return strings.Join(p, "&")
}
func canonicalMap(v map[string]string) string {
u := url.Values{}
for k, x := range v {
u.Set(k, x)
}
return canonicalValues(u, "")
}
func hasDuplicate(v url.Values) bool {
for _, x := range v {
if len(x) != 1 {
return true
}
}
return false
}
func parseAlipayAmount(s string) (int64, error) {
p := strings.Split(s, ".")
if len(p) > 2 || p[0] == "" {
return 0, errors.New("invalid amount")
}
frac := "00"
if len(p) == 2 {
if len(p[1]) < 1 || len(p[1]) > 2 {
return 0, errors.New("invalid amount")
}
frac = p[1]
if len(frac) == 1 {
frac += "0"
}
}
for _, part := range []string{p[0], frac} {
for _, r := range part {
if r < '0' || r > '9' {
return 0, errors.New("invalid amount")
}
}
}
y, e := strconv.ParseInt(p[0], 10, 64)
if e != nil {
return 0, e
}
f, _ := strconv.ParseInt(frac, 10, 64)
if y > (math.MaxInt64-f)/100 {
return 0, errors.New("amount overflow")
}
return y*100 + f, nil
}

View File

@@ -0,0 +1,253 @@
package payments
import (
"crypto/x509"
"encoding/pem"
"reflect"
"strings"
"testing"
)
func testConfigs(t *testing.T) map[string]Config {
t.Helper()
merchant := testKey(t)
platform := testKey(t)
private := string(pem.EncodeToMemory(&pem.Block{Type: "PRIVATE KEY", Bytes: mustPKCS8(t, merchant)}))
public := string(pem.EncodeToMemory(&pem.Block{Type: "PUBLIC KEY", Bytes: mustPKIX(t, &platform.PublicKey)}))
return map[string]Config{
"alipay": {
"ALIPAY_APP_ID": "app", "ALIPAY_SELLER_ID": "seller", "ALIPAY_PRIVATE_KEY": private,
"ALIPAY_PUBLIC_KEY": public, "ALIPAY_NOTIFY_URL": "https://merchant.example/alipay",
},
"wechat": {
"WECHAT_MCH_ID": "merchant", "WECHAT_APP_ID": "app", "WECHAT_SERIAL_NO": "merchant-serial",
"WECHAT_PUBLIC_KEY_ID": "PUB_KEY_ID_0000000000000024101100397200000006", "WECHAT_PUBLIC_KEY": public,
"WECHAT_PLATFORM_SERIAL": "platform-serial", "WECHAT_PRIVATE_KEY": private,
"WECHAT_PLATFORM_PUBLIC_KEY": public, "WECHAT_API_V3_KEY": "01234567890123456789012345678901",
"WECHAT_NOTIFY_URL": "https://merchant.example/wechat",
},
}
}
func mustPKCS8(t *testing.T, key any) []byte {
t.Helper()
b, err := x509.MarshalPKCS8PrivateKey(key)
if err != nil {
t.Fatal(err)
}
return b
}
func mustPKIX(t *testing.T, key any) []byte {
t.Helper()
b, err := x509.MarshalPKIXPublicKey(key)
if err != nil {
t.Fatal(err)
}
return b
}
func cloneConfig(c Config) Config {
copy := Config{}
for k, v := range c {
copy[k] = v
}
return copy
}
func TestNewProviderExplicitConfig(t *testing.T) {
for channel, cfg := range testConfigs(t) {
t.Run(channel, func(t *testing.T) {
before := cloneConfig(cfg)
// An invalid process environment must not affect explicit construction.
for _, key := range RequiredSettings(channel) {
t.Setenv(key, "invalid environment value")
}
p, err := NewProvider(channel, cfg)
if err != nil || p == nil {
t.Fatalf("provider: %T, %v", p, err)
}
if !reflect.DeepEqual(cfg, before) {
t.Fatal("constructor modified configuration")
}
switch v := p.(type) {
case *alipay:
if v.endpoint != alipayEndpoint || v.app != cfg["ALIPAY_APP_ID"] {
t.Fatal("incorrect Alipay config")
}
case *wechat:
if v.endpoint != wechatEndpoint || v.publicKeyID != cfg["WECHAT_PUBLIC_KEY_ID"] || v.verificationKey(cfg["WECHAT_PLATFORM_SERIAL"]) == nil {
t.Fatal("incorrect WeChat config")
}
default:
t.Fatalf("unexpected provider %T", p)
}
})
}
}
func TestNewProviderValidation(t *testing.T) {
configs := testConfigs(t)
for channel, cfg := range configs {
t.Run(channel, func(t *testing.T) {
for _, key := range RequiredSettings(channel) {
t.Run("missing_"+key, func(t *testing.T) {
missing := cloneConfig(cfg)
delete(missing, key)
if _, err := NewProvider(channel, missing); err == nil || !strings.Contains(err.Error(), key) {
t.Fatalf("missing %s: %v", key, err)
}
})
t.Run("blank_"+key, func(t *testing.T) {
blank := cloneConfig(cfg)
blank[key] = " \t"
if _, err := NewProvider(channel, blank); err == nil || !strings.Contains(err.Error(), key) {
t.Fatalf("blank %s: %v", key, err)
}
})
}
for _, value := range []string{"http://merchant.example/notify", "javascript:alert(1)", "https://", "https://name:secret@merchant.example/notify", "https://merchant.example/notify#fragment"} {
t.Run("notify_"+value, func(t *testing.T) {
bad := cloneConfig(cfg)
bad[strings.ToUpper(channel)+"_NOTIFY_URL"] = value
if _, err := NewProvider(channel, bad); err == nil {
t.Fatalf("accepted %q", value)
}
})
}
bad := cloneConfig(cfg)
bad[strings.ToUpper(channel)+"_PRIVATE_KEY"] = "invalid PEM"
if _, err := NewProvider(channel, bad); err == nil {
t.Fatal("accepted invalid RSA private key")
}
bad = cloneConfig(cfg)
publicKeyName := "ALIPAY_PUBLIC_KEY"
if channel == "wechat" {
publicKeyName = "WECHAT_PLATFORM_PUBLIC_KEY"
}
bad[publicKeyName] = "invalid PEM"
if _, err := NewProvider(channel, bad); err == nil {
t.Fatal("accepted invalid RSA public key")
}
bad = cloneConfig(cfg)
bad[strings.ToUpper(channel)+"_ENDPOINT"] = "https://attacker.example"
if _, err := NewProvider(channel, bad); err == nil {
t.Fatal("accepted custom gateway")
}
bad[strings.ToUpper(channel)+"_ENDPOINT"] = "http://127.0.0.1:8080"
if _, err := NewProvider(channel, bad); err == nil {
t.Fatal("accepted local gateway")
}
bad[strings.ToUpper(channel)+"_ENDPOINT"] = map[string]string{"alipay": alipayEndpoint, "wechat": wechatEndpoint}[channel]
if _, err := NewProvider(channel, bad); err != nil {
t.Fatalf("rejected official gateway: %v", err)
}
})
}
bad := cloneConfig(configs["wechat"])
bad["WECHAT_API_V3_KEY"] = "short"
if _, err := NewProvider("wechat", bad); err == nil {
t.Fatal("accepted short API v3 key")
}
for _, channel := range []string{"", "ALIPAY", "other"} {
if _, err := NewProvider(channel, nil); err == nil {
t.Fatalf("accepted channel %q", channel)
}
if len(RequiredSettings(channel)) != 0 || len(ConfigFromEnv(channel)) != 0 {
t.Fatalf("unknown channel %q has settings", channel)
}
}
}
func TestConfigFromEnvSnapshot(t *testing.T) {
for channel, cfg := range testConfigs(t) {
t.Run(channel, func(t *testing.T) {
for key, value := range cfg {
t.Setenv(key, value)
}
endpointKey := strings.ToUpper(channel) + "_ENDPOINT"
t.Setenv(endpointKey, "https://custom.example")
first := ConfigFromEnv(channel)
if len(first) != len(cfg)+1 {
t.Fatalf("unexpected snapshot size: %d", len(first))
}
for key, value := range cfg {
if first[key] != strings.TrimSpace(value) {
t.Fatalf("incorrect %s snapshot", key)
}
}
if first[endpointKey] != "https://custom.example" {
t.Fatal("legacy endpoint missing")
}
t.Setenv(endpointKey, "")
for key := range cfg {
t.Setenv(key, "")
}
if len(ConfigFromEnv(channel)) != 0 {
t.Fatal("environment did not clear")
}
if first[endpointKey] != "https://custom.example" {
t.Fatal("snapshot mutated")
}
if _, err := NewProvider(channel, first); err == nil {
t.Fatal("custom endpoint from environment accepted")
}
})
}
}
func TestWechatVerificationPairs(t *testing.T) {
base := testConfigs(t)["wechat"]
for _, mode := range []string{"public-only", "platform-only", "both", "none", "missing-public", "missing-id", "bad-id"} {
t.Run(mode, func(t *testing.T) {
cfg := cloneConfig(base)
switch mode {
case "public-only":
delete(cfg, "WECHAT_PLATFORM_SERIAL")
delete(cfg, "WECHAT_PLATFORM_PUBLIC_KEY")
case "platform-only":
delete(cfg, "WECHAT_PUBLIC_KEY_ID")
delete(cfg, "WECHAT_PUBLIC_KEY")
case "none":
delete(cfg, "WECHAT_PLATFORM_SERIAL")
delete(cfg, "WECHAT_PLATFORM_PUBLIC_KEY")
delete(cfg, "WECHAT_PUBLIC_KEY_ID")
delete(cfg, "WECHAT_PUBLIC_KEY")
case "missing-public":
delete(cfg, "WECHAT_PUBLIC_KEY")
case "missing-id":
delete(cfg, "WECHAT_PUBLIC_KEY_ID")
case "bad-id":
cfg["WECHAT_PUBLIC_KEY_ID"] = "merchant-cert"
}
_, err := NewProvider("wechat", cfg)
valid := mode == "public-only" || mode == "platform-only" || mode == "both"
if (err == nil) != valid {
t.Fatalf("unexpected configuration result: %v", err)
}
})
}
}
func TestRequiredSettingsIndependent(t *testing.T) {
for channel, cfg := range testConfigs(t) {
a := RequiredSettings(channel)
if channel == "wechat" {
if len(a) >= len(cfg) {
t.Fatalf("wechat optional verification settings became required")
}
} else if len(a) != len(cfg) {
t.Fatalf("%s: expected %d required settings, got %d", channel, len(cfg), len(a))
}
a[0] = "CHANGED"
b := RequiredSettings(channel)
if b[0] == "CHANGED" {
t.Fatalf("%s: shared settings slice", channel)
}
for _, key := range b {
if _, ok := cfg[key]; !ok {
t.Fatalf("%s: unknown setting %s", channel, key)
}
}
}
}

View File

@@ -0,0 +1,119 @@
package payments
import (
"crypto"
"crypto/aes"
"crypto/cipher"
"crypto/rand"
"crypto/rsa"
"crypto/sha256"
"crypto/x509"
"encoding/base64"
"encoding/json"
"encoding/pem"
"errors"
"io"
"os"
"strconv"
"strings"
)
func readKey(v string) ([]byte, error) {
if strings.HasPrefix(v, "@") {
return os.ReadFile(strings.TrimPrefix(v, "@"))
}
return []byte(strings.ReplaceAll(v, "\\n", "\n")), nil
}
func privateKey(v string) (*rsa.PrivateKey, error) {
b, e := readKey(v)
if e != nil {
return nil, e
}
p, _ := pem.Decode(b)
if p == nil {
return nil, errors.New("invalid PEM private key")
}
if k, e := x509.ParsePKCS8PrivateKey(p.Bytes); e == nil {
if r, ok := k.(*rsa.PrivateKey); ok {
return r, nil
}
}
if r, e := x509.ParsePKCS1PrivateKey(p.Bytes); e == nil {
return r, nil
}
return nil, errors.New("invalid RSA private key")
}
func publicKey(v string) (*rsa.PublicKey, error) {
b, e := readKey(v)
if e != nil {
return nil, e
}
p, _ := pem.Decode(b)
if p == nil {
return nil, errors.New("invalid PEM public key")
}
if c, e := x509.ParseCertificate(p.Bytes); e == nil {
if r, ok := c.PublicKey.(*rsa.PublicKey); ok {
return r, nil
}
}
if k, e := x509.ParsePKIXPublicKey(p.Bytes); e == nil {
if r, ok := k.(*rsa.PublicKey); ok {
return r, nil
}
}
return nil, errors.New("invalid RSA public key")
}
func signRSA(priv *rsa.PrivateKey, s string) (string, error) {
h := sha256.Sum256([]byte(s))
b, e := rsa.SignPKCS1v15(rand.Reader, priv, cryptoHash(), h[:])
return base64.StdEncoding.EncodeToString(b), e
}
func cryptoHash() crypto.Hash { return crypto.SHA256 }
func decryptGCM(key, nonce, ad, ct string) (string, error) {
block, e := aes.NewCipher([]byte(key))
if e != nil {
return "", e
}
g, e := cipher.NewGCM(block)
if e != nil {
return "", e
}
if len(nonce) != g.NonceSize() {
return "", errors.New("invalid GCM nonce length")
}
raw, e := base64.StdEncoding.DecodeString(ct)
if e != nil {
return "", e
}
plain, e := g.Open(nil, []byte(nonce), raw, []byte(ad))
return string(plain), e
}
func cents(v any) (int64, error) {
switch x := v.(type) {
case json.Number:
return strconv.ParseInt(string(x), 10, 64)
case string:
return strconv.ParseInt(x, 10, 64)
}
return 0, errors.New("invalid amount")
}
func verifyRSA(key *rsa.PublicKey, message, signature string) error {
b, e := base64.StdEncoding.DecodeString(signature)
if e != nil {
return e
}
h := sha256.Sum256([]byte(message))
return rsa.VerifyPKCS1v15(key, crypto.SHA256, h[:], b)
}
func readLimited(r io.Reader) ([]byte, error) {
b, e := io.ReadAll(io.LimitReader(r, (2<<20)+1))
if e != nil {
return nil, e
}
if len(b) > 2<<20 {
return nil, errors.New("payment response too large")
}
return b, nil
}

View File

@@ -0,0 +1,130 @@
package payments
import (
"context"
"errors"
"fmt"
"net/http"
"net/url"
"os"
"strings"
)
type Notification struct {
EventID, MerchantOrderNo, TradeNo, Currency string
AmountCents int64
Paid bool
}
type Provider interface {
Create(context.Context, string, int64, string) (string, error)
Query(context.Context, string) (Notification, error)
Verify(*http.Request) (Notification, error)
Close(context.Context, string) error
Refund(context.Context, string, string, int64) error
}
// Config holds channel settings using the documented ALIPAY_* and WECHAT_* keys.
// NewProvider reads this map synchronously and never modifies it or the process environment.
type Config map[string]string
const (
alipayEndpoint = "https://openapi.alipay.com/gateway.do"
wechatEndpoint = "https://api.mch.weixin.qq.com"
)
// RequiredSettings returns an independent slice. Unknown channels return nil.
func RequiredSettings(channel string) []string {
switch channel {
case "alipay":
return []string{"ALIPAY_APP_ID", "ALIPAY_SELLER_ID", "ALIPAY_PRIVATE_KEY", "ALIPAY_PUBLIC_KEY", "ALIPAY_NOTIFY_URL"}
case "wechat":
return []string{"WECHAT_MCH_ID", "WECHAT_APP_ID", "WECHAT_SERIAL_NO", "WECHAT_PRIVATE_KEY", "WECHAT_API_V3_KEY", "WECHAT_NOTIFY_URL"}
default:
return nil
}
}
// ConfigFromEnv returns a snapshot of the channel's nonempty settings, including
// its legacy endpoint setting. Unknown channels return an empty map.
func ConfigFromEnv(channel string) Config {
c := Config{}
keys := RequiredSettings(channel)
if len(keys) == 0 {
return c
}
if channel == "wechat" {
keys = append(keys, "WECHAT_PUBLIC_KEY_ID", "WECHAT_PUBLIC_KEY", "WECHAT_PLATFORM_SERIAL", "WECHAT_PLATFORM_PUBLIC_KEY")
}
keys = append(keys, strings.ToUpper(channel)+"_ENDPOINT")
for _, key := range keys {
if v := strings.TrimSpace(os.Getenv(key)); v != "" {
c[key] = v
}
}
return c
}
// NewProvider validates settings without making network requests. Endpoints are
// fixed to the official production gateways; a conflicting override is rejected.
func NewProvider(channel string, config Config) (Provider, error) {
keys := RequiredSettings(channel)
if len(keys) == 0 {
return nil, fmt.Errorf("unsupported payment channel %q", channel)
}
for _, key := range keys {
if _, err := config.required(key); err != nil {
return nil, fmt.Errorf("%s: %w", channel, err)
}
}
endpoint := alipayEndpoint
if channel == "wechat" {
endpoint = wechatEndpoint
}
if override := config.value(strings.ToUpper(channel) + "_ENDPOINT"); override != "" && override != endpoint {
return nil, fmt.Errorf("%s: endpoint must be the official production gateway", channel)
}
var p Provider
var err error
switch channel {
case "alipay":
p, err = newAlipay(config)
case "wechat":
p, err = newWechat(config)
}
if err != nil {
return nil, fmt.Errorf("%s: %w", channel, err)
}
return p, nil
}
func LoadFromEnv() (map[string]Provider, error) {
out := map[string]Provider{}
for _, channel := range []string{"alipay", "wechat"} {
c := ConfigFromEnv(channel)
if len(c) == 0 {
continue
}
p, err := NewProvider(channel, c)
if err != nil {
return nil, err
}
out[channel] = p
}
return out, nil
}
func (c Config) value(key string) string { return strings.TrimSpace(c[key]) }
func (c Config) required(key string) (string, error) {
v := c.value(key)
if v == "" {
return "", errors.New("missing " + key)
}
return v, nil
}
func validateNotifyURL(key, value string) error {
u, err := url.Parse(value)
if err != nil || u.Scheme != "https" || u.Hostname() == "" || u.User != nil || u.Fragment != "" {
return fmt.Errorf("%s must be an absolute HTTPS URL without userinfo or fragment", key)
}
return nil
}

View File

@@ -0,0 +1,37 @@
package payments
import (
"crypto/aes"
"crypto/cipher"
"encoding/base64"
"testing"
)
func TestParseAlipayAmount(t *testing.T) {
for _, tc := range []struct {
s string
want int64
ok bool
}{{"1.50", 150, true}, {"0.01", 1, true}, {"1.5", 150, true}, {"-1.00", 0, false}, {"1.000", 0, false}, {"abc", 0, false}} {
got, e := parseAlipayAmount(tc.s)
if (e == nil) != tc.ok || e == nil && got != tc.want {
t.Fatalf("%q got %d err %v", tc.s, got, e)
}
}
}
func TestDecryptGCMRejectsInvalidNonce(t *testing.T) {
if _, e := decryptGCM("01234567890123456789012345678901", "short", "", "AA=="); e == nil {
t.Fatal("expected nonce length error")
}
}
func TestDecryptGCM(t *testing.T) {
key := []byte("01234567890123456789012345678901")
b, _ := aes.NewCipher(key)
g, _ := cipher.NewGCM(b)
nonce := []byte("nonce1234567")
ct := g.Seal(nil, nonce, []byte(`{"out_trade_no":"m-1"}`), []byte("ad"))
got, e := decryptGCM(string(key), string(nonce), "ad", base64.StdEncoding.EncodeToString(ct))
if e != nil || got == "" {
t.Fatalf("decrypt failed: %q %v", got, e)
}
}

View 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")
}
}

View File

@@ -0,0 +1,337 @@
package payments
import (
"bytes"
"context"
"crypto"
"crypto/rand"
"crypto/rsa"
"crypto/sha256"
"encoding/base64"
"encoding/json"
"errors"
"fmt"
"net"
"net/http"
"net/url"
"strconv"
"strings"
"time"
)
type wechat struct {
mchid, serial, platformSerial, appid, notify, key, endpoint string
priv *rsa.PrivateKey
platform *rsa.PublicKey
publicKeyID string
verificationKeys map[string]*rsa.PublicKey
client *http.Client
}
func newWechatFromEnv() (Provider, error) { return NewProvider("wechat", ConfigFromEnv("wechat")) }
func newWechat(config Config) (Provider, error) {
m, e := config.required("WECHAT_MCH_ID")
if e != nil {
return nil, e
}
s, e := config.required("WECHAT_SERIAL_NO")
if e != nil {
return nil, e
}
pk, e := config.required("WECHAT_PRIVATE_KEY")
if e != nil {
return nil, e
}
priv, e := privateKey(pk)
if e != nil {
return nil, e
}
platformSerial := config.value("WECHAT_PLATFORM_SERIAL")
publicKeyID := config.value("WECHAT_PUBLIC_KEY_ID")
keys := map[string]*rsa.PublicKey{}
var pub *rsa.PublicKey
for _, pair := range [][2]string{{"WECHAT_PLATFORM_SERIAL", "WECHAT_PLATFORM_PUBLIC_KEY"}, {"WECHAT_PUBLIC_KEY_ID", "WECHAT_PUBLIC_KEY"}} {
id, material := config.value(pair[0]), config.value(pair[1])
if id == "" && material == "" {
continue
}
if id == "" || material == "" {
return nil, fmt.Errorf("%s and %s must be configured together", pair[0], pair[1])
}
if pair[0] == "WECHAT_PLATFORM_SERIAL" && strings.HasPrefix(id, "PUB_KEY_ID_") {
return nil, errors.New("WECHAT_PLATFORM_SERIAL must be a platform certificate serial")
}
if pair[0] == "WECHAT_PUBLIC_KEY_ID" && (!strings.HasPrefix(id, "PUB_KEY_ID_") || len(id) <= len("PUB_KEY_ID_")) {
return nil, errors.New("invalid WECHAT_PUBLIC_KEY_ID")
}
if _, exists := keys[id]; exists {
return nil, errors.New("duplicate wechat verification key identifier")
}
key, err := publicKey(material)
if err != nil {
return nil, fmt.Errorf("invalid %s", pair[1])
}
keys[id] = key
if pair[0] == "WECHAT_PLATFORM_SERIAL" {
pub = key
}
}
if len(keys) == 0 {
return nil, errors.New("configure WECHAT_PUBLIC_KEY_ID and WECHAT_PUBLIC_KEY or WECHAT_PLATFORM_SERIAL and WECHAT_PLATFORM_PUBLIC_KEY")
}
k, e := config.required("WECHAT_API_V3_KEY")
if e != nil || len(k) != 32 {
return nil, errors.New("WECHAT_API_V3_KEY must be 32 bytes")
}
appid, e := config.required("WECHAT_APP_ID")
if e != nil {
return nil, e
}
notify := config.value("WECHAT_NOTIFY_URL")
if notify == "" {
return nil, errors.New("missing WECHAT_NOTIFY_URL")
}
if e = validateNotifyURL("WECHAT_NOTIFY_URL", notify); e != nil {
return nil, e
}
return &wechat{mchid: m, serial: s, platformSerial: platformSerial, appid: appid, notify: notify, key: k, priv: priv, platform: pub, publicKeyID: publicKeyID, verificationKeys: keys, endpoint: wechatEndpoint, client: &http.Client{Timeout: 15 * time.Second, Transport: &http.Transport{DialContext: (&net.Dialer{Timeout: 5 * time.Second}).DialContext}}}, nil
}
func (w *wechat) auth(method, path string, body []byte) (http.Header, error) {
ts := fmt.Sprint(time.Now().Unix())
nonce := make([]byte, 16)
if _, e := rand.Read(nonce); e != nil {
return nil, e
}
ns := base64.RawURLEncoding.EncodeToString(nonce)
message := method + "\n" + path + "\n" + ts + "\n" + ns + "\n" + string(body) + "\n"
h := sha256.Sum256([]byte(message))
sig, e := rsa.SignPKCS1v15(rand.Reader, w.priv, crypto.SHA256, h[:])
if e != nil {
return nil, e
}
v := fmt.Sprintf("WECHATPAY2-SHA256-RSA2048 mchid=\"%s\",nonce_str=\"%s\",signature=\"%s\",timestamp=\"%s\",serial_no=\"%s\"", w.mchid, ns, base64.StdEncoding.EncodeToString(sig), ts, w.serial)
return http.Header{"Authorization": {v}}, nil
}
func (w *wechat) do(ctx context.Context, method, path string, body []byte) (map[string]any, error) {
h, e := w.auth(method, path, body)
if e != nil {
return nil, e
}
req, e := http.NewRequestWithContext(ctx, method, w.endpoint+path, bytes.NewReader(body))
if e != nil {
return nil, e
}
req.Header = h
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Accept", "application/json")
if w.publicKeyID != "" {
req.Header.Set("Wechatpay-Serial", w.publicKeyID)
}
resp, e := w.client.Do(req)
if e != nil {
return nil, e
}
defer resp.Body.Close()
raw, e := readLimited(resp.Body)
if e != nil {
return nil, e
}
var out map[string]any
if len(raw) > 0 {
dec := json.NewDecoder(bytes.NewReader(raw))
dec.UseNumber()
if e := dec.Decode(&out); e != nil {
return nil, e
}
}
if resp.Header.Get("Wechatpay-Signature") == "" {
return nil, errors.New("missing wechat response signature")
}
if sig := resp.Header.Get("Wechatpay-Signature"); sig != "" {
ts, nonce := resp.Header.Get("Wechatpay-Timestamp"), resp.Header.Get("Wechatpay-Nonce")
stamp, e := strconv.ParseInt(ts, 10, 64)
if e != nil || nonce == "" || time.Since(time.Unix(stamp, 0)) > 5*time.Minute || time.Until(time.Unix(stamp, 0)) > 5*time.Minute {
return nil, errors.New("wechat response timestamp outside window")
}
serial := resp.Header.Get("Wechatpay-Serial")
key := w.verificationKey(serial)
if key == nil {
return nil, errors.New("wechat response serial mismatch")
}
b, e := base64.StdEncoding.DecodeString(sig)
if e != nil {
return nil, e
}
h := sha256.Sum256([]byte(ts + "\n" + nonce + "\n" + string(raw) + "\n"))
if e = rsa.VerifyPKCS1v15(key, crypto.SHA256, h[:], b); e != nil {
return nil, errors.New("invalid wechat response signature")
}
}
if resp.StatusCode < 200 || resp.StatusCode >= 300 {
return out, fmt.Errorf("wechat HTTP %d", resp.StatusCode)
}
return out, nil
}
func (w *wechat) Create(ctx context.Context, no string, amount int64, title string) (string, error) {
if amount <= 0 {
return "", errors.New("invalid amount")
}
b, _ := json.Marshal(map[string]any{"appid": w.appid, "mchid": w.mchid, "description": title, "out_trade_no": no, "notify_url": w.notify, "amount": map[string]any{"total": amount, "currency": "CNY"}})
o, e := w.do(ctx, "POST", "/v3/pay/transactions/native", b)
if e != nil {
return "", e
}
q, _ := o["code_url"].(string)
if q == "" {
return "", errors.New("wechat missing code_url")
}
return q, nil
}
func (w *wechat) Query(ctx context.Context, no string) (Notification, error) {
o, e := w.do(ctx, "GET", "/v3/pay/transactions/out-trade-no/"+urlPath(no)+"?mchid="+urlPath(w.mchid), nil)
if e != nil {
return Notification{}, e
}
if o["mchid"] != w.mchid || o["appid"] != w.appid || o["out_trade_no"] != no {
return Notification{}, errors.New("wechat query identity mismatch")
}
n := Notification{EventID: "query-" + no, MerchantOrderNo: no, Currency: "CNY"}
n.TradeNo, _ = o["transaction_id"].(string)
if n.TradeNo != "" {
n.EventID = "query-" + n.TradeNo
}
status, _ := o["trade_state"].(string)
n.Paid = status == "SUCCESS"
if am, ok := o["amount"].(map[string]any); ok {
if am["currency"] != "CNY" {
return Notification{}, errors.New("currency mismatch")
}
n.AmountCents, e = cents(am["total"])
if e != nil || n.AmountCents < 0 {
return Notification{}, errors.New("invalid amount")
}
}
if n.Paid && (n.AmountCents <= 0 || n.TradeNo == "") {
return Notification{}, errors.New("incomplete paid query")
}
return n, nil
}
func urlPath(s string) string {
return url.PathEscape(s)
}
func (w *wechat) Close(ctx context.Context, no string) error {
o, e := w.do(ctx, "GET", "/v3/pay/transactions/out-trade-no/"+urlPath(no)+"?mchid="+url.QueryEscape(w.mchid), nil)
if e != nil {
return e
}
if o["mchid"] != w.mchid || o["out_trade_no"] != no {
return errors.New("close identity mismatch")
}
if o["trade_state"] == "CLOSED" {
return nil
}
_, e = w.do(ctx, "POST", "/v3/pay/transactions/out-trade-no/"+urlPath(no)+"/close", []byte(`{"mchid":"`+w.mchid+`"}`))
return e
}
func (w *wechat) Refund(ctx context.Context, no, refund string, amount int64) error {
original, e := w.Query(ctx, no)
if e != nil {
return e
}
if amount <= 0 || amount > original.AmountCents {
return errors.New("invalid refund amount")
}
b, _ := json.Marshal(map[string]any{"out_trade_no": no, "out_refund_no": refund, "amount": map[string]any{"refund": amount, "total": original.AmountCents, "currency": "CNY"}})
_, e = w.do(ctx, "POST", "/v3/refund/domestic/refunds", b)
return e
}
func (w *wechat) Verify(req *http.Request) (Notification, error) {
if req == nil {
return Notification{}, errors.New("nil request")
}
ts := req.Header.Get("Wechatpay-Timestamp")
nonce := req.Header.Get("Wechatpay-Nonce")
sig := req.Header.Get("Wechatpay-Signature")
serial := req.Header.Get("Wechatpay-Serial")
key := w.verificationKey(serial)
if key == nil {
return Notification{}, errors.New("wechat certificate serial mismatch")
}
stamp, e := strconv.ParseInt(ts, 10, 64)
if e != nil || time.Since(time.Unix(stamp, 0)) > 5*time.Minute || time.Until(time.Unix(stamp, 0)) > 5*time.Minute {
return Notification{}, errors.New("wechat notification timestamp outside window")
}
if sig == "" || ts == "" || nonce == "" {
return Notification{}, errors.New("missing wechat signature headers")
}
body, e := readLimited(req.Body)
if e != nil {
return Notification{}, e
}
msg := ts + "\n" + nonce + "\n" + string(body) + "\n"
raw, e := base64.StdEncoding.DecodeString(sig)
if e != nil {
return Notification{}, e
}
h := sha256.Sum256([]byte(msg))
if e = rsa.VerifyPKCS1v15(key, crypto.SHA256, h[:], raw); e != nil {
return Notification{}, errors.New("invalid wechat signature")
}
var env struct {
Id string `json:"id"`
EventType string `json:"event_type"`
Resource struct {
Algorithm string `json:"algorithm"`
Nonce string `json:"nonce"`
AssociatedData string `json:"associated_data"`
Ciphertext string `json:"ciphertext"`
} `json:"resource"`
}
if e = json.Unmarshal(body, &env); e != nil {
return Notification{}, e
}
if env.EventType != "TRANSACTION.SUCCESS" || env.Id == "" {
return Notification{}, errors.New("unexpected notification event")
}
if env.Resource.Algorithm != "AEAD_AES_256_GCM" {
return Notification{}, errors.New("unsupported wechat notification algorithm")
}
plain, e := decryptGCM(w.key, env.Resource.Nonce, env.Resource.AssociatedData, env.Resource.Ciphertext)
if e != nil {
return Notification{}, e
}
var x struct {
TransactionId string `json:"transaction_id"`
OutTradeNo string `json:"out_trade_no"`
TradeState string `json:"trade_state"`
Appid string `json:"appid"`
Amount struct {
Total int64 `json:"total"`
Currency string `json:"currency"`
} `json:"amount"`
Mchid string `json:"mchid"`
}
if e = json.Unmarshal([]byte(plain), &x); e != nil {
return Notification{}, e
}
if x.Mchid != w.mchid || (w.appid != "" && x.Appid != w.appid) || x.Amount.Currency != "CNY" || x.Amount.Total <= 0 || x.OutTradeNo == "" || x.TransactionId == "" {
return Notification{}, errors.New("wechat merchant or currency mismatch")
}
return Notification{EventID: env.Id, MerchantOrderNo: x.OutTradeNo, TradeNo: x.TransactionId, Currency: x.Amount.Currency, AmountCents: x.Amount.Total, Paid: x.TradeState == "SUCCESS"}, nil
}
// Select only explicitly configured trusted keys; never fetch a key named by a request.
func (w *wechat) verificationKey(id string) *rsa.PublicKey {
if id == "" {
return nil
}
if w.verificationKeys != nil {
return w.verificationKeys[id]
}
if id == w.platformSerial {
return w.platform
}
return nil
}