使用 UniApp 實現(xiàn)小程序的微信登錄功能
1.微信登錄思路:
- 在main.js 中封裝公共函數(shù),用于判斷用戶是否登錄
- 在main.js 中分定義全局變量,用于存儲接口地址
- 如果沒有登錄、則跳轉(zhuǎn)至登錄頁面
- 進入登錄頁面
- 通過 wx.login 獲取用戶的 code
- 通過 code 獲取用戶的 SessionKey、OpenId 等信息【本應(yīng)后臺接口、但是此處使用js發(fā)送請求】
- 通過 openId 調(diào)用后臺 Api 獲取用戶的信息
- 獲取成功,則說明已經(jīng)授權(quán)過了,直接登錄成功
- 獲取失敗,則說明沒有授權(quán)過,需要授權(quán)之后才能進行登錄
- 用戶點擊頁面微信登錄按鈕【 <button open-type="getUserInfo"></button>】
- 獲取用戶數(shù)據(jù),然后調(diào)用后臺接口寫入數(shù)據(jù)庫
2.在 applets/main.js 中添加如下
// 封裝全局登錄函數(shù)
// backpage, backtype 2個參數(shù)分別代表:
// backpage : 登錄后返回的頁面
// backtype : 打開頁面的類型[1 : redirectTo 2 : switchTab]
Vue.prototype.checkLogin = function( backpage, backtype ){
// 同步獲取本地數(shù)據(jù)(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 == ''){
// 使用重定向的方式跳轉(zhuǎn)至登錄頁面
uni.redirectTo({url:'../login/login?backpage='+backpage+'&backtype='+backtype});
return false;
}
// 登錄成功、已經(jīng)登錄返回數(shù)組 [用戶 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>申請獲取以下權(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ù)到后臺、寫入數(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傳遞到后臺置換用戶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 判斷用戶是否授權(quán)
uni.request({
url: _self.apiServer + 'loginApplets',
data: {
openid: _self.openId
},
method: 'POST',
success: openIdRes => {
console.log(openIdRes);
// 隱藏loading
uni.hideLoading();
// 還沒授權(quán)登錄、請先授權(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
//默認加載
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', '');
// 驗證數(shù)據(jù)
$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]);
}
// 根據(jù) openid 判斷是否存在
$where['u_openid'] = $data['u_openid'];
$user = $userInfo->selOne($where);
if (!$user) {
return json(['code' => 1, 'msg' => '還沒授權(quán)登錄、請先授權(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', '');
// 驗證數(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 格式錯誤',
'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]);
}
// 根據(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' => '注冊失敗,返回重試', 'res' => null]);
}
return json(['code' => 0, 'msg' => 'ok', 'res' => $res]);
}
總結(jié)
到此這篇關(guān)于使用 UniApp 實現(xiàn)小程序的微信登錄的文章就介紹到這了,更多相關(guān)使用 UniApp 實現(xiàn)小程序的微信登錄內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
微信小程序教程系列之頁面跳轉(zhuǎn)和參數(shù)傳遞(6)
這篇文章主要為大家詳細介紹了微信小程序教程系列之頁面跳轉(zhuǎn)和參數(shù)傳遞,微信小程序提供了3種頁面跳轉(zhuǎn)方法,具有一定的參考價值,感興趣的小伙伴們可以參考一下2017-04-04
才發(fā)現(xiàn)的超鏈接js導(dǎo)致網(wǎng)頁中GIF動畫停止的解決方法
才發(fā)現(xiàn)的超鏈接js導(dǎo)致網(wǎng)頁中GIF動畫停止的解決方法...2007-11-11
bootstrap基本配置_動力節(jié)點Java學(xué)院整理
這篇文章主要介紹了bootstrap基本配置,詳細講解如何下載并安裝 Bootstrap,討論 Bootstrap 文件結(jié)構(gòu),并通過一個實例演示它的用法。2017-07-07
符合W3C網(wǎng)頁標(biāo)準(zhǔn)的iframe標(biāo)簽的使用方法
符合W3C網(wǎng)頁標(biāo)準(zhǔn)的iframe標(biāo)簽的使用方法...2007-07-07

