notify_result.go 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  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. resMap["appid"] = notifyRes.AppID
  43. resMap["bank_type"] = notifyRes.BankType
  44. resMap["cash_fee"] = notifyRes.CashFee
  45. resMap["fee_type"] = notifyRes.FeeType
  46. resMap["is_subscribe"] = notifyRes.IsSubscribe
  47. resMap["mch_id"] = notifyRes.MchID
  48. resMap["nonce_str"] = notifyRes.NonceStr
  49. resMap["openid"] = notifyRes.OpenID
  50. resMap["out_trade_no"] = notifyRes.OutTradeNo
  51. resMap["result_code"] = notifyRes.ResultCode
  52. resMap["return_code"] = notifyRes.ReturnCode
  53. resMap["time_end"] = notifyRes.TimeEnd
  54. resMap["total_fee"] = notifyRes.TotalFee
  55. resMap["trade_type"] = notifyRes.TradeType
  56. resMap["transaction_id"] = notifyRes.TransactionID
  57. // 支付key
  58. sortedKeys := make([]string, 0, len(resMap))
  59. for k := range resMap {
  60. sortedKeys = append(sortedKeys, k)
  61. }
  62. sort.Strings(sortedKeys)
  63. // STEP2, 对key=value的键值对用&连接起来,略过空值
  64. var signStrings string
  65. for _, k := range sortedKeys {
  66. value := fmt.Sprintf("%v", resMap[k])
  67. if value != "" {
  68. signStrings = signStrings + k + "=" + value + "&"
  69. }
  70. }
  71. // STEP3, 在键值对的最后加上key=API_KEY
  72. signStrings = signStrings + "key=" + pcf.PayKey
  73. // STEP4, 进行MD5签名并且将所有字符转为大写.
  74. sign := util.MD5Sum(signStrings)
  75. if sign != notifyRes.Sign {
  76. return false
  77. }
  78. return true
  79. }