2013-02-27 172 views
3

以下php代碼不能用於獲取訪問令牌 在客戶端ID和密鑰中,我用我的真實客戶端ID和密鑰替換。Instagram從PHP代碼獲取訪問代碼

<?php 
$client_id = 'MY CLIENT ID'; 
$client_secret = 'MY CLIENT SECRET'; 
$redirect_uri = 'http://localhost/instagram/demo.php'; 
$scope = 'basic+likes+comments+relationships'; 

$url = "https://api.instagram.com/oauth/authorize?client_id=$client_id&redirect_uri=$redirect_uri&scope=$scope&response_type=code"; 

if(!isset($_GET['code'])) 
{ 
    echo '<a href="'.$url.'">Login With Instagram</a>'; 
} 
else 
{ 
    $code = $_GET['code']; 

$apiData = array(
    'client_id'  => $client_id, 
    'client_secret' => $client_secret, 
    'grant_type'  => 'authorization_code', 
    'redirect_uri' => $redirect_uri, 
    'code'   => $code 
); 

$apiHost = 'https://api.instagram.com/oauth/access_token'; 

$ch = curl_init(); 
curl_setopt($ch, CURLOPT_URL, $apiHost); 
curl_setopt($ch, CURLOPT_POST, count($apiData)); 
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($apiData)); 
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Accept: application/json')); 
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); 
$jsonData = curl_exec($ch); 
curl_close($ch); 

var_dump($jsonData); 
$user = @json_decode($jsonData); 

echo '<pre>'; 
print_r($user); 
exit; 
} 
?> 

上面的代碼總是返回false ..我不明白爲什麼這是行不通的。

有人調試此代碼,讓我知道什麼是我的代碼中的問題?

回答

0

那麼你的代碼有幾個問題。對於一個它看起來像你的redirect_uri是本地主機。顯然localhost到Instagram是他們自己的服務器。您需要提供FQDN /全球可訪問的網址。

而且從http://php.net/manual/en/function.curl-setopt.php代碼

curl_setopt($ch, CURLOPT_POST, count($apiData)); 

是否應簡單是

curl_setopt($ch, CURLOPT_POST, 1); 
0

你的代碼是正確的,但你需要改變

$redirect_uri = 'your site addres (not localhost)';

例子:

$client_id  = 'YOUR_CLIENT_ID'; 
$client_secret = 'YOUR CLIENT SECRET'; 
$redirect_uri  = 'http://www.YOUR_SERVER.com/instagram/demo.php'; 
$scope   = 'basic+likes+comments+relationships'; 

如果使用此更改執行此腳本,您可以獲得此結果。

stdClass Object 
(
    [access_token] => 'your_ID'.xxxxxxx.xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx 
    [user] => stdClass Object 
     (
      [username] => 'your username' 
      [bio] => 
      [website] => 
      [profile_picture] => 'your url picture profile' 
      [full_name] => 
      [id] => 'your_ID' 
     ) 

) 
2

因爲它是HTTPS已經所以你需要把這個代碼

curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); 
curl_setopt($ch,CURLOPT_SSL_VERIFYHOST, false); 

這不是您的重定向URI是本地的。這是因爲SSL_VERIFYPEER未設置在捲曲選項中