使用 OAuth 2.0 规范的 Laravel 对 Xero 的集成

v1.1.2 2020-03-26 20:03 UTC

This package is auto-updated.

Last update: 2024-09-15 01:53:34 UTC


README

Latest Version on Packagist Total Downloads

此包使用 OAuth 2.0 规范与 Laravel 集成新的推荐包 xeroapi/xero-php-oauth2

安装

您可以使用以下命令通过 composer 安装此包:

composer require webfox/laravel-xero-oauth2

此包将自动注册自身。

您可以使用以下命令发布配置文件:

php artisan vendor:publish --provider="Webfox\Xero\XeroServiceProvider" --tag="config"

您需要在配置文件中设置应用程序所需的作用域。

您应该使用以下密钥在 .env 文件中添加您的 Xero 密钥:

XERO_CLIENT_ID=
XERO_CLIENT_SECRET=

在 Xero 中设置应用程序时,请确保您的重定向 URL 是 https://{your-domain}/xero/auth/callback

使用此包

此包在服务容器中注册了两个绑定,您可能会感兴趣

  • \XeroAPI\XeroPHP\Api\AccountingApi::class 这是 Xero 的主要 API - 有关用法,请参阅 xeroapi/xero-php-oauth2 文档。当您首次解析此依赖项时,如果存储的凭据已过期,它将自动刷新令牌。
  • Webfox\Xero\OauthCredentialManager 这是凭证管理器 - 账户 API 需要我们传递每个请求的租户 ID,这个类就是用来访问它的。这里也是我们获取关于认证用户信息的地方。以下是一个示例。

app\Http\Controllers\XeroController.php

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Webfox\Xero\OauthCredentialManager;

class XeroController extends Controller
{

    public function index(Request $request, OauthCredentialManager $xeroCredentials)
    {
        try {
            // Check if we've got any stored credentials
            if ($xeroCredentials->exists()) {
                /* 
                 * We have stored credentials so we can resolve the AccountingApi, 
                 * If we were sure we already had some stored credentials then we could just resolve this through the controller
                 * But since we use this route for the initial authentication we cannot be sure!
                 */
                $xero             = resolve(\XeroAPI\XeroPHP\Api\AccountingApi::class);
                $organisationName = $xero->getOrganisations($xeroCredentials->getTenantId())->getOrganisations()[0]->getName();
                $user             = $xeroCredentials->getUser();
                $username         = "{$user['given_name']} {$user['family_name']} ({$user['username']})";
            }
        } catch (\throwable $e) {
            // This can happen if the credentials have been revoked or there is an error with the organisation (e.g. it's expired)
            $error = $e->getMessage();
        }

        return view('xero', [
            'connected'        => $xeroCredentials->exists(),
            'error'            => $error ?? null,
            'organisationName' => $organisationName ?? null,
            'username'         => $username ?? null
        ]);
    }

}

resources\views\xero.blade.php

@extends('_layouts.main')

@section('content')        
@if($error)
    <h1>Your connection to Xero failed</h1>
    <p>{{ $error }}</p>
    <a href="{{ route('xero.auth.authorize') }}" class="btn btn-primary btn-large mt-4">
        Reconnect to Xero
    </a>
@elseif($connected)
    <h1>You are connected to Xero</h1>
    <p>{{ $organisationName }} via {{ $username }}</p>
    <a href="{{ route('xero.auth.authorize') }}" class="btn btn-primary btn-large mt-4">
        Reconnect to Xero
    </a>
@else
    <h1>You are not connected to Xero</h1>
    <a href="{{ route('xero.auth.authorize') }}" class="btn btn-primary btn-large mt-4">
        Connect to Xero
    </a>
@endif
@endsection

routes/web.php

/* 
 * We name this route xero.auth.success as by default the config looks for a route with this name to redirect back to
 * after authentication has succeeded. The name of this route can be changed in the config file.
 */
Route::get('/manage/xero', [\App\Http\Controllers\XeroController::class, 'index'])->name('xero.auth.success');

使用 Webhooks

在 Xero 开发者门户中的应用程序中创建一个 webhook 以获取您的 webhook 密钥。

然后您可以将此添加到 .env 文件中作为

XERO_WEBHOOK_KEY=...

然后您可以为处理 webhook 并注入 \Webfox\Xero\Webhook 设置一个控制器,例如。

<?php

namespace App\Http\Controllers;

use Webfox\Xero\Webhook;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Webfox\Xero\WebhookEvent;
use XeroApi\XeroPHP\Models\Accounting\Contact;
use XeroApi\XeroPHP\Models\Accounting\Invoice;

class XeroWebhookController extends Controller
{
    public function __invoke(Request $request, Webhook $webhook)
    {

        // The following lines are required for Xero's 'itent to receive' validation
        if (!$webhook->validate($request->header('x-xero-signature'))) {
            // We can't use abort here, since Xero expects no response body
            return response('', Response::HTTP_UNAUTHORIZED);
        }

        // A single webhook trigger can contain multiple events, so we must loop over them
        foreach ($webhook->getEvents() as $event) {
            if ($event->getEventType() === 'CREATE' && $event->getEventCategory() === 'INVOICE') {
                $this->invoiceCreated($request, $event->getResource());
            } elseif ($event->getEventType() === 'CREATE' && $event->getEventCategory() === 'CONTACT') {
                $this->contactCreated($request, $event->getResource());
            } elseif ($event->getEventType() === 'UPDATE' && $event->getEventCategory() === 'INVOICE') {
                $this->invoiceUpdated($request, $event->getResource());
            } elseif ($event->getEventType() === 'UPDATE' && $event->getEventCategory() === 'CONTACT') {
                $this->contactUpdated($request, $event->getResource());
            }
        }

        return response('', Response::HTTP_OK);
    }

    protected function invoiceCreated(Request $request, Invoice $invoice)
    {
    }

    protected function contactCreated(Request $request, Contact $contact)
    {
    }

    protected function invoiceUpdated(Request $request, Invoice $invoice)
    {
    }

    protected function contactUpdated(Request $request, Contact $contact)
    {
    }

}

许可

MIT 许可证 (MIT)。有关更多信息,请参阅 许可文件