index.php
<? //scope=snsapi_base 实例 $appid='appid'; $redirect_uri = urlencode('http://wx.xswkj.com/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); ?>
getinfo.php
<? header("Content-type: text/html; charset=utf-8"); //ID 密钥 $appid = "appid"; $appsecret = "appsecret"; $code = $_GET["code"]; //第一步:取全局access_token $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=$appid&secret=$appsecret"; //$token = getJson($url); $jsoninfo = https_request($url); //$jsoninfo = json_decode($output, true); //返回 一个数组 //[html] view plain copy //7200 //var_dump($jsoninfo); //[html] view plain copy $access_token = $jsoninfo["access_token"]; //第二步:取得openid $oauth2Url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=$appid&secret=$appsecret&code=$code&grant_type=authorization_code"; //$oauth2 = getJson($oauth2Url); $oauth2 = https_request($oauth2Url); //$oauth2 = json_decode($oauth2, true); //第三步:根据全局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 = https_request($get_user_info_url); //$userinfo = json_decode($userinfo, true); //打印用户信息 echo "欢迎你:".$userinfo['nickname']."登录到我的公众号。</br></br></br></br>"; echo "你的openid是:".$userinfo['openid']."</br></br></br></br>"; 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, FALSE); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); $output = curl_exec($ch); curl_close($ch); //return $output; return json_decode($output, true); } function https_request($url,$data = null){ $curl = curl_init(); //$data=iconv('GB2312','UTF-8',$data); $encode = mb_detect_encoding($data, array('ASCII','UTF-8','GB2312','GBK','BIG5')); if ($encode!='UTF-8') { $data=iconv('GB2312','UTF-8',$data); } echo $data; curl_setopt($curl, CURLOPT_HTTPHEADER, array("Accept: application/json", "Content-Type: text/xml; charset=utf-8")); curl_setopt($curl, CURLOPT_URL, $url); curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE); curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE); if (!empty($data)){ curl_setopt($curl, CURLOPT_POST, 1); curl_setopt($curl, CURLOPT_POSTFIELDS, $data); } curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); $output = curl_exec($curl); curl_close($curl); // return $output; return json_decode($output, true); } ?>