wechat.go 6.7 KB

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