PHP获得微信用户的OpenID,然后再通过OpenID和access_token查询用户信息大致如下步骤:
前提是必须要知道的有公众帐号的:appid和secret
* 1、拼成一个链接
* 2、把链接抛出去返回一个code echo $_GET[\'code\']
* 3、根据code换取access_token和openid
* 4. 使用access_token和openid来获取用户信息
* 5、
*
一、第一步写个页面去进行请求微信API获取code
<?php
//$APPID=\'*******\';
//$REDIRECT_URI=\'wx.qq.com/c/m1020.php\';
//$scope=\'snsapi_base\';如果要获取所有的信息请用$scope = snsapi_userinfo;
//$state = 120;
//需要授权的域名 wx.qq.com这一步是在公众后台进行添加的,然后这个域名下的所有页面都可以获得授权比如我的:http://wx.qq.com/c/m1020a.php
header("Location: https://open.weixin.qq.com/connect/oauth2/authorize?appid=***********&redirect_uri=http://wx.qq.com/c/m1020a.php&response_type=code&scope=snsapi_userinfo&state=1#wechat_redirect");
?>
二、第二步写另外一个页面获得微信用户的OpenID,然后再通过OpenID和access_token查询用户信息代码如下:
<?php
//wx.mtgdfs.com/c/m1020.php
$appid = "你的公众帐号appid";
$secret = "你的公众帐号秘钥";
$code = $_GET["code"];
$get_token_url = \'https://api.weixin.qq.com/sns/oauth2/access_token?appid=\'.$appid.\'&secret=\'.$secret.\'&code=\'.$code.\'&grant_type=authorization_code\';
$ch = curl_init();
curl_setopt($ch,CURLOPT_URL,$get_token_url);
curl_setopt($ch,CURLOPT_HEADER,0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1 );
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
$res = curl_exec($ch);
curl_close($ch);
$json_obj = json_decode($res,true);
//根据openid和access_token查询用户信息
$access_token = $json_obj[\'access_token\'];
$openid = $json_obj[\'openid\'];
$get_user_info_url = \'https://api.weixin.qq.com/sns/userinfo?access_token=\'.$access_token.\'&openid=\'.$openid.\'&lang=zh_CN\';
$ch = curl_init();
curl_setopt($ch,CURLOPT_URL,$get_user_info_url);
curl_setopt($ch,CURLOPT_HEADER,0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1 );
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
$res = curl_exec($ch);
curl_close($ch);
//echo "<hr>ddd<hr>";
//$code = $_GET[\'code\'];//获取code
//$weixin = file_get_contents("https://api.weixin.qq.com/sns/oauth2 /access_token?appid=wxba922caddc6700a8& secret=9f47a54b26ab9ed1a01fa71ae2e82f27&code=".$code."& grant_type=authorization_code");//通过code换取网页授权access_token
//$jsondecode = json_decode($weixin); //对JSON格式的字符串进行编码
//$array = get_object_vars($jsondecode);//转换成数组
//print_r($array);exit;
//$openid = $array[\'openid\'];//输出openid
//解析json
$user_obj = json_decode($res,true);
$_SESSION[\'user\'] = $user_obj;
print_r($user_obj);
?>