我正在尝试使用 PHP
对 à LinkedIn用户配置文件进行API
。我已经成功注册了我的应用程序,并记下了我的API和密钥,并列出了我的重定向URL。
用户从此页面开始:index.php
。此页包含指向"LinkedIn"对话框的链接:
<a href="https://www.linkedin.com/uas/oauth2/authorization?response_type=code&client_id=<?php echo $api_key ?>&state=<?php echo $state ?>&redirect_uri=<?php echo $redirect_uri ?>">Apply Now</a>
当我单击此链接时,我使用我的详细信息登录LinkedIn,并成功重定向到application_form.php
。从这里我现在想获取用户配置文件详细信息:
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://www.linkedin.com/v1/people/~");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$output = curl_exec($ch);
curl_close($ch);
var_dump($output);
但是,上面的代码会导致输出:
"401 Unknown authentication scheme"
在做了一些研究之后,我认为这可能是因为我此时还没有获得访问令牌?有人知道我应该怎么做才能解决这个问题吗?
对于正在阅读本文并想使用LinkedIn Profile API
的任何人,我的问题的解决方案是,当我尝试提出第一个请求时,我没有有效的Access Token
。
我做的第一件事是创建一个链接,将用户定向到LinkedIn
身份验证对话框。
接下来,用户将选择批准或拒绝我的应用程序访问其配置文件的请求。无论他们的选择如何,他们都会被重定向到我的redirect url
。
从这里开始,我现在有一个access code
,我可以用来请求access token
,从而进行 api 调用。
if (isset($_GET['error'])) {
echo $_GET['error'] . ': ' . $_GET['error_description'];
} elseif (isset($_GET['code'])) {
getAccessToken();
//$user = fetch('GET', '/v1/people/~:(firstName,lastName)');//get name
//$user = fetch('GET', '/v1/people/~:(phone-numbers)');//get phone numbers
$user = fetch('GET', '/v1/people/~:(location:(name))');//get country
var_dump($user);
}
我基于 LinkedIn 开发人员网站上的代码使用的getAccessToken()
方法
https://developer.linkedin.com/documents/code-samples
function getAccessToken() {
$params = array(
'grant_type' => 'authorization_code',
'client_id' => 'MY API KEY',
'client_secret' => 'MY SECRET KEY',
'code' => $_GET['code'],
'redirect_uri' => 'MY REDIRECT URL',
);
// Access Token request
$url = 'https://www.linkedin.com/uas/oauth2/accessToken?' . http_build_query($params);
// Tell streams to make a POST request
$context = stream_context_create(
array('http' =>
array('method' => 'POST',
)
)
);
// Retrieve access token information
$response = file_get_contents($url, false, $context);
// Native PHP object, please
$token = json_decode($response);
// Store access token and expiration time
$_SESSION['access_token'] = $token->access_token; // guard this!
$_SESSION['expires_in'] = $token->expires_in; // relative time (in seconds)
$_SESSION['expires_at'] = time() + $_SESSION['expires_in']; // absolute time
return true;
}
然后是fetch()
方法,也来自LinkedIn API
function fetch($method, $resource, $body = '') {
$opts = array(
'http' => array(
'method' => $method,
'header' => "Authorization: Bearer " .
$_SESSION['access_token'] . "'r'n" .
"x-li-format: json'r'n"
)
);
$url = 'https://api.linkedin.com' . $resource;
if (count($params)) {
$url .= '?' . http_build_query($params);
}
$context = stream_context_create($opts);
$response = file_get_contents($url, false, $context);
return json_decode($response);
}
通过执行上述操作,我向API
提出请求没有问题。公平地说,上面评论的克布罗。我缺少这些信息。如果他/她想留下答案,我很乐意接受,但以防万一我已经为遇到我遇到的问题的任何人提供了我的解决方案。