批改状态:合格
老师批语:
// 微信网页授权
// 获取当前用户的昵称、头像信息
// 1 第一步:用户同意授权,获取code
// 2 第二步:通过code换取网页授权access_token
// 3 第三步:刷新access_token(如果需要)
// 4 第四步:拉取用户信息(需scope为 snsapi_userinfo)
public function auth()
{
$redirect = 'http://0e22edf9.ngrok.io'; //此回调域名必须与网页授权域名一致,并存储给变量,
$url_code = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid='.config('app.appid').'&redirect_uri='.urlEncode($redirect).'&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect'; //获取code
header('Location:'.$url_code);
}
// 显示用户信息
public function userinfo()
{
// 获取code
$code = input('get.code');
// 第二步:通过code换取网页授权access_token
$res = $this->model->auth_access_token($code,false);
$auth_access_token = $res['access_token'];
$openid = $res['openid'];
// 第三步:拉取用户信息(需scope为 snsapi_userinfo)
$userinfo = $this->model->get_userinfo($auth_access_token,$openid);
dump($userinfo);
} //网页授权access_token
public function auth_access_token($code)
{
$appid = config('app.appid');
$appsecret = config('app.appsecret');
$url = 'https://api.weixin.qq.com/sns/oauth2/access_token?appid='.$appid.'&secret='.$appsecret.'&code='.$code.'&grant_type=authorization_code';
$res = http_Get($url);
$res = json_decode($res);
if(!isset($res['access_token'])){
return false;
}
return $res;
}
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号