package controllers import ( NatsSwever "Wx_MP/Nats/Server" "Wx_MP/lib" "Wx_MP/logs" "crypto/sha1" "encoding/xml" "fmt" beego "github.com/beego/beego/v2/server/web" "io" "sort" "strings" "time" ) type WxController struct { beego.Controller } // 列表 - http://cloud.hoooooo.cn/ func (c *WxController) Wx_handler() { // c.Ctx.Input.RequestBody beego 无法获取RequestBody 里的内容 //conf文件内增加: //copyrequestbody = true logs.Println("RequestBody-", string(c.Ctx.Input.RequestBody)) //var ob map[string]interface{} //var err error //if err = json.Unmarshal(c.Ctx.Input.RequestBody, &ob); err == nil { // //} else { // //} if strings.Contains(string(c.Ctx.Input.RequestBody), "failed") { logs.PrintlnE("RequestBody-", string(c.Ctx.Input.RequestBody)) } Reply_Content := "" var Person_xml lib.Person_Xml err := xml.Unmarshal(c.Ctx.Input.RequestBody, &Person_xml) if err != nil { logs.PrintlnE("!!!!!微信消息 xml.Unmarshal 解析失败") c.Ctx.WriteString("") return } logs.Println("ToUserName:", Person_xml.ToUserName) logs.Println("MsgType:", Person_xml.MsgType) logs.Println("MsgType:", Person_xml.Event) switch Person_xml.MsgType { case "text": Reply_Content = NatsSwever.Wx_BasicMessage_Text(c.Ctx.Input.RequestBody) break case "event": var Person_Event_xml lib.Person_Event_Xml err := xml.Unmarshal(c.Ctx.Input.RequestBody, &Person_Event_xml) if err != nil { logs.PrintlnE("!!!!!微信消息 xml.Unmarshal 解析失败") c.Ctx.WriteString("") return } switch Person_Event_xml.Event { case "subscribe_msg_sent_event": c.Ctx.WriteString("") return } Reply_Content = NatsSwever.Wx_BasicMessage_Event(c.Ctx.Input.RequestBody) break } logs.Println("Reply_Content 回复消息:", Reply_Content) // 回复消息 if len(Reply_Content) == 0 { Reply_Content = "无法识别您的指令" } // 回复消息 必须是 xml type xml struct { ToUserName string FromUserName string CreateTime int64 MsgType string Content string } var p = xml{ ToUserName: Person_xml.FromUserName, FromUserName: Person_xml.ToUserName, CreateTime: time.Now().Unix(), MsgType: "text", Content: Reply_Content, } logs.Println("xml:", p) c.Data["xml"] = &p c.ServeXML() return } // 验证 服务器配置 func (c *WxController) Wx_Verification() { // timestamp := c.GetString("timestamp") nonce := c.GetString("nonce") signatureIn := c.GetString("signature") echostr := c.GetString("echostr") println("timestamp:", timestamp) println("nonce:", nonce) println("signatureIn:", signatureIn) signatureGen := MakeSignature("wxb5b2c9147ae0b9db", timestamp, nonce) println("signatureGen:", signatureGen) //if signatureGen != signatureIn { // return //} c.Ctx.WriteString(echostr) return } func MakeSignature(token, timestamp, nonce string) string { strs := []string{token, timestamp, nonce} sort.Strings(strs) sha := sha1.New() io.WriteString(sha, strings.Join(strs, "")) return fmt.Sprintf("%x", sha.Sum(nil)) }