说明
uniapp+tp简单实现微信公众号网页授权
后端除了tp6以外还需要一个easywechat
微信开发库
实现
前端uniapp部分
1.首先判断本地缓存内是否有openid,有就不需要授权
2.没有openid就去请求后端授权,然后后端取到授权把信息放在url内,重定向到前端
/**
* 判断是否微信授权
*/
export function is_auth() {
//1.这个getStorage是我封装的uniapp的本地缓存
const openid = getStorage('openid');
console.log('openid', openid);
if (openid) {
console.log('已有授权', openid);
} else {
const routes = getCurrentPages(); // 获取当前打开过的页面路由数组
console.log('routes', routes);
const curParam = routes[routes.length - 1].options;
console.log('curParam', curParam);
if (curParam.data) {
console.log('授权成功', curParam);
const res = JSON.parse(curParam.data);
setStorage('openid', res.openid);
setStorage('uid', res.uid);
} else {
uni.showToast({
title:'没有授权',
})
console.log('没有授权', curParam)
//后端处理授权地址
window.location.href = 'http://xxxx.cn/api/Login/InitiateAuthorization1';
}
}
}
后端php部分
//首页地址,授权完毕要重定向会首页
protected $homeUrl = 'http://ces.xzndw1.cn/h5';
/**
* 微信授权配置
* 静默授权 snsapi_base
* 弹出授权提示 snsapi_userinfo
*/
protected function wx_config($scope){
return [
'app_id' => '你的appid',
'secret' => '你的secret',
'response_type' => 'array',
'oauth' => [
'scopes' => [$scope],
'callback' => 'http://xxxx.cn/api/Login/InitiateAuthorization1',
]
];
}
/**
* 发起静默授权
*/
public function InitiateAuthorization1(){
$app = Factory::officialAccount($this->wx_config('snsapi_base'));
$response = input();
//这里是为了判断是否存在上级uid,如果不需要这个可以去掉
if (!empty($response['suid'])) {
Session::set('suid', $response['uid']);
Session::save();
}
$oauth = $app->oauth;
if (!empty($response['code'])) {
$user = $oauth->user();
if (!empty($user)) {
// 验证wxid是否存在数据库,不存在则注册,这里的Session::pull('suid')也就是取上面存的uid
$uid = $this->sign_up($user->getId(),Session::pull('suid'));
if (!empty($uid)) {
$data = [
'openid' => $user->getId(),
'uid' => $uid
];
return redirect($this->homeUrl .'/?data=' . json_encode($data));
}
}
return redirect($this->homeUrl .'/?data=' . '授权失败');
} else {
$oauth->redirect()->send();
}
return '获取授权失败';
}