wechat.go 6.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232
  1. package channel
  2. import (
  3. "bytes"
  4. "context"
  5. "crypto"
  6. "crypto/rand"
  7. "crypto/rsa"
  8. "crypto/sha256"
  9. "crypto/x509"
  10. "encoding/base64"
  11. "encoding/hex"
  12. "encoding/json"
  13. "encoding/pem"
  14. "errors"
  15. "fmt"
  16. "io"
  17. "math"
  18. "net/http"
  19. "os"
  20. "strings"
  21. "time"
  22. "wails-app/internal/config"
  23. )
  24. const (
  25. wechatAPIBase = "https://api.mch.weixin.qq.com"
  26. wechatNativePay = "/v3/pay/transactions/native"
  27. wechatQueryByID = "/v3/pay/transactions/out-trade-no/"
  28. )
  29. // WechatChannel 微信支付 Native 扫码(APIv3)。
  30. // 到账确认走查单接口(ADR-0002);notify_url 仅透传给微信做预留挂点,
  31. // 系统内没有回调端点。v1 未校验应答的微信平台签名(查询应答为明文 JSON),
  32. // 商户私钥签名请求已启用。
  33. type WechatChannel struct {
  34. appID string
  35. mchID string
  36. serialNo string
  37. privateKey *rsa.PrivateKey
  38. notifyURL string
  39. currency string
  40. client *http.Client
  41. }
  42. func NewWechatChannelFromConfig(cfg config.WechatPay) (*WechatChannel, error) {
  43. if !cfg.Enabled {
  44. return nil, errors.New("微信支付未启用")
  45. }
  46. if cfg.AppID == "" || cfg.MchID == "" || cfg.SerialNo == "" || cfg.PrivateKeyPath == "" {
  47. return nil, errors.New("微信支付商户配置不完整(app-id/mch-id/serial-no/private-key-path)")
  48. }
  49. pemBytes, err := os.ReadFile(cfg.PrivateKeyPath)
  50. if err != nil {
  51. return nil, fmt.Errorf("读取商户私钥失败: %w", err)
  52. }
  53. key, err := parsePrivateKey(pemBytes)
  54. if err != nil {
  55. return nil, err
  56. }
  57. currency := strings.ToUpper(strings.TrimSpace(cfg.Currency))
  58. if currency == "" {
  59. currency = "CNY"
  60. }
  61. return &WechatChannel{
  62. appID: cfg.AppID, mchID: cfg.MchID, serialNo: cfg.SerialNo,
  63. privateKey: key, notifyURL: cfg.NotifyURL, currency: currency,
  64. client: &http.Client{Timeout: 10 * time.Second},
  65. }, nil
  66. }
  67. func parsePrivateKey(pemBytes []byte) (*rsa.PrivateKey, error) {
  68. for {
  69. block, rest := pem.Decode(pemBytes)
  70. if block == nil {
  71. return nil, errors.New("商户私钥 PEM 解析失败")
  72. }
  73. if key, err := x509.ParsePKCS1PrivateKey(block.Bytes); err == nil {
  74. return key, nil
  75. }
  76. if key, err := x509.ParsePKCS8PrivateKey(block.Bytes); err == nil {
  77. if rsaKey, ok := key.(*rsa.PrivateKey); ok {
  78. return rsaKey, nil
  79. }
  80. return nil, errors.New("私钥不是 RSA 类型")
  81. }
  82. pemBytes = rest
  83. }
  84. }
  85. func (w *WechatChannel) Code() string { return ChannelWechat }
  86. type wechatNativeResp struct {
  87. CodeURL string `json:"code_url"`
  88. Message string `json:"message"`
  89. }
  90. func (w *WechatChannel) CreateOrder(ctx context.Context, req CreateOrderRequest) (CreateOrderResult, error) {
  91. total, err := yuanToFen(req.Amount)
  92. if err != nil {
  93. return CreateOrderResult{}, err
  94. }
  95. body := map[string]interface{}{
  96. "appid": w.appID,
  97. "mchid": w.mchID,
  98. "description": req.Description,
  99. "out_trade_no": req.OrderNo,
  100. "amount": map[string]interface{}{"total": total, "currency": w.currency},
  101. }
  102. if w.notifyURL != "" {
  103. body["notify_url"] = w.notifyURL
  104. }
  105. var resp wechatNativeResp
  106. if err := w.call(ctx, http.MethodPost, wechatNativePay, body, &resp); err != nil {
  107. return CreateOrderResult{}, err
  108. }
  109. if resp.CodeURL == "" {
  110. return CreateOrderResult{}, fmt.Errorf("微信下单未返回 code_url: %s", resp.Message)
  111. }
  112. return CreateOrderResult{CodeURL: resp.CodeURL}, nil
  113. }
  114. type wechatQueryResp struct {
  115. TradeState string `json:"trade_state"`
  116. TransactionID string `json:"transaction_id"`
  117. OutTradeNo string `json:"out_trade_no"`
  118. }
  119. func (w *WechatChannel) QueryOrder(ctx context.Context, orderNo string) (QueryOrderResult, error) {
  120. path := wechatQueryByID + orderNo + "?mchid=" + w.mchID
  121. var resp wechatQueryResp
  122. if err := w.call(ctx, http.MethodGet, path, nil, &resp); err != nil {
  123. return QueryOrderResult{}, err
  124. }
  125. switch resp.TradeState {
  126. case "SUCCESS":
  127. return QueryOrderResult{Status: QueryPaid, TransactionID: resp.TransactionID}, nil
  128. case "CLOSED", "REVOKED", "PAYERROR":
  129. return QueryOrderResult{Status: QueryClosed}, nil
  130. default: // NOTPAY, USERPAYING 等
  131. return QueryOrderResult{Status: QueryPending}, nil
  132. }
  133. }
  134. // call 发起微信 APIv3 请求并用商户私钥签名(WECHATPAY2-SHA256withRSA)。
  135. func (w *WechatChannel) call(ctx context.Context, method, path string, body interface{}, out interface{}) error {
  136. var bodyBytes []byte
  137. if body != nil {
  138. var err error
  139. bodyBytes, err = json.Marshal(body)
  140. if err != nil {
  141. return err
  142. }
  143. }
  144. req, err := http.NewRequestWithContext(ctx, method, wechatAPIBase+path, bytes.NewReader(bodyBytes))
  145. if err != nil {
  146. return err
  147. }
  148. authorization, err := w.authorizationHeader(method, path, bodyBytes)
  149. if err != nil {
  150. return err
  151. }
  152. req.Header.Set("Authorization", authorization)
  153. req.Header.Set("Content-Type", "application/json")
  154. req.Header.Set("Accept", "application/json")
  155. req.Header.Set("User-Agent", "smart-parking-exit-kiosk")
  156. resp, err := w.client.Do(req)
  157. if err != nil {
  158. return fmt.Errorf("微信支付请求失败: %w", err)
  159. }
  160. defer resp.Body.Close()
  161. respBytes, err := io.ReadAll(io.LimitReader(resp.Body, 1<<20))
  162. if err != nil {
  163. return err
  164. }
  165. if resp.StatusCode != http.StatusOK {
  166. return fmt.Errorf("微信支付接口错误 HTTP %d: %s", resp.StatusCode, truncate(respBytes, 300))
  167. }
  168. if out != nil && len(respBytes) > 0 {
  169. if err := json.Unmarshal(respBytes, out); err != nil {
  170. return fmt.Errorf("微信支付应答解析失败: %w", err)
  171. }
  172. }
  173. return nil
  174. }
  175. func (w *WechatChannel) authorizationHeader(method, path string, body []byte) (string, error) {
  176. timestamp := fmt.Sprintf("%d", time.Now().Unix())
  177. nonce, err := randomNonce()
  178. if err != nil {
  179. return "", err
  180. }
  181. message := strings.Join([]string{method, path, timestamp, nonce, string(body)}, "\n") + "\n"
  182. digest := sha256.Sum256([]byte(message))
  183. signature, err := rsa.SignPKCS1v15(rand.Reader, w.privateKey, crypto.SHA256, digest[:])
  184. if err != nil {
  185. return "", fmt.Errorf("微信支付签名失败: %w", err)
  186. }
  187. // 注意:新商户(微信支付公钥模式)网关要求的认证类型是 WECHATPAY2-SHA256-RSA2048,
  188. // 旧文档中的 WECHATPAY2-SHA256withRSA 会被拒绝并报"认证类型不正确"。
  189. return fmt.Sprintf(`WECHATPAY2-SHA256-RSA2048 mchid="%s",nonce_str="%s",signature="%s",timestamp="%s",serial_no="%s"`,
  190. w.mchID, nonce, base64.StdEncoding.EncodeToString(signature), timestamp, w.serialNo), nil
  191. }
  192. func randomNonce() (string, error) {
  193. buf := make([]byte, 16)
  194. if _, err := rand.Read(buf); err != nil {
  195. return "", err
  196. }
  197. return strings.ToUpper(hex.EncodeToString(buf)), nil
  198. }
  199. // yuanToFen 金额(元)转分,超出两位小数视为非法。
  200. func yuanToFen(amount float64) (int64, error) {
  201. if math.IsNaN(amount) || math.IsInf(amount, 0) || amount < 0 {
  202. return 0, errors.New("支付金额必须是有限的非负数")
  203. }
  204. fen := math.Round(amount * 100)
  205. if math.Abs(fen-amount*100) > 0.51 {
  206. return 0, fmt.Errorf("支付金额精度超限: %.4f", amount)
  207. }
  208. return int64(fen), nil
  209. }
  210. func truncate(b []byte, n int) string {
  211. if len(b) <= n {
  212. return string(b)
  213. }
  214. return string(b[:n]) + "..."
  215. }