0

So i'm trying to use the https://api.thetvdb.com/swagger api via PHP.

I've successfully managed to get a JWT token from the API using the following method:

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);

I then copy the token and submit it on the API webpage to submit the token. It gives me a confirmation message.

The problem arises from the next step. If I do the previous steps ON the API website page, and then do the next step ON the API webpage, it works just fine. But when I try to convert the next step into PHP, it gives me a "Not Authorized" messaged.

The next step on the API webpage is:

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.

in php my next step looks like this:

$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.

Can anyone please tell me what i'm doing wrong between converting the next step from the API webpage to php?

Dal
  • 107
  • 1
  • 4
  • 11
  • 1
    Is `$authorization` variable accessible in the function scope? I guess not... Feed it as argument or make it global. – Ruby Racer Jun 02 '17 at 06:57
  • ...and of course `-X GET` shouldn't have been used on the original line at all... See https://stackoverflow.com/questions/8498371/curl-get-and-x-get/8502004#8502004 – Daniel Stenberg Jun 02 '17 at 07:31

1 Answers1

0

The $authorization variable was outside the function and the function was trying to use it's values. Once I moved it inside the function the function worked as expected. Sorry for posting!

Dal
  • 107
  • 1
  • 4
  • 11