PHP code example of academe / xero-php

1. Go to this page and download the library: Download academe/xero-php 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/ */

    

academe / xero-php example snippets


use use Academe\XeroPHP;

// Most of the configuration goes into one place.

$myStorageObject = /* Your OAuth token storage object */

$clientProvider = new XeroPHP\ClientProvider([
    // Account credentials.
    'consumerKey'       => 'your-consumer-key',
    'consumerSecret'    => 'your-consumer-sectet',
    // Current token and secret from storage.
    'oauthToken'            => $myStorageObject->oauthToken,
    'oauthTokenSecret'      => $myStorageObject->oauthTokenSecret,
    // Curresnt session for refreshes also from storage.
    'oauthSessionHandle'    => $myStorageObject->oauthSessionHandle,
    // The local time the OAuth token is expected to expire.
    'oauthExpiresAt'        => $myStorageObject->oauthExpiresAt, // Carbon, Datetime or string
    // Running the Partner Application
    'oauth1Options' => [
        'signature_method' => \GuzzleHttp\Subscriber\Oauth\Oauth1::SIGNATURE_METHOD_RSA, // Default
        'private_key_file' => 'local/path/to/private.pem',
        'private_key_passphrase' => 'your-optional-passphrase', // Optional
    ],
    'clientOptions' => [
        // You will almost always want exceptions off, so Guzzle does not throw an exception
        // on every non-20x response.
        // false is the default if not supplied.
        'exceptions' => false,
        'headers' => [
            // We would like JSON back for most APIs, as it is structured nicely.
            // Exceptions 

if ($refreshableClient->tokenIsRefreshed()) {
    // Maybe save the token or other details, or just log the event.
}

// Refresh the token and get a new provider back:

$clientProvider = $refreshableClient->refreshToken();

// Use the new $clientProvider if you want to create additional refreshable clients.
// Otherwise just keep using the current $refreshableClient.

// The `$refreshableClient` will now have a new Guzzzle client with a refreshed token.
// The new token details are retrieved from the provider, and can then be stored,
// assuming your callback has not already stored it. Store these three details:

$clientProvider->oauthToken;        // String
$clientProvider->oauthTokenSecret;  // String
$clientProvider->oauthExpiresAt;    // Carbon time

// A guard window of five minutes (300 seconds).
// If we have entered the last 300 seconds of the token lifetime,
// then renew it immediately.

if ($refreshableClient->isExpired(60*5)) {
    $refreshableClient->refreshToken();
}

// Get the first page of payruns.
// This assumes the payrun Endpoint was supplied as the default endpoint:
$response = $refreshableClient->get('payruns', ['query' => ['page' => 1]]);

// or if no default endpoint was given in the config:
$response = $refreshableClient->get(
    XeroPHP\Endpoint::createGbPayroll('payruns')->getUrl(),
    ['query' => ['page' => 1]]
);

// Assuming all is fine, parse the response to an array.
$bodyArray = XeroPHP\Helper::parseResponse($response);

// Instantiate the response data object.
$result = new XeroPHP\ResponseMessage($bodyArray);

// OR just use the PSR-7 response without the need to parse it first:
$result = new XeroPHP\ResponseMessage($response);

### Navigating the Response Message

// Now we can navigate the data.

// At the top level will be metadata.

echo $result->getMetadata()->id;
// 14c9fc04-f825-4163-a0cf-3c2bc31c989d

echo $result->getPagination()->pageSize;
// 100

var_dump($result->getPagination()->toArray());
// array(4) {
//   ["page"]=>
//   int(1)
//   ["pageSize"]=>
//   int(100)
//   ["pageCount"]=>
//   int(1)
//   ["itemCount"]=>
//   int(3)
// }

The results object provides access to structured data of resources fetched from the API.
It is a value object, and does not provide any ORM-like functionality (e.g. you can't
update it then `PUT` it back to Xero, at least not yet).

A `ResponseMessage` object may contain a resource, a collection or resources, or may be empty.
The following methods indicate what the response contains:


$value = $result->foo->bar->where->amI;
var_dump($value->isEmpty());
// bool(true)

try {
    $response = $client->get('PayRuns', []);
} catch (\Exception $e) {
    $response = $e->getResponse();
    ...
}

$response = $client->get('PayRuns', ['exceptions' => false]);