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
}
// 签名
func (app *App) sign(params map[string]interface{}) respSign {
// 默认参数
v := "1.0"
format := "json"
timestamp := strconv.FormatInt(time.Now().Unix(), 10)
params["v"] = v // 客户端接口版本目前是1.0
params["format"] = format // 默认json
params["app_key"] = app.appKey // 应用唯一表示
params["client"] = app.clientIp // 客户端请求ip
params["timestamp"] = timestamp // unix时间戳秒单位
// 排序所有的 key
var keys []string
for key := range params {
keys = append(keys, key)
}
sort.Strings(keys)
signStr := app.appSecret
for _, key := range keys {
signStr += key + getString(params[key])
}
signStr += app.appSecret
return respSign{
AppKey: app.appKey,
Timestamp: timestamp,
Client: app.clientIp,
V: v,
Format: format,
Sign: app.createSign(signStr),
}
}
// 签名
func (app *App) createSign(signStr string) string {
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)
}
}