微信接口的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.

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