欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

使用 UniApp 实现小程序的微信登录功能

程序员文章站 2024-01-17 14:24:22
1.微信登录思路: 在main.js 中封装公共函数,用于判断用户是否登录 在main.js 中分定义全局变量,用于存储接口地址 如果没有登录、则跳转至登录页面 进入登录页面 通过 wx.l...

1.微信登录思路:

  • 在main.js 中封装公共函数,用于判断用户是否登录
  • 在main.js 中分定义全局变量,用于存储接口地址
  • 如果没有登录、则跳转至登录页面
  • 进入登录页面
  • 通过 wx.login 获取用户的 code
  • 通过 code 获取用户的 sessionkey、openid 等信息【本应后台接口、但是此处使用js发送请求】
  • 通过 openid 调用后台 api 获取用户的信息
  • 获取成功,则说明已经授权过了,直接登录成功
  • 获取失败,则说明没有授权过,需要授权之后才能进行登录
  • 用户点击页面微信登录按钮【 <button open-type="getuserinfo"></button>】
  • 获取用户数据,然后调用后台接口写入数据库

2.在 applets/main.js 中添加如下

// 封装全局登录函数
// backpage, backtype 2个参数分别代表:
// backpage : 登录后返回的页面
// backtype : 打开页面的类型[1 : redirectto 2 : switchtab]
vue.prototype.checklogin = function( backpage, backtype ){
	// 同步获取本地数据(uid、随机码、用户名、头像)
	var user_id = uni.getstoragesync('user_id');
	var user_nu = uni.getstoragesync('user_nu');
	var user_nm = uni.getstoragesync('user_nm');
	var user_fa = uni.getstoragesync('user_fa');
	if( user_id == '' || user_nu == '' || user_fa == ''){
		// 使用重定向的方式跳转至登录页面
		uni.redirectto({url:'../login/login?backpage='+backpage+'&backtype='+backtype});
		return false;
	}
	// 登录成功、已经登录返回数组 [用户 id, 用户随机码, 用户昵称, 用户表情]
	return [user_id, user_nu, user_nm, user_fa];
}
// 定义一个全局的请求地址
vue.prototype.apiserver = 'http://0608.cc/'

3.在 pages/login/login.vue 中添加如下

<template>
	<view>
		<!-- login view html start -->
		<view>
			<view>
				<view class="header"><image src="/static/img/public/login-wx.png"></image></view>
				<view class="content">
					<view>申请获取以下权限</view>
					<text>获得你的公开信息(昵称,头像、地区等)</text>
				</view>
				<button class="bottom" type="primary" open-type="getuserinfo" withcredentials="true" lang="zh_cn" @getuserinfo="wxgetuserinfo">授权登录</button>
			</view>
		</view>
		<!-- login view html end -->
	</view>
</template>

