Skip to content

Commit

Permalink
feat: add job to renew token automatically, add ability to unlink
Browse files Browse the repository at this point in the history
  • Loading branch information
wilr committed Jul 1, 2022
1 parent 8b283e6 commit 9b7c968
Show file tree
Hide file tree
Showing 8 changed files with 279 additions and 65 deletions.
13 changes: 13 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
BSD 3-Clause License

Copyright (c) Fullscreen Interactive All rights reserved.

Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:

Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.

Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.

Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
96 changes: 94 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ Silverstripe support for authenication and connecting applications via oauth.
To setup register a Xero Application and define your clientId and clientSecret
as environment variables.

```
```yaml
XERO_CLIENT_ID='123'
XERO_CLIENT_SECRET='123'
```
Expand All @@ -25,13 +25,105 @@ Once those API keys are available, a new tab under the `Settings` admin will
appear for connecting to Xero. Follow the prompts to link the selected account
to your Silverstripe website.

## Renewing the Access Token

Access tokens last 30 days, a scheduled queued job (`RefreshXeroTokenJob`) is
provided which renews the access token on a regular basis.

## Setting up the application in Xero

1. Head to https://developer.xero.com/app/manage/
1. Create a new `Web App`
1. Set the `Redirect URI` to be `https://www.yoursite.com/connectXero`

Note the `connectXero` endpoint in Silverstripe is restricted to `ADMIN` only
users.

## Interacting with the API

```
```php
/** @var \XeroPHP\Application **/
$app = XeroFactory::singleton()->getApplication();
```

Integrating with the API is done via https://github.com/calcinai/xero-php.
Consult that page for further information for creating invoices etc.

#### Creating a Xero Contact from a Member

```php
<?php

use Psr\Log\LoggerInterface;
use SilverStripe\ORM\DataExtension;
use FullscreenInteractive\SilverStripeXero\XeroFactory;
use SilverStripe\Core\Injector\Injector;

