1. Go to this page and download the library: Download vaclavvanik/oauth2-token library. Choose the download type require.
2. Extract the ZIP file and open the index.php.
3. Add this code to the index.php.
<?php
require_once('vendor/autoload.php');
/* Start to develop here. Best regards https://php-download.com/ */
vaclavvanik / oauth2-token example snippets
declare(strict_types=1);
use VaclavVanik\Oauth2Token\AccessToken;
use VaclavVanik\Oauth2Token\TokenProvider;
use VaclavVanik\Oauth2Token\TokenRequest;
final class AcmeTokenProvider implements TokenProvider
{
// ... your PSR-18 / Guzzle / curl call ...
public function getToken(TokenRequest $request): AccessToken
{
$body = $this->post('https://acme.example/oauth/token', [
'grant_type' => 'client_credentials',
'client_id' => $request->getClientId(),
'client_secret' => $request->getClientSecret(),
'scope' => $request->getScope(), // "read write" or null
]);
return AccessToken::fromValidatedArray($body);
}
}
declare(strict_types=1);
use VaclavVanik\Oauth2Token\CachingTokenProviderFactory;
use VaclavVanik\Oauth2Token\RefreshableTokenProvider;
// Both factory methods return a RefreshableTokenProvider (getToken() + forget()).
// Shared across processes - the token survives until it expires.
$provider = CachingTokenProviderFactory::createJsonFile(new AcmeTokenProvider(), '/var/cache/acme-token.json');
// Or, for a single long-running process:
$provider = CachingTokenProviderFactory::createMemory(new AcmeTokenProvider());
declare(strict_types=1);
use VaclavVanik\Oauth2Token\TokenRequest;
$token = $provider->getToken(new TokenRequest($clientId, $clientSecret)); // or (..., ['read', 'write'])
$httpRequest = $httpRequest->withHeader('Authorization', $token->headerValue()); // "Bearer eyJhbGci..."
declare(strict_types=1);
use VaclavVanik\Oauth2Token\TokenRequest;
$tokenRequest = new TokenRequest($clientId, $clientSecret);
$token = $provider->getToken($tokenRequest);
$response = $api->send($httpRequest->withHeader('Authorization', $token->headerValue()));
if ($response->getStatusCode() === 401) { // adjust to your API
$provider->forget($tokenRequest);
$token = $provider->getToken($tokenRequest);
$response = $api->send($httpRequest->withHeader('Authorization', $token->headerValue()));
}
declare(strict_types=1);
use VaclavVanik\Oauth2Token\CachingTokenProviderFactory;
$provider = CachingTokenProviderFactory::createJsonFile(
new AcmeTokenProvider(),
'/var/cache/acme-token.json',
null, // clock - defaults to "now"
120, // refresh delta, in seconds
);
Loading please wait ...
Before you can download the PHP files, the dependencies should be resolved. This can take some minutes. Please be patient.