1. The basic backstage configuration of Wechat official account is as follows
2.
3. Code-post the most important part
const WXMESSAGETOKEN = "zxxxxxx4"
type CdataString struct {
Value string `xml:",cdata"`
}
type ReqWxMessage struct {
ToUserName CdataString `xml:"ToUserName"`
FromUserName CdataString `xml:"FromUserName"`
CreateTime int64 `xml:"CreateTime"`
MsgType CdataString `xml:"MsgType"`
Content CdataString `xml:"Content"`
MsgId string `xml:"MsgId"`
}
type RespWxTextMessage struct {
XMLName xml.Name `xml:"xml"`
ToUserName CdataString `xml:"ToUserName"`
FromUserName CdataString `xml:"FromUserName"`
CreateTime int64 `xml:"CreateTime"`
MsgType CdataString `xml:"MsgType"`
Content CdataString `xml:"Content"`
}
/ / accept Wechat message function
func WxMessageHandler (rw http.ResponseWriter, req * http.Request) {
fmt.Println("WxMessageHandler[+]")
var retByte []byte
for loop := true; loop; loop=false {
//
if (!checkMessage(req)) {
break;
}
//
message, err := getMessage(req)
if err != nil {
break;
}
//
retMessage, err := routeTaskHandler(message)
if err != nil {
break
}
retByte, err = xml.MarshalIndent(retMessage, "", " ")
if err != nil {
break
}
}
fmt.Println("WxMessageHandler[-] info=", string(retByte))
fmt.Fprintf(rw, "%v", string(retByte))
}
/ / Distribution function
func routeTaskHandler (message ReqWxMessage) (ret interface {}, err error) {
switch message.MsgType.Value {
case "text": //
ret, err = replyTextMessageHandler(message);
default:
ret, err = replyTextMessageHandler(message);
}
return
}
/ / text message reply
func replyTextMessageHandler (text ReqWxMessage) (ret RespWxTextMessage, err error) {
ret.ToUserName = CdataString{ Value: "zhangbo04"}
ret.FromUserName = CdataString{ Value: "zhangbo04"}
ret.CreateTime = time.Now().Unix()
ret.MsgType = CdataString{ Value: "text"}
ret.Content = CdataString{ Value: ""}
return
}
/ / verify whether Wechat is a message passed from Wechat
func checkMessage (req * http.Request) bool {/ p >
signature := req.URL.Query().Get("signature")
timestamp := req.URL.Query().Get("timestamp")
nonce := req.URL.Query().Get("nonce")
list := []string{WXMESSAGETOKEN, timestamp, nonce}
sort.Strings(list)
//
t := sha1.New();
for _, values := range list {
io.WriteString(t,values)
}
checkInfo := fmt.Sprintf("%x",t.Sum(nil))
if checkInfo == signature {
return true;
} else {
return false;
}
}
/ / read the message sent by Wechat
func getMessage (req * http.Request) (info ReqWxMessage, err error) {
// post
body,err :=ioutil.ReadAll(req.Body)
if err != nil {
return
}
if len(body) == 0 {
return
}
//xml
err = xml.Unmarshal(body, &info)
if err != nil {
return
}
return
}
4. The server log is printed as
WxMessageHandler [+]
WxMessageHandler [-] info= < xml >
<ToUserName><![CDATA[zhangbo04]]></ToUserName>
<FromUserName><![CDATA[zhangbo04]]></FromUserName>
<CreateTime>1528358735</CreateTime>
<MsgType><![CDATA[text]]></MsgType>
<Content><![CDATA[]]></Content>
< / xml >