uniapp微信小程序登录

605 阅读1分钟

使用uniapp开发微信小程序,实现授权登录仅需三步即可完成登录流程。

1.拉起用户授权协议框

				uni.getUserProfile({
					desc: '用于完善会员资料',
					success: function(weixinRes) {
						that.login(weixinRes.userInfo)
					}
				})

2.发起登录请求获取code授权码

				uni.getUserProfile({
					desc: '用于完善会员资料',
					success: function(weixinRes) {
						that.login(weixinRes.userInfo)
					}
				})
  1. 通过code授权码 换取 微信小程序唯一身份标识ID,调用 auth.code2Session 接口,换取OpenID/UnionID (UnionID需要当前小程序已绑定到微信开放平台账号)。
package services

import (
	"github.com/go-resty/resty/v2"
)

type wechatApp struct{}

const (
	// 微信公众号的appid和secret 测试账号
	WechatAppAppid             = "wxad50d3b12eb5f40c"
	WechatAppSecret            = "59c51e321dfba607d1ae9af2c2f9298f"
	WechatAppTokenAPI          = "https://api.weixin.qq.com/cgi-bin/token"
	WechatAppJscode2sessionAPI = "https://api.weixin.qq.com/sns/jscode2session"
)

type WechatAppAccessToken struct {
	AccessToken string `json:"access_token"`
	ExpiresIn   int    `json:"expires_in"`
}

type WechatAppJscode2session struct {
	SessionKey string `json:"session_key"`
	Unionid    string `json:"unionid"`
	Errmsg     string `json:"errmsg"`
	Openid     string `json:"openid"`
	Errcode    string `json:"errcode"`
}

func NewWechatApp() *wechatApp {
	return &wechatApp{}
}

func (s *wechatApp) GetAccessToken() (accessToken string, err error) {
	client := resty.New()
	params := map[string]string{
		"grant_type": "client_credential",
		"appid":      WechatAppAppid,
		"secret":     WechatAppSecret,
	}

	resp, err := client.R().SetQueryParams(params).SetResult(&WechatAppAccessToken{}).Get(WechatAppTokenAPI)
	if err == nil {
		return resp.Result().(*WechatAppAccessToken).AccessToken, nil
	}

	return
}

func (s *wechatApp) Code2Session(code string) (result *WechatAppJscode2session, err error) {
	client := resty.New()
	params := map[string]string{
		"appid":      WechatAppAppid,
		"secret":     WechatAppSecret,
		"js_code":    code,
		"grant_type": "authorization_code",
	}

	resp, err := client.R().SetQueryParams(params).SetResult(&WechatAppJscode2session{}).Get(WechatAppJscode2sessionAPI)
	if err == nil {
		return resp.Result().(*WechatAppJscode2session), nil
	}

	return
}