package wechat import ( "fmt" "math/rand" "sort" "strings" "time" "git.chuangxin1.com/cx/myth" ) // 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 } sign = strings.ToUpper(myth.MD5(s)) 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) return strings.Compare(signature, myth.SHA1(strings.Join(sl, ""))) == 0 }