2021-07-06 16:36:58

golang echo框架,微信小程序登录

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}
	// https: //developers.weixin.qq.com/miniprogram/dev/api-backend/open-api/login/auth.code2Session.html
	resp, err := client.Get("https://api.weixin.qq.com/sns/jscode2session?appid=" + 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()))
	}
	// 判断 openid 是否存在
	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,
		// RoleId: mod.RoleId,
		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))
}

本文链接:https://blog.kingxues.com/post/golang-mpg-login.html

-- EOF --

Comments