Browse Source

fix signature calculate

Mongo 8 năm trước cách đây
mục cha
commit
a9bfce3fbe
2 tập tin đã thay đổi với 20 bổ sung9 xóa
  1. 4 9
      pay/pay.go
  2. 16 0
      util/crypto.go

+ 4 - 9
pay/pay.go

@@ -2,10 +2,8 @@ package pay
 
 import (
 	"errors"
-	"crypto/md5"
 	"encoding/xml"
 	"fmt"	
-	"strings"
 	"github.com/silenceper/wechat/context"
 	"github.com/silenceper/wechat/util"
 )
@@ -88,12 +86,9 @@ func NewPay(ctx *context.Context) *Pay {
 func (pcf *Pay) PrePayId(p *PayParams) (prePayID string, err error) {
 	nonceStr := util.RandomStr(32)
 	tradeType := "JSAPI"
-	template := "appid=%s&body=%s&mch_id=%s&nonce_str=%s&notify_url=%s&out_trade_no=%s&spbill_create_ip=%s&total_fee=%s&trade_type=%s"
-	str := fmt.Sprintf(template, pcf.AppID, p.Body, pcf.PayMchID, nonceStr, pcf.PayNotifyURL, p.OutTradeNo, p.CreateIP, p.TotalFee, tradeType)
-	str = str + "&key=" + pcf.PayKey
-	sum := md5.Sum([]byte(str))
-	signature := string(sum[:])
-	sign := strings.ToUpper(signature)
+	template := "appid=%s&body=%s&mch_id=%s&nonce_str=%s&notify_url=%s&out_trade_no=%s&spbill_create_ip=%s&total_fee=%s&trade_type=%s&key=%s"
+	str := fmt.Sprintf(template, pcf.AppID, p.Body, pcf.PayMchID, nonceStr, pcf.PayNotifyURL, p.OutTradeNo, p.CreateIP, p.TotalFee, tradeType, pcf.PayKey)
+	sign := util.Md5Sum(str)
 	request := payRequest{
 		AppID: pcf.AppID,
 		MchID: pcf.PayMchID,
@@ -123,6 +118,6 @@ func (pcf *Pay) PrePayId(p *PayParams) (prePayID string, err error) {
 		}
 		return "", errors.New(payRet.ErrCode + payRet.ErrCodeDes)
 	} else {
-		return "", errors.New("xml unmarshal err : raw - " + string(rawRet))		
+		return "", errors.New("[msg : xmlUnmarshalError] [rawReturn : " + string(rawRet) + "] [params : " + str + "] [sign : " + sign + "]")		
 	}
 }

+ 16 - 0
util/crypto.go

@@ -1,9 +1,13 @@
 package util
 
 import (
+	"bytes"
+	"bufio"
 	"crypto/aes"
 	"crypto/cipher"
+	"crypto/md5"
 	"encoding/base64"
+	"encoding/hex"
 	"fmt"
 )
 
@@ -181,3 +185,15 @@ func decodeNetworkByteOrder(orderBytes []byte) (n uint32) {
 		uint32(orderBytes[2])<<8 |
 		uint32(orderBytes[3])
 }
+
+// 计算 32 位长度的 MD5 sum
+func Md5Sum(txt string) (sum string) {
+	h := md5.New()
+	buf := bufio.NewWriterSize(h, 128)
+	buf.WriteString(txt)
+	buf.Flush()
+	sign := make([]byte, hex.EncodedLen(h.Size()))
+	hex.Encode(sign, h.Sum(nil))
+	sum = string(bytes.ToUpper(sign))
+	return
+}