package main import ( "fmt" "html/template" "log" "net/http" "blog.bing89.com/go/wechat/wechat" "github.com/gin-gonic/gin" ) const ( appID = "wxc39301065b66300c" secret = "7fee3a1cba8c555cf6c4caec4f05844c" token = "qwertyuiopasdfghjkl" Secret = "0a05cb757a9e4fdc9b1aac4f0406a3df" Appid = "wx2fa7fb238aa6896a" Encodingaeskey = "Lw2YDq9Svzhi5HeTzldcG5ID7rlgsJkQ5tDv8wwa092" ) type Server struct { w *wechat.Wechat users map[string]*wechat.UserInfo } func NewServer() (*Server, error) { w, err := wechat.NewWechat(Appid, Secret) if err != nil { return nil, err } s := Server{ w: w, users: make(map[string]*wechat.UserInfo), } return &s, nil } func (s *Server) Check(c *gin.Context) { me := &wechat.MessageEntity{} me.Signature = c.Query("signature") me.Timestamp = c.Query("timestamp") me.Nonce = c.Query("nonce") me.EchoStr = c.Query("echostr") log.Println("signature:", me.Signature, "timestamp:", me.Timestamp, "noce:", me.Nonce, "echostr:", me.EchoStr) if !me.CheckSignature(token) { log.Println("token is not ok") c.AbortWithError(http.StatusForbidden, fmt.Errorf("token invalid")) return } c.Set("echostr", me.EchoStr) c.Next() } //// func cdata(data string) string { return fmt.Sprintf(``, data) } func (s *Server) handleGet(c *gin.Context) { echoStr := c.GetString("echostr") log.Println("token is ok") c.String(http.StatusOK, echoStr) } //关注 func (s *Server) handlePost(c *gin.Context) { data := wechat.FoucsRequest{} err := c.BindXML(&data) if err != nil { log.Println(err) } log.Println("data: ", data) openID := c.Query("openid") log.Println("openid is ", openID) res, err := s.w.SendText(data.FromUserName, "welcome to xk.design.") log.Printf("res: %s\nerr:%v", string(res), err) ui, err := s.w.GetUserInfo(data.FromUserName) if err == nil { s.users[ui.OpenID] = ui ui.Show() } if err != nil { log.Printf("get ui err:%v", err) } c.String(http.StatusOK, "success") } func (s *Server) handlePut(c *gin.Context) { data := wechat.FoucsRequest{} err := c.BindXML(&data) if err != nil { log.Println(err) } log.Println("data: ", data) c.String(http.StatusOK, "success") } func (s *Server) handleDelete(c *gin.Context) { data := wechat.FoucsRequest{} err := c.BindXML(&data) if err != nil { log.Println(err) } log.Println("data: ", data) c.String(http.StatusOK, "success") } //@router /auth/login func (s *Server) login(c *gin.Context) { code := c.Query("code") if code == "" { c.AbortWithError(http.StatusBadRequest, fmt.Errorf("no code")) return } ticket, err := s.w.CreateQRCode() if err != nil { } log.Printf("ticket: %s\nurl: %s\n err:%v\n", ticket.Ticket, ticket.URL, ticket.ExpireSeconds) log.Println("==========> code is: ", code) c.HTML(http.StatusOK, "next", gin.H{"next": template.HTML(ticket.URL)}) } func (s *Server) Template(name string) *template.Template { tmpl := template.New(name) tmpl.Parse(s.html()) return tmpl } func (s *Server) html() string { return `