4

我从一些关于链接注册的教程中获得了这段代码,但该教程只提供了基本信息。我还需要获取用户电子邮件...我该怎么做?

这是代码:

授权文件

这是我在 likedin 上获取访问表单的链接。

<?php
    session_start();
    $config['base_url']             =   '';
    $config['callback_url']         =   '';
    $config['linkedin_access']      =   '';
    $config['linkedin_secret']      =   '';

    include_once "linkedin.php";

    # First step is to initialize with your consumer key and secret. We'll use an out-of-band oauth_callback
    $linkedin = new LinkedIn($config['linkedin_access'], $config['linkedin_secret'], $config['callback_url'] );
    //$linkedin->debug = true;

    # Now we retrieve a request token. It will be set as $linkedin->request_token
    $linkedin->getRequestToken();
    $_SESSION['requestToken'] = serialize($linkedin->request_token);

    # With a request token in hand, we can generate an authorization URL, which we'll direct the user to
    //echo "Authorization URL: " . $linkedin->generateAuthorizeUrl() . "\n\n";
    header("Location: " . $linkedin->generateAuthorizeUrl()); ?>

演示.php

这是我注册后得到的脚本。

<?php
    session_start();

    $config['base_url']             =   'http://xxx/linkedin/auth.php';
    $config['callback_url']         =   'http://xxx/linkedin/demo.php';
    $config['linkedin_access']      =   '';
    $config['linkedin_secret']      =   '';

    include_once "linkedin.php";

    # First step is to initialize with your consumer key and secret. We'll use an out-of-band oauth_callback
    $linkedin = new LinkedIn($config['linkedin_access'], $config['linkedin_secret'], $config['callback_url'] );
    //$linkedin->debug = true; if (isset($_REQUEST['oauth_verifier'])){
    $_SESSION['oauth_verifier']     = $_REQUEST['oauth_verifier'];

    $linkedin->request_token    =   unserialize($_SESSION['requestToken']);
    $linkedin->oauth_verifier   =   $_SESSION['oauth_verifier'];
    $linkedin->getAccessToken($_REQUEST['oauth_verifier']);

    $_SESSION['oauth_access_token'] = serialize($linkedin->access_token);
    header("Location: " . $config['callback_url']);
    exit;}   else{
    $linkedin->request_token    =   unserialize($_SESSION['requestToken']);
    $linkedin->oauth_verifier   =   $_SESSION['oauth_verifier'];
    $linkedin->access_token     =   unserialize($_SESSION['oauth_access_token']);}

    # You now have a $linkedin->access_token and can make calls on behalf of the current member
    $xml_response = $linkedin->getProfile("~:(id,first-name,last-name,headline,picture-url)");


    $id = $linkedin->getProfile('~:(id)');
    $fname = $linkedin->getProfile('~:(first-name)');
    $lname = $linkedin->getProfile('~:(last-name)');
    $headline = $linkedin->getProfile('~:(headline)');
    $picture = $linkedin->getProfile('~:(picture-url)');

    $id = trim(strip_tags($id));
    $fname = trim(strip_tags($fname));
    $lname = trim(strip_tags($lname));
    $headline = trim(strip_tags($headline));
    $picture = trim(strip_tags($picture)); ?>

链接的.php

这是 LinkedIn 库:

