I have a Magento 2.3 store that I'm trying to sync some data to Quickbooks Online. I've created a QBO App but this is my first time using oauth and I'm a bit confused on how to store and use the access / refresh tokens.
According to Quickbooks doc I need to store the latest refresh token:
Each access token can only be valid for an hour after its creation. If you try to make an API call after an hour with the same access token, the request will be blocked by QBO. That is what refresh token used for. It is used to request a new access token after access token expired, so you can still access to the QBO company after an hour. Just remember, whenever you make a refreshToken API call, always STORE THE LATEST REFRESH TOKEN value in your session or database. In QuickBooks Online OAuth 2 protocol, it is not the access token you should store, it is the refresh token you need to store.
So my question is, how do I properly store and call upon my refresh token to generate a new access token each time my API makes a call to sync data.
Currently, I'm directly using my OAuth tokens by hard coding them into my helper file:
<?php
namespace Company\Module\Helper;
use QuickBooksOnline\API\DataService\DataService;
class Data extends \Magento\Framework\App\Helper\AbstractHelper
{
public function getConfigurationSetting()
{
$dataService = DataService::Configure(array(
'auth_mode' => 'oauth2',
'ClientID' => '<<my ClientID',
'ClientSecret' => '<<my ClientSecret>>',
'accessTokenKey' => 'xxxxxx',
'refreshTokenKey' => 'xxxxxx',
'QBORealmID' => "123xxxxxxx",
'baseUrl' => 'Development'
));
$OAuth2LoginHelper = $dataService->getOAuth2LoginHelper();
$refreshedAccessTokenObj = $OAuth2LoginHelper->refreshToken();
$error = $OAuth2LoginHelper->getLastError();
if ($error){
$dataService->throwExceptionOnError(true);
} else {
$dataService->updateOAuth2Token($refreshedAccessTokenObj);
}
return $dataService;
}
}
And then I'm calling that from my controller:
<?php
namespace Company\Module\Observer;
use Magento\Framework\Event\ObserverInterface;
use QuickBooksOnline\API\DataService\DataService;
class CreateQbInvoice implements ObserverInterface
{
protected $helperData;
public function __construct(
\Company\Module\Helper\Data $helperData
){
$this->helperData = $helperData;
}
public function execute()
{
// Prep Data Services
$dataService = $this->helperData->getConfigurationSetting();
...
Now this works until my access token expires and I need to generate a new one, I'm just not sure how to update my access token and store the new refresh token properly to keep access to my app always refreshed.