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 }