<script>
export default {
	data() {
		return {
			appid: '*************',
			secret: '*************************',
			code: '',
			sessionkey: '',
			openid: '',
			userinfo: {
				avatarurl: '',
				city: '',
				country: '',
				gender: 1,
				language: '',
				nickname: ''
			},
			pageoption: {}
		};
	},
	methods: {
		// 第一授权获取用户信息 ===》按钮触发
		wxgetuserinfo() {
			let _self = this;
			// 1.获取用户的信息
			uni.getuserinfo({
				provider: 'weixin',
				success: ( infores ) => {
					console.log( infores )
					_self.userinfo = infores.userinfo
					// 2.提交数据到后台、写入数据库
					uni.request({
						url: _self.apiserver + 'appletsuserinfo',
						data: {
							openid: _self.openid,
							avatarurl: _self.userinfo.avatarurl,
							city: _self.userinfo.city,
							country: _self.userinfo.country,
							gender: _self.userinfo.gender,
							language: _self.userinfo.language,
							nickname: _self.userinfo.nickname
						},
						method: 'post',
						success: res => {
							if( res.data.code != 0 )
							{
								uni.showtoast({ title: res.data.msg, icon: 'none' });
								return false;
							}
							// 用户信息写入缓存
							uni.showtoast({title: '登录成功'})
							uni.setstoragesync( 'user_id', res.data.res.u_id );
							uni.setstoragesync( 'user_nm', res.data.res.u_nickname );
							uni.setstoragesync( 'user_fa', res.data.res.u_avatarurl );
							uni.setstoragesync( 'user_nu', res.data.res.u_regtime );
							// 然后跳回原页面
							if( _self.pageoption.backtype == 1 )
							{
								uni.redirectto({ url: _self.pageoption.backpage })
							}else{
								uni.switchtab({ url: _self.pageoption.backpage })
							}
						},
						fail: () => {
							uni.showtoast({ title: '用户信息操作失败', icon: 'none' });
						}
					});
				},
				fail: () => {
					uni.showtoast({ title: '获取用户信息失败', icon: 'none' });
				}
			});
			return false
		},
		// 登录
		login() {
			let _self = this;

			// 0. 显示加载的效果
			uni.showloading({
				title: '登录中...'
			});

			// 1. wx 获取登录用户 code
			uni.login({
				provider: 'weixin',
				success: loginres => {
					console.log(loginres);
					_self.code = loginres.code;
					// 2. 将用户登录code传递到后台置换用户sessionkey、openid等信息
					uni.request({
						url:
							'https://api.weixin.qq.com/sns/jscode2session?appid=' +
							_self.appid +
							'&secret=' +
							_self.secret +
							'&js_code=' +
							_self.code +
							'&grant_type=authorization_code',
						success: coderes => {
							console.log(coderes);
							_self.openid = coderes.data.openid;
							_self.sessionkey = coderes.data.session_key;
							// 3.通过 openid 判断用户是否授权
							uni.request({
								url: _self.apiserver + 'loginapplets',
								data: {
									openid: _self.openid
								},
								method: 'post',
								success: openidres => {
									console.log(openidres);
									// 隐藏loading
									uni.hideloading();
									// 还没授权登录、请先授权然后登录
									if (openidres.data.code == 1) {
										// 提示消息、让用户授权
										uni.showtoast({ title: openidres.data.msg, icon: 'none' });
									}
									// 已经授权了、查询到用户的数据了
									if (openidres.data.code == 0) {
										// 用户信息写入缓存
										uni.showtoast({title: '登录成功'})
										uni.setstoragesync( 'user_id', openidres.data.res.u_id );
										uni.setstoragesync( 'user_nm', openidres.data.res.u_nickname );
										uni.setstoragesync( 'user_fa', openidres.data.res.u_avatarurl );
										uni.setstoragesync( 'user_nu', openidres.data.res.u_regtime );
										// 然后跳回原页面
										if( _self.pageoption.backtype == 1 )
										{
											uni.redirectto({ url: _self.pageoption.backpage })
										}else{
											uni.switchtab({ url: _self.pageoption.backpage })
										}
									}
								},
								fail: () => {
									uni.showtoast({ title: '获取授权信息失败', icon: 'none' });
									return false;
								}
							});
						},
						fail: () => {
							uni.showtoast({ title: '获取 sesssionkey openid 失败', icon: 'none' });
							return false;
						}
					});
				},
				fail: () => {
					uni.showtoast({ title: '获取 code 失败', icon: 'none' });
					return false;
				}
			});
			return false;
		}
	},
	onload( options ) {
		// 接收跳转的参数
		this.pageoption = options
		//默认加载
		this.login();
	}
};
</script>

<style>
.header {
	margin: 90rpx 0 90rpx 50rpx;
	border-bottom: 1px solid #ccc;
	text-align: center;
	width: 650rpx;
	height: 300rpx;
	line-height: 450rpx;
}

.header image {
	width: 200rpx;
	height: 200rpx;
}

