PHP微信网页授权代码获取用户信息
1.填写授权回调页面的域名 (注意只有服务号才可以页面授权)
登录公众平台-->开发者中心-->接口权限表
2.代码如下
scope为snsapi_base 那么用户必须是关注了公众号才能取得信息
index.PHP //scope=snsapi_base 实例 $appid='你的AppId'; $redirect_uri = urlencode ( 'http://你的域名/getUserInfo.PHP' ); $url ="https://open.weixin.qq.com/connect/oauth2/authorize?appid=$appid&redirect_uri=$redirect_uri&response_type=code&scope=snsapi_base&state=1#wechat_redirect"; header("Location:".$url);
getUserInfo.PHP $appid = "你的AppId"; $secret = "你的AppSecret"; $code = $_GET["code"]; //第一步:取全局access_token $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=$appid&secret=$secret"; $token = getJson($url); //第二步:取得openid $oauth2Url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=$appid&secret=$secret&code=$code&grant_type=authorization_code"; $oauth2 = getJson($oauth2Url); //第三步:根据全局access_token和openid查询用户信息 $access_token = $token["access_token"]; $openid = $oauth2['openid']; $get_user_info_url = "https://api.weixin.qq.com/cgi-bin/user/info?access_token=$access_token&openid=$openid&lang=zh_CN"; $userinfo = getJson($get_user_info_url); //打印用户信息 print_r($userinfo); function getJson($url){ $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE); curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, CURLOPT_RETURNTRANSFER, 1); $output = curl_exec($ch); curl_close($ch); return json_decode($output, true); }
snsapi_userinfo 用户不用关注公众号,也能取到信息,但是会有一个界面让用户去点击确认
index.PHP $appid='你的AppId'; $redirect_uri = urlencode ( 'http://你的域名/getUserInfo.PHP' ); $url ="https://open.weixin.qq.com/connect/oauth2/authorize?appid=$appid&redirect_uri=$redirect_uri&response_type=code&scope=snsapi_userinfo&state=1#wechat_redirect"; header("Location:".$url);
getUserInfo.PHP $appid = "你的AppId"; $secret = "你的AppSecret"; $code = $_GET["code"]; //第一步:取得openid $oauth2Url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=$appid&secret=$secret&code=$code&grant_type=authorization_code"; $oauth2 = getJson($oauth2Url); //第二步:根据全局access_token和openid查询用户信息 $access_token = $oauth2["access_token"]; $openid = $oauth2['openid']; $get_user_info_url = "https://api.weixin.qq.com/cgi-bin/user/info?access_token=$access_token&openid=$openid&lang=zh_CN"; $userinfo = getJson($get_user_info_url); //打印用户信息 print_r($userinfo); function getJson($url){ $ch = curl_init(); curl_setopt($ch, true); }
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。