官方文档
准备工作
账号设置-功能设置-设置网页授权域名
这里用的是服务号

示例代码
// 获取code
public function getCode()
{
$userInfo = session('USER'); // 跳转链接中可以携带参数
$user_id = $userInfo['id'];
// 配置微信跳转链接
$redirect_uri = "http://www.****.com/login/getUserOpenId?user_id=" . $user_id;
$redirect_uri = urlencode($redirect_uri);
$url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=" . $this->appid . "&redirect_uri=$redirect_uri&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect";
header("Location: $url");
exit();
}
// 这里获取到openid和token,还可以使用token进一步获取用户信息。但是我不需要 就没写
public function getUserOpenId()
{
// 微信返回的code
$code = $_GET['code'];
// 发送curl请求
$curl = curl_init();
$url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" . $this->appid . "&secret=" . $this->app_secret . "&code=" . $code . "&grant_type=authorization_code";
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
$result = curl_exec($curl);
curl_close($curl);
$json = json_decode($result, true);
$user_id = $_GET['user_id']; // 这里是微信回调地址,获取不到session,只能通过回调地址传参实现
$update['openid'] = $json['openid'];
Db::name('user')->where(['id' => $user_id])->update($update);
// 返回
// echo"<script>alert('授权成功!');history.back();window.location.reload()</script>";
}
参考链接
PHP实践:手把手微信公众号网页授权登录功能实现----(也没有参考它,只是这一篇比较详细)
问题
- 唤起授权,但是redirect_url没有跳转。
在配置了网页授权域名后还出现这个问题,那就直接访问一下你的跳转链接就好了。肯定是跳转链接出错了。
我一开始使用https的链接,但是https证书到期了。一直不知道,也没看到报错。后面索性换成http就可以了。
1万+

被折叠的 条评论
为什么被折叠?



