所以我正在尝试使用https://api.thetvdb.com/swagger api php。
我已经成功地使用以下方法从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之间做错了什么?
$授权变量不在函数之外,并且该函数试图使用其值。一旦我将其移动到功能中,功能按预期工作。很抱歉发布!