class XeroMemberExtension extends DataExtension
{
private static $db = [
'XeroContactID' => 'Varchar'
];

public function updateCMSFields(FieldList $fields)
{
$fields->makeFieldReadonly('XeroContactID');
}

public function getXeroContact()
{
try {
$xero = XeroFactory::singleton()->getApplication();
} catch (Throwable $e) {
$xero = null;
}

if ($xero) {
try {
$contact = null;

if ($id = $this->owner->XeroContactID) {
$contact = $xero->loadByGUID('Accounting\\Contact', $id);
}

if (!$contact) {
$existing = $xero->load('Accounting\\Contact')
->where('EmailAddress!=null AND EmailAddress.Contains("' . trim($this->owner->Email) . '")')
->execute();

if (count($existing) > 1) {
$contact = $existing->offsetGet(0);
}
}

if (!$contact) {
// create the record
$contact = new \XeroPHP\Models\Accounting\Contact();
$contact->setName($this->owner->Name);
$contact->setFirstName($this->owner->FirstName);
$contact->setLastName($this->owner->Surname);
$contact->setEmailAddress($this->owner->Email);

try {
$xero->save($contact);
} catch (Exception $e) {
if (strpos($e->getMessage(), 'Already assigned to') !== false) {
$contact->setName($this->owner->Name . ' ' . date('Y-m-d'));

try {
$xero->save($contact);
} catch (Exception $e) {
Injector::inst()->get(LoggerInterface::class)->warning($e);
}
}
}
}

return $contact;
} catch (Exception $e) {
Injector::inst()->get(LoggerInterface::class)->error($e);
}
}
}
}
```
13 changes: 13 additions & 0 deletions _config/jobs.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
SilverStripe\Core\Injector\Injector:
Symbiote\QueuedJobs\Services\QueuedJobService:
properties:
defaultJobs:
RefreshXeroToken:
type: 'FullscreenInteractive\SilverStripeXero\RefreshXeroTokenJob'
filter:
JobTitle: 'Refresh Xero token'
construct:
title: 'Refresh Xero token'
startDateFormat: 'Y-m-d H:i:s'
startTimeString: 'next week 00:01'
recreate: 1
8 changes: 1 addition & 7 deletions composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -16,15 +16,9 @@
],
"require": {
"silverstripe/framework": "^4",
"symbiote/silverstripe-queuedjobs": "^4 || ^5",
"calcinai/xero-php": "^2.3"
},
"require-dev": {
"phpunit/phpunit": "^5.7",
"squizlabs/php_codesniffer": "^3"
},
"replace": {
"silverstripe/googlesitemaps": "*"
},
"extra": {
"branch-alias": {
"dev-master": "1.x-dev"
Expand Down
24 changes: 24 additions & 0 deletions src/RefreshXeroTokenJob.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
<?php

namespace FullscreenInteractive\SilverStripeXero;

use Symbiote\QueuedJobs\Services\AbstractQueuedJob;

class RefreshXeroTokenJob extends AbstractQueuedJob
{
public function getTitle()
{
return 'Refresh Xero token';
}


public function process()
{
$xero = XeroFactory::create();
$date = $xero->renewToken();

$this->addMessage('Token refreshed until: '. date('d/m/Y H:i:s', $date));

$this->isComplete = true;
}
}
66 changes: 54 additions & 12 deletions src/XeroController.php
Original file line number Diff line number Diff line change
Expand Up @@ -3,18 +3,21 @@
namespace FullscreenInteractive\SilverStripeXero;

use SilverStripe\Control\Controller;
use SilverStripe\Control\Director;
use SilverStripe\Security\Permission;
use SilverStripe\Security\SecurityToken;
use SilverStripe\SiteConfig\SiteConfig;

class XeroController extends Controller
{
private static $scope = 'openid offline_access email profile accounting.contacts accounting.contacts.read accounting.transactions accounting.transactions.read';

private static $allowed_actions = [
'index',
'unlink'
];

public function index()
{
$url = self::join_links(Director::absoluteBaseURL() . 'xero');

$provider = XeroFactory::singleton()->getProvider();

if (!isset($_GET['code'])) {
Expand All @@ -41,26 +44,65 @@ public function index()
return $this->httpError(401);
}

$obj = SiteConfig::current_site_config();
$obj->XeroAccessToken = $token->getToken();
$config = SiteConfig::current_site_config();
$config->XeroAccessToken = $token->getToken();

$refresh = $token->getRefreshToken();

if ($refresh) {
$obj->XeroRefreshToken = $refresh;
$config->XeroRefreshToken = $refresh;
$config->XeroTokenRefreshExpires = $token->getExpires();
} else {
$config->XeroRefreshToken = null;
$config->XeroTokenRefreshExpires = null;
}

$obj->write();
$tenants = $provider->getTenants($token);

foreach ($tenants as $tenant) {
$id = $tenant->tenantId;
$config->XeroTenants = serialize($tenants);
$config->write();

if ($tenants) {
$id = null;

foreach ($tenants as $tenant) {
$id = $tenant->tenantId;

$obj->XeroTenantId = $id;
$obj->write();
if (!$config->XeroTenantId) {
$config->XeroTenantId = $id;
$config->write();

return $this->redirect('admin/settings/?doneGlobal=1');
return $this->redirect('admin/settings/?connectedXeroTo='. $id. '#Root_Xero');
}
}

if ($id) {
$config->XeroTenantId = $id;
$config->write();

return $this->redirect('admin/settings/?connectedXeroTo='. $id . '#Root_Xero');
}
}

return $this->redirect('admin/settings/#Root_Xero');
}
}


public function unlink()
{
if (!SecurityToken::inst()->checkRequest($this->request)) {
return $this->httpError(400);
}

$config = SiteConfig::current_site_config();
$config->XeroTenantId = null;
$config->XeroTenants = null;
$config->XeroTokenRefreshExpires = null;
$config->XeroRefreshToken = null;
$config->XeroAccessToken = null;
$config->write();

return $this->redirect('admin/settings/#Root_Xero');
}
}
Loading

0 comments on commit 9b7c968

Please sign in to comment.