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.
wikeyun/sign.go

77 lines
1.6 KiB

2 years ago
package wikeyun
import (
"crypto/md5"
"encoding/hex"
"encoding/json"
"sort"
"strconv"
"strings"
"time"
)
type respSign struct {
AppKey int
Timestamp string
Client string
V string
Format string
Sign string
}
// 签名
2 years ago
func (c *Client) sign(params map[string]interface{}) respSign {
2 years ago
// 默认参数
v := "1.0"
format := "json"
timestamp := strconv.FormatInt(time.Now().Unix(), 10)
2 years ago
params["v"] = v // 客户端接口版本目前是1.0
params["format"] = format // 默认json
params["app_key"] = c.GetAppKey() // 应用唯一表示
params["client"] = c.GetClientIp() // 客户端请求ip
params["timestamp"] = timestamp // unix时间戳秒单位
2 years ago
// 排序所有的 key
var keys []string
for key := range params {
keys = append(keys, key)
}
sort.Strings(keys)
2 years ago
signStr := c.GetAppSecret()
2 years ago
for _, key := range keys {
signStr += key + getString(params[key])
}
2 years ago
signStr += c.GetAppSecret()
2 years ago
return respSign{
2 years ago
AppKey: c.GetAppKey(),
2 years ago
Timestamp: timestamp,
2 years ago
Client: c.GetClientIp(),
2 years ago
V: v,
Format: format,
2 years ago
Sign: c.createSign(signStr),
2 years ago
}
}
// 签名
2 years ago
func (c *Client) createSign(signStr string) string {
2 years ago
h := md5.New()
h.Write([]byte(signStr))
cipherStr := h.Sum(nil)
return strings.ToUpper(hex.EncodeToString(cipherStr))
}
func getString(i interface{}) string {
switch v := i.(type) {
case string:
return v
case []byte:
return string(v)
case int:
return strconv.Itoa(v)
case bool:
return strconv.FormatBool(v)
default:
bytes, _ := json.Marshal(v)
return string(bytes)
}
}