在網站的開發功能中,我們很多時間需要做第三方登錄,比如說QQ,百度賬號,新浪微博等可以登錄自己的網站。
百度賬號登錄。
<button οnclick="baidu()" class="u-btn btn-bd">使用百度帳號登錄</button>
function baidu(){
window.location.href = "<{$web_url}>/index.php/login/baidu";
}
public function baidu(){
//client_id 這個需要在百度開發者平臺申請
//redirect_uri 這個就是 申請賬號的寫的回調地址
//
$url = "http://openapi.baidu.com/social/oauth/2.0/authorize?media_type=baidu&client_id=*********&state=&response_type=code&redirect_uri=http%3A%2F%2
F*****&display=page&client_type=web";
header("location:".$url);
}
這個就是百度驗證請求的信息 ,要是正確的話 會返回一個code到你的回調地址,這個code也就是相當於一個鑰匙,有了這個鑰匙,你就可以去尋找百度賬號的有關信
返回的code格式
http://www.****/?code=226d900af50345e49513bc4f320f6007&state=
然後就是:
$accesstoken=$this->requestAccessToken($code);
$userinfo=$this->requestUserInfo($accesstoken['access_token']); //返回第三方用戶信息
/**
* 獲取AccessToKen
*/
private function requestAccessToken($code){
$url = 'https://openapi.baidu.com/social/oauth/2.0/token';
$client_id = '*********';//這個需要百度申請
$client_secret = '*************************';//這個需要百度申請
$redirect_uri='**********';//這個需要跟申請時候寫的回調地址一樣 格式;http://www.***.com
$params = array(
'grant_type' => 'authorization_code',
'client_id' => $client_id,
'client_secret' => $client_secret,
'redirect_uri' => $redirect_uri,
'code' => $code,
);
$ch = curl_init();
$curl_opts = array(
CURLOPT_CONNECTTIMEOUT => 3,
CURLOPT_TIMEOUT => 5,
CURLOPT_USERAGENT => 'baidu-apiclient-php-2.0',
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_HEADER => false,
CURLOPT_FOLLOWLOCATION => false,
);
if (stripos($url, 'https://') === 0) {
$curl_opts[CURLOPT_SSL_VERIFYPEER] = false;
}
$query = http_build_query($params, '', '&');
$delimiter = strpos($url, '?') === false ? '?' : '&';
$curl_opts[CURLOPT_URL] = $url . $delimiter . $query;
$curl_opts[CURLOPT_POST] = false;
curl_setopt_array($ch, $curl_opts);
$result = curl_exec($ch);
if ($result === false) {
curl_close($ch);
return false;
} elseif (empty($result)) {
$http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
if ($http_code != 200) {
curl_close($ch);
return false;
}
}
curl_close($ch);
return json_decode($result, true);
}
/**
* 返回第三方用戶信息
* @param $access_token
*/
private function requestUserInfo($access_token){
$url="https://openapi.baidu.com/social/api/2.0/user/info?access_token={$access_token}";
$result=file_get_contents($url);
$result =json_decode($result,true);
return $result;
}
var_dump($userinfo) 就可以顯示出百度接口