-
Notifications
You must be signed in to change notification settings - Fork 25
/
callback.php
executable file
·82 lines (70 loc) · 2.98 KB
/
callback.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
<?php
ini_set('display_errors', 'On');
require __DIR__ . '/vendor/autoload.php';
require_once('storage.php');
$dotenv = Dotenv\Dotenv::createImmutable(__DIR__);
$dotenv->load();
$clientId = getenv('CLIENT_ID');
$clientSecret = getenv('CLIENT_SECRET');
$redirectUri = getenv('REDIRECT_URI');
// Storage Classe uses sessions for storing token > extend to your DB of choice
$storage = new StorageClass();
$provider = new \League\OAuth2\Client\Provider\GenericProvider([
'clientId' => $clientId,
'clientSecret' => $clientSecret,
'redirectUri' => $redirectUri,
'urlAuthorize' => 'https://login.xero.com/identity/connect/authorize',
'urlAccessToken' => 'https://identity.xero.com/connect/token',
'urlResourceOwnerDetails' => 'https://api.xero.com/api.xro/2.0/Organisation'
]);
// If we don't have an authorization code then get one
if (!isset($_GET['code'])) {
echo "Something went wrong, no authorization code found";
header("Location: index.php?error=true");
exit();
// Check given state against previously stored one to mitigate CSRF attack
} elseif (empty($_GET['state']) || ($_GET['state'] !== $_SESSION['oauth2state'])) {
echo "Invalid State";
unset($_SESSION['oauth2state']);
exit('Invalid state');
} else {
try {
// Try to get an access token using the authorization code grant.
$accessToken = $provider->getAccessToken('authorization_code', [
'code' => $_GET['code']
]);
$jwt = new XeroAPI\XeroPHP\JWTClaims();
$jwt->setTokenId($accessToken->getValues()["id_token"]);
$jwt->decode();
$config = XeroAPI\XeroPHP\Configuration::getDefaultConfiguration()->setAccessToken( (string)$accessToken->getToken() );
$identityInstance = new XeroAPI\XeroPHP\Api\IdentityApi(
new GuzzleHttp\Client(),
$config
);
// Get Array of Tenant Ids
$result = $identityInstance->getConnections();
// Save my token, expiration and tenant_id
$storage->setToken(
$accessToken->getToken(),
$accessToken->getExpires(),
$result[0]->getTenantId(),
$accessToken->getRefreshToken(),
$accessToken->getValues()["id_token"]
);
header('Location: ' . './get.php');
exit();
} catch (\League\OAuth2\Client\Provider\Exception\IdentityProviderException $e) {
echo "Failed!!!";
// Failed to get the access token or user details.
exit($e->getMessage());
}
}
?>
<html>
<head>
<title>My App</title>
</head>
<body>
Opps! Should have redirected to <a href="get.php">to this page</a>
</body>
</html>