.content {
	margin-left: 50rpx;
	margin-bottom: 90rpx;
}

.content text {
	display: block;
	color: #9d9d9d;
	margin-top: 40rpx;
}

.bottom {
	border-radius: 80rpx;
	margin: 70rpx 50rpx;
	font-size: 35rpx;
}
</style>

在 pages/my/my.vue 中添加如下:

<template>
	<view>我的页面</view>
</template>

<script>
var loginres;
export default {
	data() {
		return {};
	},
	onload() {
		// 加载定义好的方法
		loginres = this.checklogin('../my/my', 2);
		// 没有登录成功,返回空
		if (!loginres) {
			return;
		}
	},
	methods: {}
};
</script>

<style></style>

5.php 接口 loginapplets

public function loginapplets(request $request, userinfo $userinfo)
{
 // 获取数据
 $data['u_openid'] = $request->param('openid', '');
 // 验证数据
 $rule = [
  'u_openid' => 'require|max:200|min:10'
 ];
 $message = [
  'u_openid.require' => 'openid 不能为空',
  'u_openid.max'  => 'openid 格式错误',
  'u_openid.min'  => 'openid 格式错误'
 ];
 $validate = validate::rule($rule)->message($message);
 if (!$validate->check($data)) {
  return json(['code' => 1, 'msg' => $validate->geterror(), 'res' => null]);
 }
 // 根据 openid 判断是否存在
 $where['u_openid'] = $data['u_openid'];
 $user = $userinfo->selone($where);
 if (!$user) {
  return json(['code' => 1, 'msg' => '还没授权登录、请先授权然后登录', 'res' => $user]);
 }
 return json(['code' => 0, 'msg' => '已授权获取到用户的数据', 'res' => $user]);
}

6.php 接口 appletsuserinfo

public function appletsuserinfo(request $request, userinfo $userinfo)
{
 // 获取数据
 $data['u_openid'] = $request->param('openid', '');
 $data['u_avatarurl'] = $request->param('avatarurl', '');
 $data['u_city'] = $request->param('city', '');
 $data['u_country'] = $request->param('country', '');
 $data['u_gender'] = $request->param('gender', '');
 $data['u_language'] = $request->param('language', '');
 $data['u_nickname'] = $request->param('nickname', '');
 // 验证数据
 $rule = [
  'u_openid' => 'require|max:200|min:10',
  'u_avatarurl' => 'require',
  'u_nickname' => 'require'
 ];
 $message = [
  'u_openid.require'  => 'openid 不能为空',
  'u_openid.max'   => 'openid 格式错误',
  'u_openid.min'   => 'openid 格式错误',
  'u_avatarurl.require' => '用户头像 不能为空',
  'u_nickname.max'  => '用户名 格式错误',
 ];
 $validate = validate::rule($rule)->message($message);
 if (!$validate->check($data)) {
  return json(['code' => 1, 'msg' => $validate->geterror(), 'res' => null]);
 }

 // 根据 openid 判断是否存在
 $where['u_openid'] = $data['u_openid'];
 $user = $userinfo->selone($where);

 // 存在、执行修改
 if ($user) {
  $user_res = $userinfo->updone($where, $data);
  $res = [];
  $res['u_id'] = $user['u_id'];
  $res['u_regtime'] = $user['u_regtime'];
 }

 // 不存在、执行添加
 if (empty($user)) {
  $res = [];
  $res = $data;
  $res['u_regtime'] = time();
  $res['u_id'] = $userinfo->addone($res);
 }

 // 判断是否添加成功
 if (empty($res['u_id'])) {
  return json(['code' => 1, 'msg' => '注册失败,返回重试', 'res' => null]);
 }
 return json(['code' => 0, 'msg' => 'ok', 'res' => $res]);
}

总结

到此这篇关于使用 uniapp 实现小程序的微信登录的文章就介绍到这了,更多相关使用 uniapp 实现小程序的微信登录内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!