2013-12-10 47 views
1

這是我第一次與LinkedIn的API的工作,我試圖按照官方文檔在這個例子:LinkedIn PHP API不設置訪問令牌笨

[http://developer.linkedin.com/documents/code-samples][1] 

我已經重構同樣的程序代碼到所謂Auth一個笨控制器類:我使用

<?php if (!defined('BASEPATH')) die(); 

class Auth extends CI_Controller 
{ 

    public function __construct() 
    { 

     parent::__construct(); 

     define('API_KEY',  $this->config->item('key')); 
     define('API_SECRET', $this->config->item('secret')); 
     define('REDIRECT_URI', 'http://' . $_SERVER['SERVER_NAME'] . ':8000/auth'); 
     define('SCOPE',  'r_basicprofile r_emailaddress rw_groups'); 

    } 

    public function index() 
    { 
     var_dump($this->session->all_userdata()); 
     if (!empty($this->session->userdata('state'))) { 
     $user = $this->fetch('GET', '/v1/people/~:(firstName,lastName)'); 
     print "Hello $user->firstName $user->lastName."; 
     } else { 
     // $this->session->sess_destroy(); 
     echo anchor('auth/oauth', 'Sign in with Linkedin'); 
     } 

    } 


    public function oauth() 
    { 
     // 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 ($this->session->userdata('state') == $_GET['state']) { 
       // Get token so you can make API calls 
       $this->getAccessToken(); 
      } else { 
       // CSRF attack? Or did you mix up your states? 
       exit; 
      } 
     } else { 
      if ((empty($this->session->userdata('expires_at'))) || (time() > $this->session->userdata('expires_at'))) { 
       // Token has expired, clear the state 
       $this->session->sess_destroy(); 
      } 
      if (empty($this->session->userdata('access_token'))) { 
       echo "here I am"; 
       // Start authorization process 
       $this->getAuthorizationCode(); 
      } 
     } 

    } 

    protected 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 

     $this->session->set_userdata('access_token', $token->access_token); 
     $this->session->set_userdata('expires_in', $token->expires_in); 
     $this->session->set_userdata('expires_at', time() + $this->session->userdata('expires_in')); 

     return true; 
    } 

    protected 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']; 
     $this->session->set_userdata('state', $params['state']); 

     // Redirect user to authenticate 
     redirect($url); 
    } 


    protected function fetch($method, $resource, $body = '') { 
     $params = array('oauth2_access_token' => $this->session->userdata('access_token'), 
         'format' => 'json', 
       ); 

     // Need to use HTTPS 
     $url = 'https://api.linkedin.com' . $resource . '?' . http_build_query($params); 
     // Tell streams to make a (GET, POST, PUT, or DELETE) request 
     $context = stream_context_create(
         array('http' => 
          array('method' => $method, 
          ) 
         ) 
        ); 


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

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

    public function logout() 
    { 
     $_SESSION = array(); 
     $this->load->view('comment_index'); 
    } 

} 

數據庫來存儲會話,我期待access_token存儲在我的序列化的字段中的值的一個叫user_data 。但我什麼也沒得到。當前會話的輸出是:

array (size=5) 
    'session_id' => string '1dfcbc17bf0346424726c7cace63501b' (length=32) 
    'ip_address' => string '`127.0.0.1`' (length=9) 
    'user_agent' => string 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10.8; rv:25.0) Gecko/20100101 Firefox/25.0' (length=81) 
    'last_activity' => int 1386687134 
    'user_data' => string '' (length=0) 

我不明白爲什麼LinkedIn是不是給我回令牌存儲。由於redirect_url,我無法正確調試此代碼。到目前爲止,什麼工作是:

  1. 用戶重定向到授權窗口,其中烏爾:https://www.linkedin.com/uas/oauth2/authorization?response_type=code&client_id=75y11f289134ga&scope=r_basicprofile+r_emailaddress+rw_groups&state=52a72cc4e54f36.03304050&redirect_uri=http%3A%2F%2F127.0.0.1%3A8000%2Fauth

  2. 用戶被重定向到auth動作,而不與此網址的任何錯誤:http://127.0.0.1:8000/auth?碼= AQTWPFJqnZlBZmFByb3Vbjkf4jtNvn8C7atg5iM6iXFW3ON_SrM3uJ9h8AiF1RbMjgGt_NpDq4cTPL1qw8uNiA_vsOv1H3lpxu0IxHVx_sa9rDAinbo & state = 52a72d109261d4.41607693

