sign.go 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. package wechat
  2. import (
  3. "fmt"
  4. "math/rand"
  5. "sort"
  6. "strings"
  7. "time"
  8. "git.chuangxin1.com/cx/myth"
  9. )
  10. // Sign 微信计算签名的函数
  11. func Sign(req map[string]interface{}, key string) (sign string) {
  12. keys := make([]string, 0)
  13. for k := range req {
  14. keys = append(keys, k)
  15. }
  16. sort.Strings(keys)
  17. var s string
  18. for _, k := range keys {
  19. value := fmt.Sprintf("%v", req[k])
  20. if value != "" {
  21. s = s + k + "=" + value + "&"
  22. }
  23. }
  24. if key != "" {
  25. s = s + "key=" + key
  26. }
  27. sign = strings.ToUpper(myth.MD5(s))
  28. return
  29. }
  30. // Random 指定长度的随机字符串(字母或数字)
  31. func Random(n int) string {
  32. str := "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
  33. bytes := []byte(str)
  34. result := []byte{}
  35. r := rand.New(rand.NewSource(time.Now().UnixNano()))
  36. n1 := len(bytes)
  37. for i := 0; i < n; i++ {
  38. result = append(result, bytes[r.Intn(n1)])
  39. }
  40. return string(result)
  41. }
  42. // makeSignature echo 签名验证
  43. func makeSignature(token, signature, timestamp, nonce string) bool {
  44. sl := []string{token, timestamp, nonce}
  45. sort.Strings(sl)
  46. return strings.Compare(signature, myth.SHA1(strings.Join(sl, ""))) == 0
  47. }