notify_result.go 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. package pay
  2. import (
  3. "fmt"
  4. "github.com/silenceper/wechat/util"
  5. "sort"
  6. )
  7. // Base 公用参数
  8. type Base struct {
  9. AppID string `xml:"appid"`
  10. MchID string `xml:"mch_id"`
  11. NonceStr string `xml:"nonce_str"`
  12. Sign string `xml:"sign"`
  13. }
  14. // NotifyResult 下单回调
  15. type NotifyResult struct {
  16. Base
  17. ReturnCode string `xml:"return_code"`
  18. ReturnMsg string `xml:"return_msg"`
  19. ResultCode string `xml:"result_code"`
  20. OpenID string `xml:"openid"`
  21. IsSubscribe string `xml:"is_subscribe"`
  22. TradeType string `xml:"trade_type"`
  23. BankType string `xml:"bank_type"`
  24. TotalFee int `xml:"total_fee"`
  25. FeeType string `xml:"fee_type"`
  26. CashFee int `xml:"cash_fee"`
  27. CashFeeType string `xml:"cash_fee_type"`
  28. TransactionID string `xml:"transaction_id"`
  29. OutTradeNo string `xml:"out_trade_no"`
  30. Attach string `xml:"attach"`
  31. TimeEnd string `xml:"time_end"`
  32. }
  33. // NotifyResp 消息通知返回
  34. type NotifyResp struct {
  35. ReturnCode string `xml:"return_code"`
  36. ReturnMsg string `xml:"return_msg"`
  37. }
  38. // VerifySign 验签
  39. func (pcf *Pay) VerifySign(notifyRes NotifyResult) bool {
  40. // 封装map 请求过来的 map
  41. resMap := make(map[string]interface{})
  42. // base
  43. resMap["appid"] = notifyRes.AppID
  44. resMap["mch_id"] = notifyRes.MchID
  45. resMap["nonce_str"] = notifyRes.NonceStr
  46. // NotifyResult
  47. resMap["return_code"] = notifyRes.ReturnCode
  48. resMap["result_code"] = notifyRes.ResultCode
  49. resMap["openid"] = notifyRes.OpenID
  50. resMap["is_subscribe"] = notifyRes.IsSubscribe
  51. resMap["trade_type"] = notifyRes.TradeType
  52. resMap["bank_type"] = notifyRes.BankType
  53. resMap["total_fee"] = notifyRes.TotalFee
  54. resMap["fee_type"] = notifyRes.FeeType
  55. resMap["cash_fee"] = notifyRes.CashFee
  56. resMap["transaction_id"] = notifyRes.TransactionID
  57. resMap["out_trade_no"] = notifyRes.OutTradeNo
  58. resMap["attach"] = notifyRes.Attach
  59. resMap["time_end"] = notifyRes.TimeEnd
  60. // 支付key
  61. sortedKeys := make([]string, 0, len(resMap))
  62. for k := range resMap {
  63. sortedKeys = append(sortedKeys, k)
  64. }
  65. sort.Strings(sortedKeys)
  66. // STEP2, 对key=value的键值对用&连接起来,略过空值
  67. var signStrings string
  68. for _, k := range sortedKeys {
  69. value := fmt.Sprintf("%v", resMap[k])
  70. if value != "" {
  71. signStrings = signStrings + k + "=" + value + "&"
  72. }
  73. }
  74. // STEP3, 在键值对的最后加上key=API_KEY
  75. signStrings = signStrings + "key=" + pcf.PayKey
  76. // STEP4, 进行MD5签名并且将所有字符转为大写.
  77. sign := util.MD5Sum(signStrings)
  78. if sign != notifyRes.Sign {
  79. return false
  80. }
  81. return true
  82. }