微信公众号授权

147 阅读1分钟

今天先来聊聊微信公众号鉴权,官方文档

服务鉴权

按照文档描述,在公众号与服务器关联时,需要一个GET请求的接口返回echostr值即可。

r.GET("/", func(c *gin.Context) {
		// 声明接收的变量
		wxPublic := &WxPublic{
			Signature: c.Query("signature"),
			Timestamp: c.Query("timestamp"),
			Nonce:     c.Query("nonce"),
			Echostr:   c.Query("echostr"),
		}
		if wxPublic.Signature == "" {
			c.String(http.StatusOK, "hello, NO Signature")
			return
		}
		c.String(http.StatusOK, wxPublic.Echostr)
	})

公众号信息处理

当用户发信息给我们的公众号,希望公众号做出不同的处理。按照文档描述,需要一个POST请求的接口即可,例如:

	r.POST("/", func(c *gin.Context) {
		data, _ := ioutil.ReadAll(c.Request.Body)
		var publicMsg PublicMsg
		if err := xml.Unmarshal(data, &publicMsg); err != nil {
			c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		}
		fmt.Println("post publicMsg==", publicMsg)
		// 限制一个用户 5 分钟内只能申请一个
		has, txt := datasource.GetRedisByString(publicMsg.FromUserName)
		if publicMsg.MsgType == "text" && publicMsg.Content == "体验码" && has == false && txt == "empty" {
		    ...
			replyText := formatPbTxtMsg(&publicMsg, fmt.Sprintf("您好,%v: %v ,时效5分钟.感谢使用.", desc, key))
			c.String(http.StatusOK, replyText)
		}
	})

最后

这就是用gin简单的服务并于公众号关联上。