微信公衆號開發:用戶授權獲取用戶信息


獲取用戶授權用戶信息中的assesstoken調用不限次數!!!有效期兩小時

header("Content-type: text/html; charset=utf-8"); 
$openid='';
$username='';
$img='';
if($_COOKIE['<span style="font-family: Arial, Helvetica, sans-serif;">openid</span><span style="font-family: Arial, Helvetica, sans-serif;">']){</span>
$openid=$_COOKIE['<span style="font-family: Arial, Helvetica, sans-serif;">openid</span><span style="font-family: Arial, Helvetica, sans-serif;">'];</span>
$username=$_COOKIE['username'];
$img=$_COOKIE['img'];
}else{
$code = $_GET['code'];
$state = $_GET['state'];
$url = 'https://api.weixin.qq.com/sns/oauth2/access_token?appid=公衆號id&secret=公衆號祕鑰&code=' . $code . '&grant_type=authorization_code';
$result = null;
try {
    $result = curlGet($url);
    $obj = json_decode($result);
    $getInfoUrl = "https://api.weixin.qq.com/sns/userinfo?access_token=" . $obj->access_token . "&openid=" . $obj->openid;
    //微信返回值
    $userObj = json_decode(curlGet($getInfoUrl));
} catch (Exception $e) {
    echo $e->getTraceAsString();

}
//echo $userObj->openid;die;
//echo $userObj->openid;die;
$openid=$userObj->openid;
$username=urlencode(str_replace(array("'", "\\"), array(''), $userObj->nickname));
$img=$userObj->headimgurl;
setcookie('uid',$userObj->openid,time()+3*24*60*60);
setcookie('username',$username,time()+3*24*60*60);
setcookie('img',$img,time()+3*24*60*60);
}

function curlGet($url, $method = 'get', $data = '')
{
    $ch = curl_init();
    $header = "Accept-Charset: utf-8";
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, strtoupper($method));
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
    curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (compatible; MSIE 5.01; Windows NT 5.0)');
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
    curl_setopt($ch, CURLOPT_AUTOREFERER, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    $temp = curl_exec($ch);
    return $temp;
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章