本文介绍在使用uniapp开发的H5、小程序和App中使用微信授权登录的方法。
由于微信的公众号、小程序和App是相对独立的体系,同一个用户在这些不同的端中授权所返回的openid是不一样的,这个时候就必须在微信开放平台注册账号,并把对应的公众号、小程序和移动应用绑定上去,在授权的时候就能返回一个unionid了,这样就可以在后台识别到是同一个用户了。
前期要准备的工作:
1、申请公众号、小程序和微信开放平台,并拿到对应平台的appid和secret;
2、H5网页授权还要在公众号后台设置网页授权域名;
3、小程序的接口域名必须启用https,且要设置request、download合法域名等;
4、App必须在微信开放平台申请应用并绑定。
上述工作准备好后,就可以开干了!
一、H5网页授权
1、授权按钮
// official.vue
<u-button class="button" type="success" @click="getWeChatCode">立即授权</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、公众号授权scope有两种方式:snsapi_base和snsapi_userinfo,前者静默授权不会有授权弹窗,后者必须用户点击授权弹窗按钮授权才行;
2、网页授权是需要跳转到微信服务器上,然后携带code再跳回来,所以在跳回来后还需要用到的变量比如scope必须用缓存保存起来,否则会读取不到;
3、跳转回来的页面就是发起授权的页面,所以在页面的onload方法中要判断url是否携带有code,避免重复跳转授权的死循环(会提示code已被使用);
4、授权后拿code去后台通过微信请求换取用户信息。
二、小程序授权
1、授权按钮,必须是button,且设置
// mp.vue
<u-button type="success" @click="getUserProfile()">微信授权登录</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、授权后会得到code和userInfo,里面有昵称、头像、性别、地域等字段,没有openid;
2、把code和userInfo传回后台,再通过code换取用户的openid和unionid。
三、App授权
1、授权按钮
// app.vue
<u-button class="button" type="success" @click="onAppAuth">确定授权</u-button>
2、js代码
// app.vue
onAppAuth() {
uni.getProvider({
service: 'oauth',
success: (a) => {
if (~a.provider.indexOf('weixin')) {
uni.login({
provider: 'weixin',
onlyAuthorize: true, // 注意此参数
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: '授权登录失败',
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: '授权登录失败',
showCancel: false
})
})
},
fail: (err) => {
console.error(err)
}
})
}
},
fail: (err) => {
console.error(err)
}
})
}
},
fail: (err) => {
console.error(err)
}
})
}
注意:微信在App中授权有两种方式,
1、第一种是uni.login里面的onlyAuthorize为false,此时直接调用uni.getUserInfo方法即可直接在前端获取到用户信息。但此方式有个问题,即必须把App的secret配置在manifest.json文件当中,并且会被打包进apk/ipa中,存在泄漏的风险!所以不推荐此种方式;
2、第二种是onlyAuthorize设置为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']
];
// 判断是否需要注册或更新数据
if ($wechat_member) {
// 如果该用户已经存在,则只更新数据
} 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']
];
// 判断是否需要注册或更新数据
if ($wechat_member) {
// 如果该用户已经存在,则只更新数据
} 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授权未返回此字段
'country' => $params['country'],
'province' => $params['province'],
'city' => $params['city'],
'headimgurl' => $params['avatarUrl']
];
}
// 判断是否需要注册或更新数据
if ($wechat_member) {
// 如果该用户已经存在,则只更新数据
} else {
// 否则的话先用unionid判断有无其他微信记录,再进行更新或注册
}
break;
}
}
至此,微信公众号H5、小程序和App授权登录全部流程结束。
转载自王维的博客: https://asyou.github.io/content/43.html