使用UniApp實(shí)現(xiàn)小程序的微信登錄功能的代碼詳解

這篇文章主要講解了使用UniApp實(shí)現(xiàn)小程序的微信登錄功能的代碼詳解,內(nèi)容清晰明了,對(duì)此有興趣的小伙伴可以學(xué)習(xí)一下,相信大家閱讀完之后會(huì)有幫助。

在醴陵等地區(qū),都構(gòu)建了全面的區(qū)域性戰(zhàn)略布局,加強(qiáng)發(fā)展的系統(tǒng)性、市場前瞻性、產(chǎn)品創(chuàng)新能力,以專注、極致的服務(wù)理念,為客戶提供成都網(wǎng)站制作、網(wǎng)站設(shè)計(jì) 網(wǎng)站設(shè)計(jì)制作定制制作,公司網(wǎng)站建設(shè),企業(yè)網(wǎng)站建設(shè),品牌網(wǎng)站制作,全網(wǎng)整合營銷推廣,外貿(mào)網(wǎng)站建設(shè),醴陵網(wǎng)站建設(shè)費(fèi)用合理。

1.微信登錄思路:

  • 在main.js 中封裝公共函數(shù),用于判斷用戶是否登錄
  • 在main.js 中分定義全局變量,用于存儲(chǔ)接口地址
  • 如果沒有登錄、則跳轉(zhuǎn)至登錄頁面
  • 進(jìn)入登錄頁面
  • 通過 wx.login 獲取用戶的 code
  • 通過 code 獲取用戶的 SessionKey、OpenId 等信息【本應(yīng)后臺(tái)接口、但是此處使用js發(fā)送請(qǐng)求】
  • 通過 openId 調(diào)用后臺(tái) Api 獲取用戶的信息
  • 獲取成功,則說明已經(jīng)授權(quán)過了,直接登錄成功
  • 獲取失敗,則說明沒有授權(quán)過,需要授權(quán)之后才能進(jìn)行登錄
  • 用戶點(diǎn)擊頁面微信登錄按鈕【 <button open-type="getUserInfo"></button>】
  • 獲取用戶數(shù)據(jù),然后調(diào)用后臺(tái)接口寫入數(shù)據(jù)庫

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

