2017-06-02 57 views
0

所以我試圖通過PHP使用https://api.thetvdb.com/swagger api。通過php curl發送「curl -X GET -header」不起作用

我已經成功地管理使用下面的方法來從一個API JWT令牌:

function tvdb_post ($url, $userinfo) { 
    $ch = curl_init($url); 
    $payload = json_encode($userinfo); 
    curl_setopt($ch, CURLOPT_POSTFIELDS, $payload); 
    curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type:application/json')); 
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); 
    $result = curl_exec($ch); 
    curl_close($ch); 
    $return = json_decode($result, true); 

    return $return; 
} 

$userinfo = array (
    'username' => 'dstealth', 
    'userkey' => '***{redacted}***', 
    'apikey' => '***{redacted}***' 
); 

$token = tvdb_post('https://api.thetvdb.com/login', $userinfo); 

我然後複製令牌,並提交有關的API網頁提交令牌。它給了我一個確認信息。

問題出現在下一步。如果我在API網站頁面上執行前面的步驟,然後在API網頁上執行下一步,它就可以正常工作。但是當我嘗試將下一步轉換爲PHP時,它給了我一個「未授權」的消息。

在API網頁上的下一個步驟是:

curl -X GET --header 'Accept: application/json' --header 'Authorization: Bearer <token>' 'https://api.thetvdb.com/refresh_token' 
// returns a response code 200 and refreshes the token successfully. 

在PHP我的下一個步驟是這樣的:

$authorization = "Authorization: Bearer ***{redacted}*** "; 

function tvdb_api ($url) { 
    $ch = curl_init(); 
    curl_setopt($ch, CURLOPT_URL, $url); 
    curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json', $authorization)); 
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); 
    $json = curl_exec($ch); 
    curl_close($ch); 
    $array = json_decode($json, true); 

    return $array; 
} 

$refresh = tvdb_api('https://api.thetvdb.com/refresh_token'); 
// This returns a "Not Authorized" error. 

誰能告訴我,我轉換之間做錯了什麼下一步從API網頁到PHP?

+0

'$ authorization'變量是否可以在函數範圍內訪問?我想不是......將它作爲論據或使其成爲全球性的。 –

+0

......當然'-X GET'不應該在原始行上使用...請參閱https://stackoverflow.com/questions/8498371/curl-get-and-x-get/ 8502004#8502004 –

回答

0

$ authorization變量在函數之外,函數試圖使用它的值。一旦我將它移入函數內,函數就能按預期工作。抱歉張貼!