但是我的個人資料數據在哪裏?如何以及在哪裏進行api調用以檢索配置文件數據?請幫忙

回答

4

我在Codeigniter中也是這樣做的。

以下是獲取Auth用戶配置文件的過程。

  1. 爲LinkedIn

    創建庫
    defined('BASEPATH') OR exit('No direct script access allowed'); 
    
    /** 
    * CodeIgniter Linked API Class 
    * 
    * 
    * @package   CodeIgniter 
    * @subpackage  Libraries 
    * @category  Libraries 
    * @author   Muhamamd Hafeez 
    */ 
    class Linkedin { 
    
        function __construct(){ 
    
        } 
    
        public 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; 
        } 
    
        public 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; 
        } 
    
        public function fetch($method, $resource, $body = '') { 
         $params = array('oauth2_access_token' => $_SESSION['access_token'], 
          'format' => 'json', 
         ); 
    
         // Need to use HTTPS 
         $url = 'https://api.linkedin.com' . $resource . '?' . http_build_query($params); 
         // Tell streams to make a (GET, POST, PUT, or DELETE) request 
         $context = stream_context_create(
           array('http' => 
            array('method' => $method, 
            ) 
           ) 
         ); 
    
    
         // Hocus Pocus 
         $response = file_get_contents($url, false, $context); 
    
         // Native PHP object, please 
         return json_decode($response); 
        } 
    
    } 
    
    /* End of file Linked.php */ 
    /* Location: ./application/libraries/linkedin.php */ 
    
  2. 把你所有的常量的東西,在confin/constants.php

    define('API_KEY', 'Put Yoour API_KEY here'); 
    define('API_SECRET', 'Put Yoour API_SECRET here'); 
    define('REDIRECT_URI', 'Put Yoour REDIRECT_URI here'); 
    define('SCOPE', 'r_fullprofile r_emailaddress rw_nus r_contactinfo r_network'); 
    
  3. 現在控制器

    class Profile extends CI_Controller { 
    
        function __construct() { 
         parent:: __construct(); 
         $this->load->library('linkedin'); // load library 
         session_name('linkedin'); 
         session_start(); 
        } 
    
        // linkedin login script 
        function profile() { 
         // OAuth 2 Control Flow 
         if (isset($_GET['error'])) { 
          // LinkedIn returned an error 
          // load any error view here 
          exit; 
         } elseif (isset($_GET['code'])) { 
          // User authorized your application 
          if ($_SESSION['state'] == $_GET['state']) { 
           // Get token so you can make API calls 
           $this->linkedin->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 
           $this->linkedin->getAuthorizationCode(); 
          } 
         } 
         // define the array of profile fields 
         $profile_fileds = array(
          'id', 
          'firstName', 
          'maiden-name', 
          'lastName', 
          'picture-url', 
          'email-address', 
          'location:(country:(code))', 
          'industry', 
          'summary', 
          'specialties', 
          'interests', 
          'public-profile-url', 
          'last-modified-timestamp', 
          'num-recommenders', 
          'date-of-birth', 
         ); 
         $profileData = $this->linkedin->fetch('GET', '/v1/people/~:(' . implode(',', $profile_fileds) . ')'); 
         if ($profileData) { 
          // save profile or do whatever you want 
         } else { 
          // linked return an empty array of profile data 
         } 
        } 
    
    } 
    
+0

非常感謝您貢獻此代碼。我會對它進行測試,然後馬上回到你身邊。 –

+0

我用這個代碼..但是當我試圖存儲$ profileData在sesion它不起作用..請幫助 – Brett

+0

@Brett你能分享你的代碼嗎? – DMH