Search code examples
phpapioauthquickbooksquickbooks-online

Can only get access token for QuickBooks API once


I'm using PHPoAuthLib in order to connect to the QuickBooks API per their example

When I follow their example, the first request that I make to the API works perfectly:

$result = json_decode($quickbooksService->request($url));
echo 'result: <pre>' . print_r($result, true) . '</pre>';

However in their example they use $_GET['oauth_token'] and $_GET['oauth_verifier'] to request an access token, and these values are only available on the $_GET server variable during the single callback from QuickBooks Online immediately after my app has been authorized.

For future requests there are no such examples on PHPoAuthLib's docs, so I tried a quick homebrew solution:

  1. Save the response from QBO somewhere

if (!empty($_GET['oauth_token']) {
    file_put_contents("token.txt", json_encode([
        'oauth_token' => $_GET['oauth_token'],
        'oauth_verifier' => $_GET['oauth_verifier'],
        'realm_id' => $_GET['realmId']
    ]));
}
  1. Use that response again later

$token = json_decode(file_get_contents("token.txt"));
$quickbooksService->requestAccessToken(
    $token->oauth_token,
    $token->oauth_verifier
    // $token->getRequestTokenSecret() is not necessary - it will be automatically populated
);
// At this point my app crashes and return a 500 error
// Further code does not run

The error I receive is:

TokenResponseException in StreamClient.php line 68: Failed to request resource. HTTP Code: HTTP/1.1 401 Unauthorized

Remember that the token and verifier work perfectly if I use them immediately after the app is authorized. If I save them to a file and attempt to re-use them 30 seconds later, this happens.

I think it might be a fundamental misconception about OAuth 1.0


Solution

  • I don't think what you have is a correct OAuth implementation. Have you read the OAuth spec and implemented as it's defined there?

    Once you have a request token and a verifier, you use those to get an access token.

    That access token is then good for 6 months.

    It looks like you're trying to use a short-lived request token to continually fetch access tokens instead. That won't work.

    i.e. If you're doing this everytime you want to make another request:

    $quickbooksService->requestAccessToken(

    Then you're doing something wrong. You should be doing that ONCE every 6 months, and that's it.

    Working code here:

    Spec is here: