本文介紹在使用uniapp開發(fā)的H5、小程序和App中使用微信授權(quán)登錄的方法婚惫。
由于微信的公眾號氛赐、小程序和App是相對獨立的體系,同一個用戶在這些不同的端中授權(quán)所返回的openid是不一樣的先舷,這個時候就必須在微信開放平臺注冊賬號艰管,并把對應的公眾號、小程序和移動應用綁定上去蒋川,在授權(quán)的時候就能返回一個unionid了牲芋,這樣就可以在后臺識別到是同一個用戶了。
前期要準備的工作:
1捺球、申請公眾號缸浦、小程序和微信開放平臺,并拿到對應平臺的appid和secret氮兵;
2裂逐、H5網(wǎng)頁授權(quán)還要在公眾號后臺設(shè)置網(wǎng)頁授權(quán)域名;
3泣栈、小程序的接口域名必須啟用https卜高,且要設(shè)置request、download合法域名等南片;
4掺涛、App必須在微信開放平臺申請應用并綁定。
上述工作準備好后疼进,就可以開干了薪缆!
一、H5網(wǎng)頁授權(quán)
1颠悬、授權(quán)按鈕
// official.vue
<u-button class="button" type="success" @click="getWeChatCode">立即授權(quán)</u-button>
2矮燎、js代碼
// official.vue
onLoad(options) {
if (options.scope) {
this.scope = options.scope
}
if (this.$wechat && this.$wechat.isWechat()) {
uni.setStorageSync('scope', this.scope)
let code = this.getUrlCode('code')
if (code) {
this.checkWeChatCode(code)
} else {
if (this.scope == 'snsapi_base') {
this.getWeChatCode()
}
}
}
},
methods: {
getUrlCode(name) {
return decodeURIComponent((new RegExp('[?|&]' + name + '=' + '([^&;]+?)(&|#|;|$)').exec(location.href) || [, ''])[1].replace(/\+/g, '%20')) || null
},
getWeChatCode() {
if (this.$wechat && this.$wechat.isWechat()) {
let appid = '公眾號appid'
let local = encodeURIComponent(window.location.href)
let scope = uni.getStorageSync('scope')
window.location.href = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${appid}&redirect_uri=${local}&response_type=code&scope=${scope}&state=1#wechat_redirect`
} else {
uni.showModal({
content: '請在微信中打開',
showCancel: false
})
}
},
checkWeChatCode(code) {
if (code) {
let scope = uni.getStorageSync('scope')
this.$http.post('/wechat/login', {
code,
scope,
type: 1
}).then(res => {
if (res.code == 1) {
if (scope == 'snsapi_userinfo') {
this.login(res.data.userinfo)
uni.navigateBack()
}
} else {
uni.showModal({
content: res.msg,
showCancel: false
})
}
}).catch(err => {
uni.showModal({
content: err.msg,
showCancel: false
})
})
}
}
注意,
1赔癌、公眾號授權(quán)scope有兩種方式:snsapi_base和snsapi_userinfo诞外,前者靜默授權(quán)不會有授權(quán)彈窗,后者必須用戶點擊授權(quán)彈窗按鈕授權(quán)才行灾票;
2峡谊、網(wǎng)頁授權(quán)是需要跳轉(zhuǎn)到微信服務(wù)器上,然后攜帶code再跳回來,所以在跳回來后還需要用到的變量比如scope必須用緩存保存起來既们,否則會讀取不到濒析;
3、跳轉(zhuǎn)回來的頁面就是發(fā)起授權(quán)的頁面啥纸,所以在頁面的onload方法中要判斷url是否攜帶有code号杏,避免重復跳轉(zhuǎn)授權(quán)的死循環(huán)(會提示code已被使用);
4斯棒、授權(quán)后拿code去后臺通過微信請求換取用戶信息盾致。
二、小程序授權(quán)
1荣暮、授權(quán)按鈕庭惜,必須是button,且設(shè)置
// mp.vue
<u-button type="success" @click="getUserProfile()">微信授權(quán)登錄</u-button>
2穗酥、js代碼
getUserProfile() {
uni.getUserProfile({
desc: '使用微信登錄',
lang: 'zh_CN',
success: (a) => {
uni.login({
provider: 'weixin',
success: (b) => {
this.loading = true
let userInfo = a.userInfo
userInfo.code = b.code
userInfo.type = 2
this.$http.post('/wechat/login', userInfo).then(c => {
this.loading = false
this.login(c.data.userinfo)
uni.navigateBack()
}).catch(err => {
this.loading = false
uni.showModal({
content: err.msg,
showCancel: false
})
})
},
fail: (err) => {
console.error(err)
}
})
},
fail: (err) => {
console.error(err)
}
})
}
說明:
1护赊、授權(quán)后會得到code和userInfo,里面有昵稱砾跃、頭像骏啰、性別、地域等字段蜓席,沒有openid器一;
2、把code和userInfo傳回后臺厨内,再通過code換取用戶的openid和unionid祈秕。
三、App授權(quán)
1雏胃、授權(quán)按鈕
// app.vue
<u-button class="button" type="success" @click="onAppAuth">確定授權(quán)</u-button>
2请毛、js代碼
// app.vue
onAppAuth() {
uni.getProvider({
service: 'oauth',
success: (a) => {
if (~a.provider.indexOf('weixin')) {
uni.login({
provider: 'weixin',
onlyAuthorize: true, // 注意此參數(shù)
success: (b) => {
if (b.code) {
this.$http.post('/wechat/login', {
code: b.code,
type: 3
}).then(c => {
this.loading = false
this.login(c.data.userinfo)
uni.navigateBack()
}).catch(err => {
this.loading = false
uni.showModal({
content: '授權(quán)登錄失敗',
showCancel: false
})
})
} else {
uni.getUserInfo({
success: (c) => {
this.loading = true
let userInfo = c.userInfo
userInfo.type = 3
this.$http.post('/wechat/login', userInfo).then(d => {
this.loading = false
this.login(d.data.userinfo)
uni.navigateBack()
}).catch(err => {
this.loading = false
uni.showModal({
content: '授權(quán)登錄失敗',
showCancel: false
})
})
},
fail: (err) => {
console.error(err)
}
})
}
},
fail: (err) => {
console.error(err)
}
})
}
},
fail: (err) => {
console.error(err)
}
})
}
注意:微信在App中授權(quán)有兩種方式,
1瞭亮、第一種是uni.login里面的onlyAuthorize為false方仿,此時直接調(diào)用uni.getUserInfo方法即可直接在前端獲取到用戶信息。但此方式有個問題统翩,即必須把App的secret配置在manifest.json文件當中仙蚜,并且會被打包進apk/ipa中,存在泄漏的風險厂汗!所以不推薦此種方式委粉;
2、第二種是onlyAuthorize設(shè)置為true娶桦,則uni.login只返回code贾节,跟小程序一樣傳到后臺去換取用戶信息汁汗。
// 后臺代碼
public function login()
{
$params = $this->request->param();
switch ($params['type']) {
case '1': // 公眾號
$wechat = Config::get('wechat.h5');
$access_token = Http::sendRequest('https://api.weixin.qq.com/sns/oauth2/access_token?appid='.$wechat['appid'].'&secret='.$secret['secret'].'&code='.$params['code'].'&grant_type=authorization_code');
$msg = json_decode($access_token['msg'], true);
if ($params['scope'] == 'snsapi_userinfo') {
$userinfo = Http::sendRequest('https://api.weixin.qq.com/sns/userinfo?access_token='.$msg['access_token'].'&openid='.$msg['openid'].'&lang=zh_CN');
$info = json_decode($userinfo['msg'], true);
$wechat_member = $this->memberModel->field(['user_id','headimgurl'])->where(['openid'=>$info['openid']])->find();
$member = [
'type' => $params['type'],
'unionid' => $info['unionid'],
'openid' => $info['openid'],
'nickname' => $info['nickname'],
'sex' => $info['sex'],
'language' => $info['language'],
'country' => $info['country'],
'province' => $info['province'],
'city' => $info['city'],
'headimgurl' => $info['headimgurl']
];
// 判斷是否需要注冊或更新數(shù)據(jù)
if ($wechat_member) {
// 如果該用戶已經(jīng)存在,則只更新數(shù)據(jù)
} else {
// 否則的話先用unionid判斷有無其他微信記錄栗涂,再進行更新或注冊
}
} else {
$data['openid'] = $info['openid'];
$this->success('獲取成功',$data);
}
break;
case '2': // 小程序
$app = Factory::miniProgram(Config::get('wechat.mini'));
$info = $app->auth->session($params['code']);
$wechat_member = $this->memberModel->field(['user_id','headimgurl'])->where(['openid'=>$info['openid']])->find();
$member = [
'type' => $params['type'],
'unionid' => $info['unionid'],
'openid' => $info['openid'],
'nickname' => $params['nickName'],
'sex' => $params['gender'],
'language' => $params['language'],
'country' => $params['country'],
'province' => $params['province'],
'city' => $params['city'],
'headimgurl' => $params['avatarUrl']
];
// 判斷是否需要注冊或更新數(shù)據(jù)
if ($wechat_member) {
// 如果該用戶已經(jīng)存在知牌,則只更新數(shù)據(jù)
} else {
// 否則的話先用unionid判斷有無其他微信記錄,再進行更新或注冊
}
break;
case '3': // app
if (isset($params['code'])) {
$app = Config::get('wechat.app');
$access_token = Http::sendRequest('https://api.weixin.qq.com/sns/oauth2/access_token?appid='.$app['app_id'].'&secret='.$app['secret'].'&code='.$params['code'].'&grant_type=authorization_code');
$msg = json_decode($access_token['msg'], true);
$wechat_member = $this->memberModel->field(['user_id','headimgurl'])->where(['openid'=>$msg['openid']])->find();
$member = [
'type' => $params['type'],
'unionid' => $msg['unionid'],
'openid' => $msg['openid'],
'nickname' => isset($msg['nickName']) ? $msg['nickName'] : '微信用戶',
'sex' => isset($msg['gender']) ? $msg['gender'] : '0',
'language' => isset($msg['language']) ? $msg['language'] : '',
'country' => isset($msg['country']) ? $msg['country'] : '',
'province' => isset($msg['province']) ? $msg['province'] : '',
'city' => isset($msg['city']) ? $msg['city'] : '',
'headimgurl' => isset($msg['avatarUrl']) ? $msg['avatarUrl'] : ''
];
} else {
$wechat_member = $this->memberModel->field(['user_id','headimgurl'])->where(['openid'=>$params['openId']])->find();
$member = [
'type' => $params['type'],
'unionid' => $params['unionId'],
'openid' => $params['openId'],
'nickname' => $params['nickName'],
'sex' => $params['gender'],
'language' => isset($params['language']) ? $params['language'] : '', // app微信wx.getUserInfo授權(quán)未返回此字段
'country' => $params['country'],
'province' => $params['province'],
'city' => $params['city'],
'headimgurl' => $params['avatarUrl']
];
}
// 判斷是否需要注冊或更新數(shù)據(jù)
if ($wechat_member) {
// 如果該用戶已經(jīng)存在斤程,則只更新數(shù)據(jù)
} else {
// 否則的話先用unionid判斷有無其他微信記錄角寸,再進行更新或注冊
}
break;
}
}
至此,微信公眾號H5忿墅、小程序和App授權(quán)登錄全部流程結(jié)束袭厂。
轉(zhuǎn)載自王維的博客: https://asyou.github.io/content/43.html