golang echo框架,微信小程序登录
步骤
- 小程序内,wx.login()获取code
- 小程序内,wx.request() 发送 code
- 服务端通过code获取openid
- 生成登录token
示例代码
func AuthLoginMpg(ctx echo.Context) error {
code := ctx.QueryParam("code")
if code == "" {
return ctx.JSON(utils.ErrIpt("数据输入错误", "请输入code"))
}
client := http.Client{Timeout: 30 * time.Second}
resp, err := client.Get("https://api.weixin.qq.com/sns/jscode2session?appid="toc_ + conf.App.Wechat.MpgAppid + "&secret=" + conf.App.Wechat.MpgSecret + "&js_code=" + code + "&grant_type=authorization_code")
if err != nil {
return ctx.JSON(utils.ErrOpt("链接微信服务出错", err.Error()))
}
defer resp.Body.Close()
decoder := json.NewDecoder(resp.Body)
sess := &wechat.Session{}
err = decoder.Decode(sess)
if err != nil {
return ctx.JSON(utils.ErrOpt("微信数据出错", err.Error()))
}
err = sess.Stat()
if err != nil {
return ctx.JSON(utils.ErrOpt("微信数据出错", err.Error()))
}
mod, has := model.GuestGetOpenid(sess.Openid)
if has {
goto exist
}
mod.OpenId = sess.Openid
mod.Ctime = time.Now()
if err = model.GuestAdd(mod); err != nil {
return ctx.JSON(utils.ErrOpt("登陆失败", err.Error()))
}
exist:
auth := token.Auth{
Id: mod.Id,
ExpAt: time.Now().Add(time.Hour * time.Duration(conf.App.TokenExp)).Unix(),
}
mod.Token = auth.Encode(conf.App.TokenSecret)
return ctx.JSON(utils.Succ("succ", mod.Token))
}
zxysilent
发表于 2021-07-06 16:36:58,最后修改于 2021-07-27 23:29:27
Comments