微信接口的RPC包
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

102 lines
1.7 KiB

3 years ago
3 years ago
3 years ago
3 years ago
  1. package weixinrpc
  2. import (
  3. "crypto/md5"
  4. "encoding/hex"
  5. "encoding/json"
  6. "errors"
  7. "log"
  8. "strconv"
  9. "strings"
  10. "time"
  11. "git.tetele.net/tgo/crypter"
  12. )
  13. /**
  14. * 签名
  15. */
  16. func Sign(data string, salt string) string {
  17. var build strings.Builder
  18. build.WriteString(data)
  19. build.WriteString(salt)
  20. build.WriteString(DES_KEY)
  21. data_str := build.String()
  22. h := md5.New()
  23. h.Write([]byte(data_str)) // 需要加密的字符串
  24. return hex.EncodeToString(h.Sum(nil)) // 输出加密结果
  25. }
  26. /**
  27. * 验证签名
  28. */
  29. func CheckSign(sign_str, data, salt string) bool {
  30. sign := Sign(data, salt)
  31. if strings.Compare(sign_str, sign) > -1 {
  32. return true
  33. }
  34. return false
  35. }
  36. /**
  37. * 解密
  38. */
  39. func GetOrgData(res *Response) (string, error) {
  40. res_data := res.GetData()
  41. if res_data == "" {
  42. return "", errors.New("未收到收据")
  43. }
  44. time_int64, err := strconv.ParseInt(res.GetTime(), 10, 64)
  45. if err != nil {
  46. return "", err
  47. }
  48. now_int64 := time.Now().Unix()
  49. if now_int64-time_int64 > 10 || time_int64-now_int64 > 10 {
  50. //时间误差前后10秒,返回
  51. return "", errors.New("返回时间错误")
  52. }
  53. check_sign := CheckSign(res.GetSign(), res_data, res.GetTime())
  54. if !check_sign {
  55. return "", errors.New("返回数据签名错误")
  56. }
  57. //解密
  58. res_data_de := crypter.DesDe(res_data, DES_KEY)
  59. return res_data_de, nil
  60. }
  61. /**
  62. * 处理返回结果
  63. */
  64. func HandleRes(res *Response) (*WxApiRes, error) {
  65. //解密
  66. res_data_de, err := GetOrgData(res)
  67. log.Println("res_data_de", res_data_de)
  68. if err != nil {
  69. return nil, err
  70. }
  71. var res_arr WxApiRes
  72. err = json.Unmarshal([]byte(res_data_de), &res_arr)
  73. if err != nil {
  74. return nil, err
  75. }
  76. return &res_arr, nil
  77. }