2017-06-02 59 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变量在函数之外,函数试图使用它的值。一旦我将它移入函数内,函数就能按预期工作。抱歉张贴!