首页 > 代码库 > php微信网页授权获取用户信息

php微信网页授权获取用户信息

  配置回调域名:

1. 引导用户进入授权页面同意授权,获取code 

2. 通过code换取网页授权access_token(与基础支持中的access_token不同)

3. 如果需要,开发者可以刷新网页授权access_token,避免过期 

4. 通过网页授权access_token和openid获取用户基本信息

先自己建立两个文件: index.php  和  getUser.php

代码实例

index.php如下:

1 <?php    
2     $appid = "公众号的appid";      
3     $REDIRECT_URI=‘回调链接‘;
4     $scope=‘snsapi_base‘;
5 //  $scope=‘snsapi_userinfo‘;//需要授权
6     $url = ‘https://open.weixin.qq.com/connect/oauth2/authorize?appid=‘.$appid.‘&redirect_uri=‘.urlencode($REDIRECT_URI).‘&response_type=code&scope=‘.$scope.‘&state=STATE#wechat_redirect‘;  
7     header("Location:".$url);    
8 ?>  

getUser.php如下:

 1 <?php 
 2 $appid = "公众号appid";  
 3 $secret = "公众号secret"; 
 4 //获取code 
 5 $code = $_GET["code"];  
 6 //获取access_token
 7 $get_token_url = ‘https://api.weixin.qq.com/sns/oauth2/access_token?appid=‘.$appid.‘&secret=‘.$secret.‘&code=‘.$code.‘&grant_type=authorization_code‘;  
 8 
 9 $ch = curl_init();  
10 curl_setopt($ch,CURLOPT_URL,$get_token_url);  
11 curl_setopt($ch,CURLOPT_HEADER,0);  
12 curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1 );  
13 curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);  
14 $res = curl_exec($ch);  
15 curl_close($ch);  
16 $json_obj = json_decode($res,true);  
17 
18 //根据openid和access_token查询用户信息  
19 $access_token = $json_obj[‘access_token‘];  
20 $openid = $json_obj[‘openid‘];  
21 $get_user_info_url = ‘https://api.weixin.qq.com/sns/userinfo?access_token=‘.$access_token.‘&openid=‘.$openid.‘&lang=zh_CN‘;  
22 $ch = curl_init();  
23 curl_setopt($ch,CURLOPT_URL,$get_user_info_url);  
24 curl_setopt($ch,CURLOPT_HEADER,0);  
25 curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1 );  
26 curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);  
27 $res = curl_exec($ch);  
28 curl_close($ch);  
29 //解析json  
30 $user_obj = json_decode($res,true);  
31 $_SESSION[‘user‘] = $user_obj; 
32 print_r($user_obj);  
33 ?>  

 

 

 

php微信网页授权获取用户信息