kefu/controller/openid.go

43 lines
1.1 KiB
Go

package controller
import (
"github.com/gin-gonic/gin"
"kefu/lib"
"kefu/models"
"kefu/service"
"kefu/tools"
"kefu/types"
"log"
)
func GetWechatOpenid(c *gin.Context) {
redirectUrl := c.Query("redirect")
openId := ""
entId := models.FindConfig("SystemBussinesId")
wechatConfig, _ := lib.NewWechatLib(entId)
weixinCode := c.Query("code")
if weixinCode != "" {
userInfo, err := service.GetWechatUserInfo(weixinCode, entId)
if err == nil {
openId = userInfo.OpenID
} else {
log.Println("微信公众号网页授权错误:", err)
}
} else {
wechatUrl := "https://open.weixin.qq.com/connect/oauth2/authorize?appid=" + wechatConfig.AppId + "&redirect_uri=" + wechatConfig.WechatHost + "/api/v2/wechatOpenid?redirect=" + redirectUrl + "&response_type=code&scope=snsapi_userinfo#wechat_redirect"
c.Redirect(302, wechatUrl)
return
}
if redirectUrl == "" || openId == "" {
c.JSON(200, gin.H{
"code": types.ApiCode.FAILED,
"msg": "获取openid失败或回调地址为空",
})
return
}
redirectUrl = tools.UrlDecode(redirectUrl)
c.Redirect(302, redirectUrl+"&open_id="+openId)
}