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.

53 line
1.4KB

  1. package main
  2. import (
  3. "crypto/sha1"
  4. "fmt"
  5. "math/rand"
  6. "sort"
  7. "strings"
  8. "time"
  9. )
  10. //BuildTextMsg Given a text message send it to wechat client
  11. func BuildTextMsg(txt string, ToUserName string) (string, error) {
  12. template := `<xml>
  13. <ToUserName><![CDATA[%s]]></ToUserName>
  14. <FromUserName><![CDATA[%s]]></FromUserName>
  15. <CreateTime>%d</CreateTime>
  16. <MsgType><![CDATA[text]]></MsgType>
  17. <Content><![CDATA[%s]]></Content>
  18. </xml>`
  19. msg := fmt.Sprintf(template, ToUserName, APIConfig.PublicAccountID, int32(time.Now().Unix()), txt)
  20. e := Encode(msg)
  21. str, _, _, _ := signMsg(e)
  22. return str, nil
  23. }
  24. func signMsg(content string) (xml string, timestamp int32, nonce int32, signature string) {
  25. timestamp = int32(time.Now().Unix())
  26. nonce = rand.Int31()
  27. strTimestamp := fmt.Sprintf("%d", timestamp)
  28. strNonce := fmt.Sprintf("%d", nonce)
  29. signature = getSignature(APIConfig.Token, strTimestamp, strNonce, content)
  30. xml = "<xml>" +
  31. "<Encrypt>" + content + "</Encrypt>" +
  32. "<MsgSignature>" + signature + "</MsgSignature>" +
  33. "<TimeStamp>" + strTimestamp + "</TimeStamp>" +
  34. "<Nonce>" + strNonce + "</Nonce>" +
  35. "</xml>"
  36. return
  37. }
  38. func getSignature(token string, timestamp string, nonce string, content string) (signature string) {
  39. strs := []string{token, timestamp, nonce, content}
  40. sort.Strings(strs)
  41. s := strings.Join(strs, "")
  42. h := sha1.New()
  43. h.Write([]byte(s))
  44. signature = fmt.Sprintf("%x", h.Sum(nil))
  45. return
  46. }