Sometimes getting 401 Invalid OAuth token, even after token refresh

Not sure what I am missing here, but after getting a working access token calling the API will work for a bit then stop working. I am assuming the access token has just expiring. The problem is the API will throw a 401 Invalid OAuth token after getting a new token with the refresh token.

The only way to get it working again is going through the OAuth again to get a new token. After getting the new token I can refresh it just fine with the refresh token.

I am a bit confused here. Hope that made sense.

Below is my code to refresh the token.

$getAccessTokenUrl = "" . $clientId . "&client_secret=" . $clientSecret . "&";

if (isset($_POST["refreshToken"])) {
    $refreshToken = $_POST["refreshToken"];
    $url = $getAccessTokenUrl . "grant_type=refresh_token&refresh_token=" . $refreshToken;

// use key 'http' even if you send the request to https://...
$options = array(
    'http' => array(
        'header'  => "Content-type: application/x-www-form-urlencoded\r\n",
        'method'  => 'POST',

$context  = stream_context_create($options);
$result = file_get_contents($url, false, $context);

Why is your refresh_token in $_POST?

Something seems very off with your code/work flow here. As the refresh token should be loaded from memory/database/storage not from $_POST

So not sure whats wrong here as yoru base work flow is wrong.

Also save yourself some hassle and use cURL instead of file_get_contents

I have a PHP user Auth example here

Thanks for the link.

Yea I am in the process of changing all of that but I first wanted to understand why it seems like new tokens aren’t always working as expected. Maybe I will just make the update and go from there so see if I continue having the issue.

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.