package wechat import ( "encoding/hex" "fmt" "math/rand" "sort" "strings" "time" "git.chuangxin1.com/myth/sacred/hash" ) // Sign 微信计算签名的函数 func Sign(req map[string]interface{}, key string) (sign string) { keys := make([]string, 0) for k := range req { keys = append(keys, k) } sort.Strings(keys) var s string for _, k := range keys { value := fmt.Sprintf("%v", req[k]) if value != "" { s = s + k + "=" + value + "&" } } if key != "" { s = s + "key=" + key } hs, _ := hash.MD5([]byte(s)) sign = strings.ToUpper(hex.EncodeToString(hs)) return } // Random 指定长度的随机字符串(字母或数字) func Random(n int) string { str := "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789" bytes := []byte(str) result := []byte{} r := rand.New(rand.NewSource(time.Now().UnixNano())) n1 := len(bytes) for i := 0; i < n; i++ { result = append(result, bytes[r.Intn(n1)]) } return string(result) } // makeSignature echo 签名验证 func makeSignature(token, signature, timestamp, nonce string) bool { sl := []string{token, timestamp, nonce} sort.Strings(sl) hs, _ := hash.SHA1([]byte(strings.Join(sl, ""))) return strings.Compare(signature, hex.EncodeToString(hs)) == 0 }