微信小程序(uniapp)授权登录

1. 开发前准备

2. 前端开发

    初始化openId和sessionKey
    “授权”按钮(必须添加open-type=“getUserInfo”)
<button
	:disabled="btnLoading"
	:loading="btnLoading"
	class="wechat-auth-btn"
	open-type="getUserInfo"
	@tap="authClickHandle"
>
	<image class="image" :src="wechatLogo"/>
</button>
    点击“授权”按钮拉起授权
getUserProfile_MP() {
          
   
	const _this = this;
	
	wx.getUserProfile({
          
   
		//desc的长度不能超过30个字符
		desc: "同意授权查看附近更多商户",
		success: res => {
          
   
			console.log(res=======>, res)
			if (res.errMsg === getUserProfile:ok && res.encryptedData) {
          
   
				//获取用户信息
				_this.getUserInfo_MP(res);
			}
		},
		fail: res => {
          
   
			//拒绝授权
			console.log(失败, JSON.stringify(res));
			_this.btnLoading = false;
			_this.$mHelper.toast(授权失败);
			return;
		}
	});
},
//小程序获取用户信息
getUserInfo_MP(res) {
          
   
	const _this = this;
	
	wx.showLoading({
          
   title: 正在登录...});
	_this.$http.post(mpWechatAuth, {
          
   
		wechatUser: res.userInfo,
		miniName: mpshop,
		iv: res.iv,
		..._this.wechat,
		unionId: ,
		signature: res.signature
	}).then(async result => {
          
   
		console.log(授权结果==========>, result);
		wx.hideLoading();
		_this.btnLoading = false;
		const user = result.data;
		if (200 === result.code && user.accessToken) {
          
   
			_this.$mHelper.toast(授权登录成功);
			//重定向到首页(这句话放到后面,就不能跳转了)
			if (!user.mobile) {
          
   
				//如果之前未绑定过手机号了(也就是手机号为空),进入绑定手机号页码
				_this.$mRouter.push({
          
   route: /pages/public/bind-mobile});
			} else {
          
   
				//如果之前已经绑定过手机号了(也就是手机号不为空),进入首页
				_this.$mRouter.reLaunch({
          
   route: /pages/index/index});
			}
			//把登录数据保存
			_this.$mStore.commit(login, user); 
		}
	}).catch(() => {
          
   
		_this.btnLoading = false;
	});
}

3. 后端开发

    根据code获取openId和sessionKey
    授权操作(其实没什么操作)
public ResponseResult mpAuth(WechatMPAuthBean query) {
          
   
	//TODO 授权在前端已经完成,业务操作

	return new ResponseResult();   
}
    WechatBean
经验分享 程序员 微信小程序 职场和发展