<?php require_once("OAuth.php"); class LinkedIn {
    public $base_url = "http://api.linkedin.com";
    public $secure_base_url = "https://api.linkedin.com";
    public $oauth_callback = "oob";
    public $consumer;
    public $request_token;
    public $access_token;
    public $oauth_verifier;
    public $signature_method;
    public $request_token_path;
    public $access_token_path;
    public $authorize_path;

    function __construct($consumer_key, $consumer_secret, $oauth_callback = NULL)
    {

        if($oauth_callback) {
            $this->oauth_callback = $oauth_callback;
        }

        $this->consumer = new OAuthConsumer($consumer_key, $consumer_secret, $this->oauth_callback);
        $this->signature_method = new OAuthSignatureMethod_HMAC_SHA1();
        $this->request_token_path = $this->secure_base_url . "/uas/oauth/requestToken";
        $this->access_token_path = $this->secure_base_url . "/uas/oauth/accessToken";
        $this->authorize_path = $this->secure_base_url . "/uas/oauth/authorize";
    }

    function getRequestToken()
    {
        $consumer = $this->consumer;
        $request = OAuthRequest::from_consumer_and_token($consumer, NULL, "GET", $this->request_token_path);
        $request->set_parameter("oauth_callback", $this->oauth_callback);
        $request->sign_request($this->signature_method, $consumer, NULL);
        $headers = Array();
        $url = $request->to_url();
        $response = $this->httpRequest($url, $headers, "GET");
        parse_str($response, $response_params);
        $this->request_token = new OAuthConsumer($response_params['oauth_token'], $response_params['oauth_token_secret'], 1);
    }

    function generateAuthorizeUrl()
    {
        $consumer = $this->consumer;
        $request_token = $this->request_token;
        return $this->authorize_path . "?oauth_token=" . $request_token->key;
    }

    function getAccessToken($oauth_verifier)
    {
        $request = OAuthRequest::from_consumer_and_token($this->consumer, $this->request_token, "GET", $this->access_token_path);
        $request->set_parameter("oauth_verifier", $oauth_verifier);
        $request->sign_request($this->signature_method, $this->consumer, $this->request_token);
        $headers = Array();
        $url = $request->to_url();
        $response = $this->httpRequest($url, $headers, "GET");
        parse_str($response, $response_params);
        $this->access_token = new OAuthConsumer($response_params['oauth_token'], $response_params['oauth_token_secret'], 1);
    }

    function getProfile($resource = "~")
    {
        $profile_url = $this->base_url . "/v1/people/" . $resource;
        $request = OAuthRequest::from_consumer_and_token($this->consumer, $this->access_token, "GET", $profile_url);
        $request->sign_request($this->signature_method, $this->consumer, $this->access_token);
        $auth_header = $request->to_header("https://api.linkedin.com"); # this is the realm
        # This PHP library doesn't generate the header correctly when a realm is not specified.
        # Make sure there is a space and not a comma after OAuth
        // $auth_header = preg_replace("/Authorization\: OAuth\,/", "Authorization: OAuth ", $auth_header);
        // # Make sure there is a space between OAuth attribute
        // $auth_header = preg_replace('/\"\,/', '", ', $auth_header);

        // $response will now hold the XML document
        $response = $this->httpRequest($profile_url, $auth_header, "GET");
        return $response;
    }

    function setStatus($status)
    {
        $profile_url = $this->base_url . "/v1/people/~";
        $status_url = $this->base_url . "/v1/people/~/current-status";
        echo "Setting status...\n";
        $xml = "<current-status>" . htmlspecialchars($status, ENT_NOQUOTES, "UTF-8") . "</current-status>";
        echo $xml . "\n";
        $request = OAuthRequest::from_consumer_and_token($this->consumer, $this->access_token, "PUT", $status_url);
        $request->sign_request($this->signature_method, $this->consumer, $this->access_token);
        $auth_header = $request->to_header("https://api.linkedin.com");

        $response = $this->httpRequest($profile_url, $auth_header, "GET");
        return $response;
    }

    # Parameters should be a query string starting with "?"
    # Example search("?count=10&start=10&company=LinkedIn");
    function search($parameters)
    {
        $search_url = $this->base_url . "/v1/people-search:(people:(id,first-name,last-name,picture-url,site-standard-profile-request,headline),num-results)" . $parameters;
        //$search_url = $this->base_url . "/v1/people-search?keywords=facebook";

        echo "Performing search for: " . $parameters . "<br />";
        echo "Search URL: $search_url <br />";
        $request = OAuthRequest::from_consumer_and_token($this->consumer, $this->access_token, "GET", $search_url);
        $request->sign_request($this->signature_method, $this->consumer, $this->access_token);
        $auth_header = $request->to_header("https://api.linkedin.com");
        $response = $this->httpRequest($search_url, $auth_header, "GET");
        return $response;
    }

    function httpRequest($url, $auth_header, $method, $body = NULL)
    {
        if (!$method) {
            $method = "GET";
        };

        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_HEADER, 0);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($curl, CURLOPT_HTTPHEADER, array($auth_header)); // Set the headers.

        if ($body) {
            curl_setopt($curl, CURLOPT_POST, 1);
            curl_setopt($curl, CURLOPT_POSTFIELDS, $body);
            curl_setopt($curl, CURLOPT_CUSTOMREQUEST, $method);
            curl_setopt($curl, CURLOPT_HTTPHEADER, array($auth_header, "Content-Type: text/xml;charset=utf-8"));
        }

        $data = curl_exec($curl);
        curl_close($curl);
        return $data;
    }}
