-
Notifications
You must be signed in to change notification settings - Fork 0
/
wxpay-hmac-sha256-demo.go
52 lines (46 loc) · 1.03 KB
/
wxpay-hmac-sha256-demo.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
package main
import (
"crypto/hmac"
"crypto/sha256"
"encoding/hex"
"log"
"sort"
"strings"
)
var data map[string]string
var key = ""
func init() {
data = map[string]string{
"mch_id": "",
"appid": "",
"openid": "",
"code": "",
"grant_type": "",
"scope": "",
}
}
func main() {
CalculateSignature(data, key)
}
// CalculateSignature return sign string
func CalculateSignature(fields map[string]string, key string) (result string, err error) {
var keyList []string
for k := range fields {
keyList = append(keyList, k)
}
sort.Strings(keyList)
var toSignString string
for _, v := range keyList {
if v != "sign" && fields[v] != "" {
toSignString = toSignString + v + "=" + fields[v] + "&"
}
}
toSignString = toSignString + "key=" + key
log.Printf("toSignString, %#v\n", toSignString)
hasher := hmac.New(sha256.New, []byte(key))
hasher.Write([]byte(toSignString))
result = hex.EncodeToString(hasher.Sum(nil))
result = strings.ToUpper(result)
log.Printf("%s\n", result)
return result, nil
}