[英]Get LinkedIn profile from OAuth REST API with PHP
我使用了這個網站: http : //blog.thewebcafes.com/post/1502524959/php-step-by-step-oauth-for-dummies-based-on
創建以下php頁面:
<?php
if(!isset($_SESSION)){session_start();}
define('LINKEDIN_KEY', '**************');
define('LINKEDIN_SECRET', '****************');
//Prepare The Links
$links = array(
'request_token'=>'https://api.linkedin.com/uas/oauth/requestToken',
'authorize'=>'https://www.linkedin.com/uas/oauth/authorize',
'access_token'=>'https://api.linkedin.com/uas/oauth/accessToken'
);
//Validate Parameters Passed Back by LinkedIn
if(isset($_GET['oauth_token']) && isset($_GET['oauth_verifier']) && $_GET['oauth_token']==$_SESSION['linkedin_oauth_token']) {
//we have user permission, let's get a token
getAccessToken();
getProfile();
}else {
//we don't have an authed user yet, let's ask for permission
authUser();
}
function urlencode_oauth($str) {
return str_replace('+',' ',str_replace('%7E','~',rawurlencode($str)));
}
function getProfile() {
global $links;
//Prepare OAuth Parameters
$params = array(
'oauth_consumer_key'=>LINKEDIN_KEY,
'oauth_nonce'=>sha1(microtime()),
'oauth_signature_method'=>'HMAC-SHA1',
'oauth_timestamp'=>time(),
'oauth_token'=>$_SESSION['linkedin_access_token'],
'oauth_version'=>'1.0'
);
//Prepare The Base String
// sort parameters according to ascending order of key
ksort($params);
// prepare URL-encoded query string
$q = array();
foreach ($params as $key=>$value) {
$q[] = urlencode_oauth($key).'='.urlencode_oauth($value);
}
$q = implode('&',$q);
// generate the base string for signature
$parts = array(
'GET',
urlencode_oauth('https://api.linkedin.com/v1/people/~:(id,num-connections,picture-url)?format=json'),
urlencode_oauth($q)
);
$base_string = implode('&',$parts);
//Get The Signature
$key = urlencode_oauth(LINKEDIN_SECRET) . '&' . urlencode_oauth($_SESSION['linkedin_access_token_secret']);
$signature = base64_encode(hash_hmac('sha1',$base_string,$key,true));
//Put the Signature into Parameters and Prepare Authorization Header
$params['oauth_signature'] = $signature;
$str = array();
foreach ($params as $key=>$value) {
$str[] = $key . '="'.urlencode_oauth($value).'"';
}
$str = implode(', ',$str);
$headers = array(
'GET /v1/people/~ HTTP/1.1',
'Host: api.linkedin.com',
'Authorization: OAuth '.$str,
'Connection: Keep-Alive',
'Content-Type: application/json',
'x-li-format: json'
);
//Send GET Request To LinkedIn
$fp = fsockopen("ssl://api.linkedin.com",443,$errno,$errstr,30);
if(!$fp) { echo 'Unable to connect to LinkedIn'; exit(); }
$out = implode("\r\n",$headers)."\r\n\r\n".$xml . "\r\n\r\n";
fputs($fp,$out);
// getting LinkedIn server response
$res = '';
while (!feof($fp)) $res .= fgets($fp,4096);
fclose($fp);
echo 'RESPONSE: ' . $res;
//Make sure the GET is successful
$parts = explode("\n\n",str_replace("\r","",$res));
$headers = explode("\n",$parts[0]);
if ($headers[0] != 'HTTP/1.1 201 Created') { echo 'Failed'; }
}
function getAccessToken() {
global $links;
//Prepare OAuth Parameters
$params = array(
'oauth_consumer_key'=>LINKEDIN_KEY,
'oauth_nonce'=>sha1(microtime()),
'oauth_signature_method'=>'HMAC-SHA1',
'oauth_timestamp'=>time(),
'oauth_token'=>$_GET['oauth_token'],
'oauth_verifier'=>$_GET['oauth_verifier'],
'oauth_version'=>'1.0'
);
//Prepare The Base String
// sort parameters according to ascending order of key
ksort($params);
// prepare URL-encoded query string
$q = array();
foreach ($params as $key=>$value) {
$q[] = urlencode_oauth($key).'='.urlencode_oauth($value);
}
$q = implode('&',$q);
// generate the base string for signature
$parts = array(
'POST',
urlencode_oauth($links['access_token']),
urlencode_oauth($q)
);
$base_string = implode('&',$parts);
//Get The Signature
$key = urlencode_oauth(LINKEDIN_SECRET) . '&' . urlencode_oauth($_SESSION['linkedin_oauth_token_secret']);
$signature = base64_encode(hash_hmac('sha1',$base_string,$key,true));
//Put the Signature into Parameters and Prepare Authorization Header
$params['oauth_signature'] = $signature;
$str = array();
foreach ($params as $key=>$value) {
$str[] = $key . '="'.urlencode_oauth($value).'"';
}
$str = implode(', ',$str);
$headers = array(
'POST /uas/oauth/accessToken HTTP/1.1',
'Host: api.linkedin.com',
'Authorization: OAuth '.$str,
'Content-Type: text/xml;charset=UTF-8',
'Content-Length: 0',
'Connection: close'
);
//Send POST Request To LinkedIn
$fp = fsockopen("ssl://api.linkedin.com",443,$errno,$errstr,30);
if (!$fp) { echo 'Unable to connect to LinkedIn'; exit(); }
$out = implode("\r\n",$headers) . "\r\n\r\n";
fputs($fp,$out);
// getting LinkedIn server response
$res = '';
while (!feof($fp)) $res .= fgets($fp,4096);
fclose($fp);
//Parse the Response to Get The Access Token and Secret
$parts = explode("\n\n",str_replace("\r",'',$res));
$res_headers = explode("\n",$parts[0]);
if ($res_headers[0] != 'HTTP/1.1 200 OK') {
echo 'Error getting access token and secret.'; exit();
}
parse_str($parts[1],$data);
if (empty($data['oauth_token'])) {
echo 'Failed to get LinkedIn access token.'; exit();
}
//Save the Request Token and Secret
$_SESSION['linkedin_access_token'] = $data['oauth_token'];
$_SESSION['linkedin_access_token_secret'] = $data['oauth_token_secret'];
// unset the Request Token (not needed anymore)
unset($_SESSION['linkedin_oauth_token']);
unset($_SESSION['linkedin_oauth_token_secret']);
}
function authUser() {
global $links;
//Prepare OAuth Parameters
$params = array(
'oauth_callback'=>"https://sxsw.ampthealth.com/linkedin_callback.php",
'oauth_consumer_key'=>LINKEDIN_KEY,
'oauth_nonce'=>sha1(microtime()),
'oauth_signature_method'=>'HMAC-SHA1',
'oauth_timestamp'=>time(),
'oauth_version'=>'1.0'
);
//Prepare The Base String
// sort parameters according to ascending order of key
ksort($params);
// prepare URL-encoded query string
$q = array();
foreach ($params as $key=>$value) {
$q[] = urlencode_oauth($key).'='.urlencode_oauth($value);
}
$q = implode('&',$q);
// generate the base string for signature
$parts = array(
'POST',
urlencode_oauth($links['request_token']),
urlencode_oauth($q)
);
$base_string = implode('&',$parts);
//Get The Signature
$key = urlencode_oauth(LINKEDIN_SECRET) . '&';
$signature = base64_encode(hash_hmac('sha1',$base_string,$key,true));
//Put the Signature into Parameters and Prepare Authorization Header
$params['oauth_signature'] = $signature;
$str = array();
foreach ($params as $key=>$value) {
$str[] = $key . '="'.urlencode_oauth($value).'"';
}
$str = implode(', ',$str);
$headers = array(
'POST /uas/oauth/requestToken HTTP/1.1',
'Host: api.linkedin.com',
'Authorization: OAuth '.$str,
'Content-Type: text/xml;charset=UTF-8',
'Content-Length: 0',
'Connection: close'
);
//Send POST Request To LinkedIn
$fp = fsockopen("ssl://api.linkedin.com",443,$errno,$errstr,30);
if (!$fp) { echo 'Unable to connect to LinkedIn'; exit(); }
$out = implode("\r\n",$headers) . "\r\n\r\n";
fputs($fp,$out);
// getting LinkedIn server response
$res = '';
while (!feof($fp)) $res .= fgets($fp,4096);
fclose($fp);
//Parse the Response to Get OAuth Token and Secret
$parts = explode("\n\n",str_replace("\r",'',$res));
$res_headers = explode("\n",$parts[0]);
if ($res_headers[0] != 'HTTP/1.1 200 OK') {
echo 'Error getting OAuth token and secret.'; exit();
}
parse_str($parts[1],$data);
if (empty($data['oauth_token'])) {
echo 'Failed to get LinkedIn request token.'; exit();
}
//Save the Request Token and Secret
$_SESSION['linkedin_oauth_token'] = $data['oauth_token'];
$_SESSION['linkedin_oauth_token_secret'] = $data['oauth_token_secret'];
//Redirect your user to LinkedIn with the request token
header('Location: '.$links['authorize'].'?oauth_token='.urlencode($data['oauth_token']));
exit();
}
?>
我能夠使用戶授權並請求訪問令牌,但是在獲取基本配置文件時,出現錯誤:401未經授權的服務器。 我的getProfile函數中肯定有問題,但是我丟失了一些東西。
您必須按照此處 Linkedin文檔中的步驟進行操作。
特別是閱讀申請被批准的要點。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.