4

8 回答 8

22

电子邮件地址仅对经过身份验证的用户可用,而不是他/她的连接。

  1. 在授权您的应用程序时,请确保您已向用户请求了r_emailaddress成员权限。身份验证详细介绍了身份验证和授予成员权限。

  2. 进行以下 GET 调用以获取经过身份验证的用户的电子邮件地址:

    GET http://api.linkedin.com/v1/people/~:(email-address)
    
于 2013-01-10T22:31:35.570 回答
16

对于搜索 v2 网址的人

请按照以下网址

 payload = {
        'grant_type': 'authorization_code',
        'code': token,
        'redirect_uri': s.SOCIAL_AUTH_CALLBACK_URL,
        'client_id': s.LINKED_IN_CLIENT_ID,
        'client_secret': s.LINKED_IN_CLIENT_SECRET
    }

POST "https://www.linkedin.com/oauth/v2/accessToken" 

获取访问令牌

GET "https://api.linkedin.com/v2/me"

获取用户数据在标头中发送身份验证令牌

GET "https://api.linkedin.com/v2/emailAddress?q=members&projection=(elements*(handle~))"

获取用户电子邮件地址。

于 2019-04-16T06:57:33.167 回答
7

您可以通过 api $this->userProfileUrl = " https://api.linkedin.com/v1/people/~:(id,first-name,last-name,picture-url,public-profile-url获取电子邮件地址,email-address)?oauth2_access_token= ";

但是您必须设置范围,例如 $oauth->scope = 'r_basicprofile,r_emailaddress'; 使用 Oauth https://developer-programs.linkedin.com/documents/profile-api

或尝试 https://developer.linkedin.com/docs/oauth2

于 2015-11-23T12:22:21.000 回答
5

您可以使用以下 EP 访问linkedin 用户的电子邮件地址:

`https://api.linkedin.com/v2/emailAddress?q=members&projection=(elements*(handle~))`

确保您已在库中定义范围“r_emailaddress”。您可以使用以下 curl 请求来获取数据:

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $Url);
    curl_setopt($ch, CURLOPT_HTTPHEADER, array(
      'Authorization: Bearer '. $token,
      'X-Restli-Protocol-Version: 2.0.0',
      'Accept: application/json',
      'Content-Type: application/json'
    ));
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_VERBOSE, 1);
    curl_setopt($ch, CURLOPT_HEADER, 1);
    $response = curl_exec($ch);
    $headerSize = curl_getinfo($ch, CURLINFO_HEADER_SIZE);
    $body = substr($response, $headerSize);
    $response_body = json_decode($body,true);

$response_body 将返回以下响应:

