package main
import (
"crypto/sha1"
"fmt"
"math/rand"
"sort"
"strings"
"time"
)
//BuildTextMsg Given a text message send it to wechat client
func BuildTextMsg(txt string, ToUserName string) (string, error) {
template := `
%d
`
msg := fmt.Sprintf(template, ToUserName, APIConfig.PublicAccountID, int32(time.Now().Unix()), txt)
e := Encode(msg)
str, _, _, _ := signMsg(e)
return str, nil
}
func signMsg(content string) (xml string, timestamp int32, nonce int32, signature string) {
timestamp = int32(time.Now().Unix())
nonce = rand.Int31()
strTimestamp := fmt.Sprintf("%d", timestamp)
strNonce := fmt.Sprintf("%d", nonce)
signature = getSignature(APIConfig.Token, strTimestamp, strNonce, content)
xml = "" +
"" + content + "" +
"" + signature + "" +
"" + strTimestamp + "" +
"" + strNonce + "" +
""
return
}
func getSignature(token string, timestamp string, nonce string, content string) (signature string) {
strs := []string{token, timestamp, nonce, content}
sort.Strings(strs)
s := strings.Join(strs, "")
h := sha1.New()
h.Write([]byte(s))
signature = fmt.Sprintf("%x", h.Sum(nil))
return
}