|
- 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 := `<xml>
- <ToUserName><![CDATA[%s]]></ToUserName>
- <FromUserName><![CDATA[%s]]></FromUserName>
- <CreateTime>%d</CreateTime>
- <MsgType><![CDATA[text]]></MsgType>
- <Content><![CDATA[%s]]></Content>
- </xml>`
- msg := fmt.Sprintf(template, ToUserName, "gh_f09231355c68", int32(time.Now().Unix()), txt)
- fmt.Println(msg)
- e := Encode(msg)
-
- str, _, _, _ := signMsg(e)
- fmt.Println(str)
- 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 = "<xml>" +
- "<Encrypt>" + content + "</Encrypt>" +
- "<MsgSignature>" + signature + "</MsgSignature>" +
- "<TimeStamp>" + strTimestamp + "</TimeStamp>" +
- "<Nonce>" + strNonce + "</Nonce>" +
- "</xml>"
- 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
- }
|