Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
package sign
import (
"crypto/md5"
"encoding/hex"
"net/url"
"sort"
"strings"
)
// SignToken .
// http://open.taobao.com/doc.htm?docId=101617&docType=1
type SignToken struct {
params url.Values
secret string
}
func (s *SignToken) step1() []string {
keys := make([]string, 0, len(s.params))
for key := range s.params {
keys = append(keys, key)
}
sort.Sort(sort.StringSlice(keys))
return keys
}
func (s *SignToken) step2(keys []string) string {
result := ""
for _, key := range keys {
result += key + s.params.Get(key)
}
return result
}
func (s *SignToken) step3(params string) [md5.Size]byte {
return md5.Sum([]byte(s.secret + params + s.secret))
}
func (s *SignToken) step4(b [md5.Size]byte) string {
return strings.ToUpper(hex.EncodeToString(b[:]))
}
// Sign .
func (s *SignToken) Sign() string {
return s.step4(s.step3(s.step2(s.step1())))
}
// NewSignToken create a SignToken
func NewSignToken(params url.Values, secret string) *SignToken {
return &SignToken{params: params, secret: secret}
}
package sign
func TestSign(t *testing.T) {
assert := assert.New(t)
s := NewSignToken(url.Values{
"method": []string{"taobao.item.seller.get"},
"app_key": []string{"12345678"},
"session": []string{"test"},
"timestamp": []string{"2016-01-01 12:00:00"},
"format": []string{"json"},
"v": []string{"2.0"},
"sign_method": []string{"md5"},
"fields": []string{"num_iid,title,nick,price,num"},
"num_iid": []string{"11223344"},
}, "helloworld")
if s.Sign() != "66987CB115214E59E6EC978214934FB8" {
panic("error")
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.