PHP code example of cloudadic / twin23-oauth2-php-sdk
1. Go to this page and download the library: Download cloudadic/twin23-oauth2-php-sdk 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/ */
cloudadic / twin23-oauth2-php-sdk example snippets
// In order to get your OAuth 2 credentials you need to register your app at
$client = new Twin23\OAuth2\Client([
// The client ID assigned to you by the provided
'client_id' => 'YOUR_CLIENT_ID',
// The client secret provided
'client_secret' => 'YOUR_CLIENT_SECRET',
// Redirect URL
'redirect_uri' => 'http://my.website.com/redirect-page',
// Permissions to the data that you would like to retrieve
'scope' => ['name', 'email', 'photo', 'phone']
]);
// Fetch the authorization URL. You can assign this to link on your web page.
$authorizationUrl = $client->getAuthorizationUrl();
if (!empty($_GET['code'])) {
try {
// Try to get an access token using the authorization code grant.
$accessToken = $client->getAccessToken('authorization_code', [
'code' => $_GET['code']
]);
// We have an access token, which we may use in authenticated
// requests against the service provider's API.
echo 'Access Token: ' . $accessToken->getToken() . "<br>";
echo 'Refresh Token: ' . $accessToken->getRefreshToken() . "<br>";
echo 'Expired in: ' . $accessToken->getExpires() . "<br>";
echo 'Already expired? ' . ($accessToken->hasExpired() ? 'expired' : 'not expired') . "<br>";
// Using the access token, we may look up details about the user
} catch (\Twin23\Exception\ResponseException $e) {
// Failed to get the access token or user details.
exit($e->getMessage());
}
}
$existingAccessToken = $client->getAccessToken('authorization_code', [
'code' => $code
]);
if ($existingAccessToken->hasExpired()) {
$newAccessToken = $client->getAccessToken('refresh_token', [
'refresh_token' => $existingAccessToken->getRefreshToken()
]);
// Purge old access token and store new access token to your data store.
}