So my logic to handle the API context and keep it up-to-date is as follows:
public static function loadApiContext()
{
$filePath = BUNQ_API_CONTEXT_PATH;
if (!static::validateExistingContext($filePath))
{
$apiContext = ApiContext::createForPsd2(
BunqEnumApiEnvironmentType::PRODUCTION(),
SecurityUtil::getCertificateFromFile(PSD2_SIGNING_CERTIFICATE_PATH),
new PrivateKey(static::getPrivateKey()),
[SecurityUtil::getCertificateFromFile(PSD2_CA_CHAIN_PATH)],
DESCRIPTION
);
$apiContextJson = $apiContext->toJson();
Storage::put($filePath, $apiContextJson); // Laravel storage (verified to be working).
BunqContext::loadApiContext($apiContext);
}
}
protected static function validateExistingContext($filePath)
{
if (Storage::exists($filePath))
{
$apiContextJson = Storage::get($filePath); // Retrieve existing context from storage.
$apiContext = ApiContext::fromJson($apiContextJson);
try
{
$currentContext = BunqContext::getApiContext();
if ($currentContext->getApiKey() === $apiContext->getApiKey())
return true;
}
catch (BunqException $e) { }
if ($apiContext->ensureSessionActive())
{
$apiContextJson = $apiContext->toJson();
Storage::put($filePath, $apiContextJson);
}
BunqContext::loadApiContext($apiContext); // Source of error.
return true;
}
return false;
}
This occasionally leads to a TooManyRequestsException on the final BunqContext::loadApiContext
in validateExistingContext
. This is due to the User::listing
call in UserContext
.
Now I'm wondering if anyone can see a flaw in the methods I'm using. This seems to happen sometimes when the context doesn't even need to be refreshed.
Thanks for any help!