本文介紹在使用uniapp開發(fā)的H5、小程序和App中使用微信授權(quán)登錄的方法。
由于微信的公眾號(hào)、小程序和App是相對(duì)獨(dú)立的體系,同一個(gè)用戶在這些不同的端中授權(quán)所返回的openid是不一樣的,這個(gè)時(shí)候就必須在微信開放平臺(tái)注冊(cè)賬號(hào),并把對(duì)應(yīng)的公眾號(hào)、小程序和移動(dòng)應(yīng)用綁定上去,在授權(quán)的時(shí)候就能返回一個(gè)unionid了,這樣就可以在后臺(tái)識(shí)別到是同一個(gè)用戶了。
前期要準(zhǔn)備的工作:
1、申請(qǐng)公眾號(hào)、小程序和微信開放平臺(tái),并拿到對(duì)應(yīng)平臺(tái)的appid和secret;
2、H5網(wǎng)頁授權(quán)還要在公眾號(hào)后臺(tái)設(shè)置網(wǎng)頁授權(quán)域名;
3、小程序的接口域名必須啟用https,且要設(shè)置request、download合法域名等;
4、App必須在微信開放平臺(tái)申請(qǐng)應(yīng)用并綁定。
上述工作準(zhǔn)備好后,就可以開干了!
一、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 = '公眾號(hào)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: '請(qǐng)?jiān)谖⑿胖写蜷_',
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、公眾號(hào)授權(quán)scope有兩種方式:snsapi_base和snsapi_userinfo,前者靜默授權(quán)不會(huì)有授權(quán)彈窗,后者必須用戶點(diǎn)擊授權(quán)彈窗按鈕授權(quán)才行;
2、網(wǎng)頁授權(quán)是需要跳轉(zhuǎn)到微信服務(wù)器上,然后攜帶code再跳回來,所以在跳回來后還需要用到的變量比如scope必須用緩存保存起來,否則會(huì)讀取不到;
3、跳轉(zhuǎn)回來的頁面就是發(fā)起授權(quán)的頁面,所以在頁面的onload方法中要判斷url是否攜帶有code,避免重復(fù)跳轉(zhuǎn)授權(quán)的死循環(huán)(會(huì)提示code已被使用);
4、授權(quán)后拿code去后臺(tái)通過微信請(qǐng)求換取用戶信息。
二、小程序授權(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)后會(huì)得到code和userInfo,里面有昵稱、頭像、性別、地域等字段,沒有openid;
2、把code和userInfo傳回后臺(tái),再通過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,此時(shí)直接調(diào)用uni.getUserInfo方法即可直接在前端獲取到用戶信息。但此方式有個(gè)問題,即必須把App的secret配置在manifest.json文件當(dāng)中,并且會(huì)被打包進(jìn)apk/ipa中,存在泄漏的風(fēng)險(xiǎn)!所以不推薦此種方式;
2、第二種是onlyAuthorize設(shè)置為true,則uni.login只返回code,跟小程序一樣傳到后臺(tái)去換取用戶信息。
// 后臺(tái)代碼
public function login()
{
$params = $this->request->param();
switch ($params['type']) {
case '1': // 公眾號(hào)
$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']
];
// 判斷是否需要注冊(cè)或更新數(shù)據(jù)
if ($wechat_member) {
// 如果該用戶已經(jīng)存在,則只更新數(shù)據(jù)
} else {
// 否則的話先用unionid判斷有無其他微信記錄,再進(jìn)行更新或注冊(cè)
}
} 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']
];
// 判斷是否需要注冊(cè)或更新數(shù)據(jù)
if ($wechat_member) {
// 如果該用戶已經(jīng)存在,則只更新數(shù)據(jù)
} else {
// 否則的話先用unionid判斷有無其他微信記錄,再進(jìn)行更新或注冊(cè)
}
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']
];
}
// 判斷是否需要注冊(cè)或更新數(shù)據(jù)
if ($wechat_member) {
// 如果該用戶已經(jīng)存在,則只更新數(shù)據(jù)
} else {
// 否則的話先用unionid判斷有無其他微信記錄,再進(jìn)行更新或注冊(cè)
}
break;
}
}
至此,微信公眾號(hào)H5、小程序和App授權(quán)登錄全部流程結(jié)束。
轉(zhuǎn)載自王維的博客: https://asyou.github.io/content/43.html