-
Notifications
You must be signed in to change notification settings - Fork 17
/
Copy pathauthorizedResource.php
198 lines (176 loc) · 9.25 KB
/
authorizedResource.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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
<?php
ini_set('display_errors', 'On');
require __DIR__ . '/vendor/autoload.php';
require_once('storage.php');
// Use this class to deserialize error caught
use XeroAPI\XeroPHP\AccountingObjectSerializer;
// Storage Classe uses sessions for storing token > extend to your DB of choice
$storage = new StorageClass();
$xeroTenantId = (string)$storage->getSession()['tenant_id'];
if ($storage->getHasExpired()) {
$provider = new \League\OAuth2\Client\Provider\GenericProvider([
'clientId' => '__YOUR_CLIENT_ID__',
'clientSecret' => '__YOUR_CLIENT_SECRET__',
'redirectUri' => 'http://localhost:8888/xero-php-oauth2-starter/callback.php',
'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'
]);
$newAccessToken = $provider->getAccessToken('refresh_token', [
'refresh_token' => $storage->getRefreshToken()
]);
// Save my token, expiration and refresh token
$storage->setToken(
$newAccessToken->getToken(),
$newAccessToken->getExpires(),
$xeroTenantId,
$newAccessToken->getRefreshToken(),
$newAccessToken->getValues()["id_token"] );
}
$config = XeroAPI\XeroPHP\Configuration::getDefaultConfiguration()->setAccessToken( (string)$storage->getSession()['token'] );
$apiInstance = new XeroAPI\XeroPHP\Api\AccountingApi(
new GuzzleHttp\Client(),
$config
);
$message = "no API calls";
if (isset($_GET['action'])) {
if ($_GET["action"] == 1) {
// Get Organisation details
$apiResponse = $apiInstance->getOrganisations($xeroTenantId);
$message = 'Organisation Name: ' . $apiResponse->getOrganisations()[0]->getName();
} else if ($_GET["action"] == 2) {
// Create Contact
try {
$person = new XeroAPI\XeroPHP\Models\Accounting\ContactPerson;
$person->setFirstName("John")
->setLastName("Smith")
->setEmailAddress("[email protected]")
->setIncludeInEmails(true);
$arr_persons = [];
array_push($arr_persons, $person);
$contact = new XeroAPI\XeroPHP\Models\Accounting\Contact;
$contact->setName('FooBar')
->setFirstName("Foo")
->setLastName("Bar")
->setEmailAddress("[email protected]")
->setContactPersons($arr_persons);
$arr_contacts = [];
array_push($arr_contacts, $contact);
$contacts = new XeroAPI\XeroPHP\Models\Accounting\Contacts;
$contacts->setContacts($arr_contacts);
$apiResponse = $apiInstance->createContacts($xeroTenantId,$contacts);
$message = 'New Contact Name: ' . $apiResponse->getContacts()[0]->getName();
} catch (\XeroAPI\XeroPHP\ApiException $e) {
$error = AccountingObjectSerializer::deserialize(
$e->getResponseBody(),
'\XeroAPI\XeroPHP\Models\Accounting\Error',
[]
);
$message = "ApiException - " . $error->getElements()[0]["validation_errors"][0]["message"];
}
} else if ($_GET["action"] == 3) {
$if_modified_since = new \DateTime("2019-01-02T19:20:30+01:00"); // \DateTime | Only records created or modified since this timestamp will be returned
$if_modified_since = null;
$where = 'Type=="ACCREC"'; // string
$where = null;
$order = null; // string
$ids = null; // string[] | Filter by a comma-separated list of Invoice Ids.
$invoice_numbers = null; // string[] | Filter by a comma-separated list of Invoice Numbers.
$contact_ids = null; // string[] | Filter by a comma-separated list of ContactIDs.
$statuses = array("DRAFT", "SUBMITTED");;
$page = 1; // int | e.g. page=1 – Up to 100 invoices will be returned in a single API call with line items
$include_archived = null; // bool | e.g. includeArchived=true - Contacts with a status of ARCHIVED will be included
$created_by_my_app = null; // bool | When set to true you'll only retrieve Invoices created by your app
$unitdp = null; // int | e.g. unitdp=4 – You can opt in to use four decimal places for unit amounts
try {
$apiResponse = $apiInstance->getInvoices($xeroTenantId, $if_modified_since, $where, $order, $ids, $invoice_numbers, $contact_ids, $statuses, $page, $include_archived, $created_by_my_app, $unitdp);
if ( count($apiResponse->getInvoices()) > 0 ) {
$message = 'Total invoices found: ' . count($apiResponse->getInvoices());
} else {
$message = "No invoices found matching filter criteria";
}
} catch (Exception $e) {
echo 'Exception when calling AccountingApi->getInvoices: ', $e->getMessage(), PHP_EOL;
}
} else if ($_GET["action"] == 4) {
// Create Multiple Contacts
try {
$contact = new XeroAPI\XeroPHP\Models\Accounting\Contact;
$contact->setName('George Jetson')
->setFirstName("George")
->setLastName("Jetson")
->setEmailAddress("[email protected]");
// Add the same contact twice - the first one will succeed, but the
// second contact will throw a validation error which we'll catch.
$arr_contacts = [];
array_push($arr_contacts, $contact);
array_push($arr_contacts, $contact);
$contacts = new XeroAPI\XeroPHP\Models\Accounting\Contacts;
$contacts->setContacts($arr_contacts);
$apiResponse = $apiInstance->createContacts($xeroTenantId,$contacts,false);
$message = 'First contacts created: ' . $apiResponse->getContacts()[0]->getName();
if ($apiResponse->getContacts()[1]->getHasValidationErrors()) {
$message = $message . '<br> Second contact validation error : ' . $apiResponse->getContacts()[1]->getValidationErrors()[0]["message"];
}
} catch (\XeroAPI\XeroPHP\ApiException $e) {
$error = AccountingObjectSerializer::deserialize(
$e->getResponseBody(),
'\XeroAPI\XeroPHP\Models\Accounting\Error',
[]
);
$message = "ApiException - " . $error->getElements()[0]["validation_errors"][0]["message"];
}
} else if ($_GET["action"] == 5) {
$if_modified_since = new \DateTime("2019-01-02T19:20:30+01:00"); // \DateTime | Only records created or modified since this timestamp will be returned
$where = null;
$order = null; // string
$ids = null; // string[] | Filter by a comma-separated list of Invoice Ids.
$page = 1; // int | e.g. page=1 – Up to 100 invoices will be returned in a single API call with line items
$include_archived = null; // bool | e.g. includeArchived=true - Contacts with a status of ARCHIVED will be included
try {
$apiResponse = $apiInstance->getContacts($xeroTenantId, $if_modified_since, $where, $order, $ids, $page, $include_archived);
if ( count($apiResponse->getContacts()) > 0 ) {
$message = 'Total contacts found: ' . count($apiResponse->getContacts());
} else {
$message = "No contacts found matching filter criteria";
}
} catch (Exception $e) {
echo 'Exception when calling AccountingApi->getContacts: ', $e->getMessage(), PHP_EOL;
}
} else if ($_GET["action"] == 6) {
$jwt = new XeroAPI\XeroPHP\JWTClaims();
$jwt->setTokenId((string)$storage->getIdToken() );
// Set access token in order to get authentication event id
$jwt->setTokenAccess( (string)$storage->getAccessToken() );
$jwt->decode();
echo("sub:" . $jwt->getSub() . "<br>");
echo("sid:" . $jwt->getSid() . "<br>");
echo("iss:" . $jwt->getIss() . "<br>");
echo("exp:" . $jwt->getExp() . "<br>");
echo("given name:" . $jwt->getGivenName() . "<br>");
echo("family name:" . $jwt->getFamilyName() . "<br>");
echo("email:" . $jwt->getEmail() . "<br>");
echo("user id:" . $jwt->getXeroUserId() . "<br>");
echo("username:" . $jwt->getPreferredUsername() . "<br>");
echo("session id:" . $jwt->getGlobalSessionId() . "<br>");
echo("authentication_event_id:" . $jwt->getAuthenticationEventId() . "<br>");
}
}
?>
<html>
<body>
<ul>
<li><a href="authorizedResource.php?action=1">Get Organisation Name</a></li>
<li><a href="authorizedResource.php?action=2">Create one Contact</a></li>
<li><a href="authorizedResource.php?action=3">Get Invoice with Filters</a></li>
<li><a href="authorizedResource.php?action=4">Create multiple contacts and summarizeErrors</a></li>
<li><a href="authorizedResource.php?action=5">Get Contact with Filters</a></li>
<li><a href="authorizedResource.php?action=6">Get JWT Claims</a></li>
</ul>
<div>
<?php
echo($message );
?>
</div>
</body>
</html>