Array (
    [elements] => Array
        (
            [0] => Array
                (
                    [handle] => urn:li:emailAddress:123456
                    [handle~] => Array
                        (
                            [emailAddress] => your@email.in
                        )

                )

        )

)
于 2019-04-18T05:18:50.840 回答
3

您应该在 AccessToken Request 时传递 '&scope=r_basicprofile+r_emailaddress'

第 1 步:AccessToken 请求将类似于

https://www.linkedin.com/oauth/v2/accessToken?grant_type=authorization_code&code={Your code}&redirect_uri={Yourredirect_uri}&client_id={Your client_id}&client_secret={Your client_secret }&scope=r_liteprofile+r_emailaddress

这将为您返回 AccessToken,您必须使用它再发出 2 个请求 1 用于电子邮件和个人资料详细信息

第 2 步:对于电子邮件请求将类似于

https://api.linkedin.com/v2/emailAddress?q=members&projection=(elements*(handle~))&oauth2_access_token={AccessToken You get from step 1}'

第 3 步:对于基本配置文件请求将类似于

https://api.linkedin.com/v2/me?projection=(id,firstName,lastName,emailAddress,profilePicture(displayImage~:playableStreams))&oauth2_access_token={AccessToken You get from step 1}'
于 2020-04-30T20:25:19.070 回答
1

LinkedIn API 不提供电子邮件地址作为个人资料对象的一部分。请参阅此处的文档以阅读可用的数据。

编辑:见 Kamyar 的回答。显然,截至 2012 年 8 月,LinkedIn 现在允许提取电子邮件地址。

于 2013-01-03T19:21:10.567 回答
0

你可以试试 :

->elements[0]->{"handle~"}->emailAddress

祝你好运

于 2020-08-11T08:51:56.673 回答
-1

第 1 步: AccessToken 请求

$postData = array(
    'grant_type' => 'authorization_code',
    'code' => urldecode(trim($_GET['code'])),
    'redirect_uri' => url_for('social_login/linkedin'),
    'client_id' => CFG_LINKEDIN_APP_ID,
    'client_secret' => CFG_LINKEDIN_SECRET_KEY
);

$ch = curl_init("https://www.linkedin.com/oauth/v2/accessToken");    
curl_setopt($ch, CURLOPT_HEADER, array('Content-Type' => 'application/x-www-form-urlencoded'));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($postData));
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_TIMEOUT, 15);
curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0);
$response = curl_exec($ch);

$header_size = curl_getinfo($ch, CURLINFO_HEADER_SIZE);    
$body = substr($response, $header_size);

curl_close($ch);

if(!$response)
{
    die('Curl error: ' . curl_error($ch));       
}
                
$response = json_decode($body,true);

$response中,您将找到 AccessToken 使用它您必须再提出 2 个请求 1 用于电子邮件和个人资料详细信息

第 2 步:个人资料请求

$access_token = $response['access_token']; 
   
$ch = curl_init('https://api.linkedin.com/v2/me?projection=(id,firstName,lastName,emailAddress,profilePicture(displayImage~:playableStreams))&oauth2_access_token=' . $access_token);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, false);
curl_setopt($ch, CURLOPT_VERBOSE, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_TIMEOUT, 15);        
$response = curl_exec($ch);
curl_close($ch);

第 3 步:对于电子邮件请求

$ch = curl_init('https://api.linkedin.com/v2/emailAddress?q=members&projection=(elements*(handle~))&oauth2_access_token=' . $access_token);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, false);
curl_setopt($ch, CURLOPT_VERBOSE, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_TIMEOUT, 15);        
$response2 = curl_exec($ch);
curl_close($ch);

结果:用户数据

$user = [
    'first_name' => current($response['firstName']['localized']),
    'last_name' => current($response['lastName']['localized']),
    'photo' => $response['profilePicture']['displayImage~']['elements'][0]['identifiers'][0]['identifier'],
    'email' => $response2['elements'][0]['handle~']['emailAddress']
];
于 2021-05-12T04:46:33.917 回答