LinkedIn API-如何使用Oauth2&;发布公司更新;PHP

LinkedIn API-如何使用Oauth2&;发布公司更新;PHP,linkedin,Linkedin,我正在尝试修改LinkedIn的授权代码示例,以发布公司更新 让原始代码示例正常工作,这意味着我可以登录到我的用户配置文件。所以下一步就是发布更新 我们在Internet和stackoverflow.com上找到了一些信息,结果是在下面的代码中找到了函数PostUpdate()。其余的代码几乎直接来自Linkedin代码示例 所以这段代码似乎在运行,我没有收到任何错误报告,但我在公司页面上也没有得到任何更新。我注意到一个问题,成功登录后,代码会打印“Hello$user->firstName$u

我正在尝试修改LinkedIn的授权代码示例,以发布公司更新

让原始代码示例正常工作,这意味着我可以登录到我的用户配置文件。所以下一步就是发布更新

我们在Internet和stackoverflow.com上找到了一些信息,结果是在下面的代码中找到了函数PostUpdate()。其余的代码几乎直接来自Linkedin代码示例

所以这段代码似乎在运行,我没有收到任何错误报告,但我在公司页面上也没有得到任何更新。我注意到一个问题,成功登录后,代码会打印“Hello$user->firstName$user->lastName”。但我的名字不会显示在屏幕上。“Hello”是这样的,所以这可能表示可能在哪里发现了问题

<?php
//config.php contains the API KEY, SECRET, AND COMPANY ID
    //define('API_KEY',      'your key');
    //define('API_SECRET',   'your secret');
    //define('COMPANY_ID',   'your company id');
require_once('config.php');

// You must pre-register your redirect_uri at https://www.linkedin.com/secure/developer
define('REDIRECT_URI', 'http://' . $_SERVER['SERVER_NAME'] . $_SERVER['SCRIPT_NAME']);
define('SCOPE',        'r_basicprofile r_emailaddress w_share rw_company_admin');

// You'll probably use a database
session_name('linkedin');
session_start();

// OAuth 2 Control Flow
if (isset($_GET['error'])) {
    // LinkedIn returned an error
    print $_GET['error'] . ': ' . $_GET['error_description'];
    exit;
} elseif (isset($_GET['code'])) {
    // User authorized your application
    if ($_SESSION['state'] == $_GET['state']) {
        // Get token so you can make API calls
        getAccessToken();
    } else {
        // CSRF attack? Or did you mix up your states?
        exit;
    }
} else {
    if ((empty($_SESSION['expires_at'])) || (time() > $_SESSION['expires_at'])) {
        // Token has expired, clear the state
        $_SESSION = array();
    }
    if (empty($_SESSION['access_token'])) {
        // Start authorization process
        getAuthorizationCode();
    }
}

// Congratulations! You have a valid token. Now fetch your profile
$user = fetch('GET', '/v1/people/~:(firstName,lastName)');

print "Hello $user->firstName $user->lastName.";

// temporary message content for test purposes
    $xml_txt = "<?xml version='1.0' encoding='UTF-8'?> 
      <share>
      <visibility>
        <code>anyone</code>
      </visibility>
      <comment>Testing a full company share!!!!!</comment>
      <content>
        <submitted­-url>https://www.example.com/test-2.html</submitted-­url>
        <title>Test Share with Content</title>
        <description>content description</description>
        <submitted-image-­url>https://www.example.com/img/internet.jpg</submitted­-image-­url>
      </content>
    </share>";

    //Post the message    
$result = PostUpdate($xml_txt);

//Done
exit;

function PostUpdate($message) {   
     print $_SESSION['access_token'];

    $url = 'https://api.linkedin.com/v1/companies/'. COMPANY_ID . '/shares';
    // build your message
    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $message );
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-type: application/xml', 'Authorization: Bearer ' . $this->access_token));
    $response = curl_exec($ch);
    $http_status = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);
    print_r($response);
    echo $http_status;
} 

function getAuthorizationCode() {
    $params = array(
        'response_type' => 'code',
        'client_id' => API_KEY,
        'scope' => SCOPE,
        'state' => uniqid('', true), // unique long string
        'redirect_uri' => REDIRECT_URI,
    );

    // Authentication request
    $url = 'https://www.linkedin.com/uas/oauth2/authorization?' . http_build_query($params);

    // Needed to identify request when it returns to us
    $_SESSION['state'] = $params['state'];

    // Redirect user to authenticate
    header("Location: $url");
    exit;
}

function getAccessToken() {
    $params = array(
        'grant_type' => 'authorization_code',
        'client_id' => API_KEY,
        'client_secret' => API_SECRET,
        'code' => $_GET['code'],
        'redirect_uri' => REDIRECT_URI,
    );

    // 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;
}

function fetch($method, $resource, $body = '') {
    print $_SESSION['access_token'];

    $opts = array(
        'http'=>array(
            'method' => $method,
            'header' => "Authorization: Bearer " . $_SESSION['access_token'] . "\r\n" . "x-li-format: json\r\n"
        )
    );

    // Need to use HTTPS
    $url = 'https://api.linkedin.com' . $resource;

    // Append query parameters (if there are any)
    if (count($params)) { $url .= '?' . http_build_query($params); }

    // Tell streams to make a (GET, POST, PUT, or DELETE) request
    // And use OAuth 2 access token as Authorization
    $context = stream_context_create($opts);

    // Hocus Pocus
    $response = file_get_contents($url, false, $context);

    // Native PHP object, please
    return json_decode($response);
}

终于成功发布了公司更新(共享)

导致LinkedIn代码示例()不起作用的一个问题是文件_get_contents()不起作用,这是因为PHP.ini中未启用allow_url_fopen。我相信默认情况下不会启用allow_url_fopen,因为这是一个安全问题。我找到了一个在线使用cUrl的方法。请参阅下面的代码

//首先,在
getAccessToken()
replace中:

 $response = file_get_contents($url, false, $context)

下面是添加到LinkedIn代码示例中的代码,在 '打印“Hello$user->firstName$user->lastName.”;'


也许它并不漂亮,但经过几天的努力,我感到异常高兴。感谢LinkedIn提供了一个让所有人都用一个内置的“问题”重新发明轮子代码的示例。如果你们用你们提供的代码样本一样的方法擦屁股,你们的内衣上会有三英寸的干滑痕。你知道我在说什么。

如果这个答案解决了问题,你可以将它标记为“无标题答案”
$response = curl_get_contents($url);
// temporary message content for test purposes
$xml_txt = "<?xml version='1.0' encoding='UTF-8'?> 
  <share>
    <visibility>
      <code>anyone</code>
     </visibility>
      <comment>There are a lot of great career opportunities here!</comment>
   </share>";

//Post the message    
$result = PostUpdate($xml_txt);

//Done
exit;

function PostUpdate($message) {   
     print 'here in PostUpdate <br />';
     print '$message = ' . $message .' <br />';
    $url = 'https://api.linkedin.com/v1/companies/'. COMPANY_ID . '/shares';
    // build your message
    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $message );
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-type: application/xml', 'Authorization: Bearer ' . $_SESSION['access_token']));
    $response = curl_exec($ch);
    $http_status = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);
    print_r($response);
    echo '$http_status = '. $http_status;
} 


function curl_get_contents($url)
{
    $ch = curl_init();

    curl_setopt($ch, CURLOPT_HEADER, 0);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_URL, $url);

    $data = curl_exec($ch);
    curl_close($ch);

    return $data;
}