// 封裝全局登錄函數(shù)
// backpage, backtype 2個(gè)參數(shù)分別代表:
// backpage : 登錄后返回的頁面
// backtype : 打開頁面的類型[1 : redirectTo 2 : switchTab]
Vue.prototype.checkLogin = function( backpage, backtype ){
	// 同步獲取本地?cái)?shù)據(jù)(uid、隨機(jī)碼、用戶名、頭像)
	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 == ''){
		// 使用重定向的方式跳轉(zhuǎn)至登錄頁面
		uni.redirectTo({url:'../login/login&#63;backpage='+backpage+'&backtype='+backtype});
		return false;
	}
	// 登錄成功、已經(jīng)登錄返回?cái)?shù)組 [用戶 id, 用戶隨機(jī)碼, 用戶昵稱, 用戶表情]
	return [user_id, user_nu, user_nm, user_fa];
}
// 定義一個(gè)全局的請(qǐng)求地址
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>申請(qǐng)獲取以下權(quán)限</view>
					<text>獲得你的公開信息(昵稱,頭像、地區(qū)等)</text>
				</view>
				<button class="bottom" type="primary" open-type="getUserInfo" withCredentials="true" lang="zh_CN" @getuserinfo="wxGetUserInfo">授權(quán)登錄</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: {
		// 第一授權(quán)獲取用戶信息 ===》按鈕觸發(fā)
		wxGetUserInfo() {
			let _self = this;
			// 1.獲取用戶的信息
			uni.getUserInfo({
				provider: 'weixin',
				success: ( infoRes ) => {
					console.log( infoRes )
					_self.userInfo = infoRes.userInfo
					// 2.提交數(shù)據(jù)到后臺(tái)、寫入數(shù)據(jù)庫
					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傳遞到后臺(tái)置換用戶SessionKey、OpenId等信息
					uni.request({
						url:
							'https://api.weixin.qq.com/sns/jscode2session&#63;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 判斷用戶是否授權(quán)
							uni.request({
								url: _self.apiServer + 'loginApplets',
								data: {
									openid: _self.openId
								},
								method: 'POST',
								success: openIdRes => {
									console.log(openIdRes);
									// 隱藏loading
									uni.hideLoading();
									// 還沒授權(quán)登錄、請(qǐng)先授權(quán)然后登錄
									if (openIdRes.data.code == 1) {
										// 提示消息、讓用戶授權(quán)
										uni.showToast({ title: openIdRes.data.msg, icon: 'none' });
									}
									// 已經(jīng)授權(quán)了、查詢到用戶的數(shù)據(jù)了
									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: '獲取授權(quán)信息失敗', 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 ) {
		// 接收跳轉(zhuǎn)的參數(shù)
		this.pageOption = options
		//默認(rèn)加載
		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)
{
 // 獲取數(shù)據(jù)
 $data['u_openid'] = $request->param('openid', '');
 // 驗(yàn)證數(shù)據(jù)
 $rule = [
  'u_openid' => 'require|max:200|min:10'
 ];
 $message = [
  'u_openid.require' => 'openid 不能為空',
  'u_openid.max'  => 'openid 格式錯(cuò)誤',
  'u_openid.min'  => 'openid 格式錯(cuò)誤'
 ];
 $validate = Validate::rule($rule)->message($message);
 if (!$validate->check($data)) {
  return json(['code' => 1, 'msg' => $validate->getError(), 'res' => null]);
 }
 // 根據(jù) openid 判斷是否存在
 $where['u_openid'] = $data['u_openid'];
 $user = $userInfo->selOne($where);
 if (!$user) {
  return json(['code' => 1, 'msg' => '還沒授權(quán)登錄、請(qǐng)先授權(quán)然后登錄', 'res' => $user]);
 }
 return json(['code' => 0, 'msg' => '已授權(quán)獲取到用戶的數(shù)據(jù)', 'res' => $user]);
}

6.PHP 接口 appletsUserInfo

public function appletsUserInfo(Request $request, UserInfo $userInfo)
{
 // 獲取數(shù)據(jù)
 $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', '');
 // 驗(yàn)證數(shù)據(jù)
 $rule = [
  'u_openid' => 'require|max:200|min:10',
  'u_avatarUrl' => 'require',
  'u_nickName' => 'require'
 ];
 $message = [
  'u_openid.require'  => 'openid 不能為空',
  'u_openid.max'   => 'openid 格式錯(cuò)誤',
  'u_openid.min'   => 'openid 格式錯(cuò)誤',
  'u_avatarUrl.require' => '用戶頭像 不能為空',
  'u_nickName.max'  => '用戶名 格式錯(cuò)誤',
 ];
 $validate = Validate::rule($rule)->message($message);
 if (!$validate->check($data)) {
  return json(['code' => 1, 'msg' => $validate->getError(), 'res' => null]);
 }

 // 根據(jù) openid 判斷是否存在
 $where['u_openid'] = $data['u_openid'];
 $user = $userInfo->selOne($where);

 // 存在、執(zhí)行修改
 if ($user) {
  $user_res = $userInfo->updOne($where, $data);
  $res = [];
  $res['u_id'] = $user['u_id'];
  $res['u_regtime'] = $user['u_regtime'];
 }

 // 不存在、執(zhí)行添加
 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' => '注冊(cè)失敗,返回重試', 'res' => null]);
 }
 return json(['code' => 0, 'msg' => 'ok', 'res' => $res]);
}

看完上述內(nèi)容,是不是對(duì)使用UniApp實(shí)現(xiàn)小程序的微信登錄功能的代碼詳解有進(jìn)一步的了解,如果還想學(xué)習(xí)更多內(nèi)容,歡迎關(guān)注創(chuàng)新互聯(lián)行業(yè)資訊頻道。

名稱欄目:使用UniApp實(shí)現(xiàn)小程序的微信登錄功能的代碼詳解
網(wǎng)站地址:http://muchs.cn/article2/gppoic.html

成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供網(wǎng)站排名、網(wǎng)站策劃、商城網(wǎng)站、網(wǎng)頁設(shè)計(jì)公司面包屑導(dǎo)航、Google

廣告

聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請(qǐng)盡快告知,我們將會(huì)在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場,如需處理請(qǐng)聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來源: 創(chuàng)新互聯(lián)

網(wǎng)站優(yōu)化排名