定制 globalvisionmedia/oauth2-harvest 二次开发

按需修改功能、优化性能、对接业务系统,提供一站式技术支持

邮箱:yvsm@zunyunkeji.com | QQ:316430983 | 微信:yvsm316

globalvisionmedia/oauth2-harvest

Composer 安装命令:

composer require globalvisionmedia/oauth2-harvest

包简介

Harvest OAuth 2.0 Client Provider for The PHP League OAuth2-Client - updates Nile Suan's provider for Harvest API v2

README 文档

README

Harvest OAuth 2.0 support for the PHP League's OAuth 2.0 Client With thanks to Nile Suan for the original harvest provider. This package updates it for V2 of the Harvest API

Installation

composer require globalvisionmedia/oauth2-harvest

Obtaining a Harvest access key

  1. To get a key you will need to creare an OAuth2 application in the Harvest Developer area: (https://id.getharvest.com/developers)

  2. Click the Create new Auth2 application button to create a key

  3. Select a name for yoru application

  4. The redirect URL must be exactly the same (including the http:// or https://) as the redirectUri below and is the URL of your application. Access - select I need access to one account Product - select I want access to Harvest.

  5. Note down the Client ID and Client Secret

  6. You need to know your Account ID on Harvest. This is not shown when you create an OAuth2 app, but if you create a temporary "Personal access token" you are shown your Account ID. Note it and then you can delete the temporary personal access token.

Usage

Usage is the same as The League's OAuth client, using \GlobalVisionMedia\OAuth2\MYOBClient\Provider\MYOB as the provider, except for the following:

  1. Harvest requires you to set a User Agent in Guzzle (see Example, below)

  2. You need to supply an Account ID to the Harvest API (see above)

  3. Harvest's APIs are throttled - the documented limit is 15 calls per 100 seconds (The simplest option is to limit to 6 per second) - see example below

Instantiation

$provider = new \GlobalVisionMedia\OAuth2\HarvestClient\Provider\Harvest([
    'clientId'                => 'yourId',                // The Client ID assigned to you by Harvest
    'clientSecret'            => 'yourSecret',            // The Client Secret assigned to you by Harvest
    'redirectUri'             => 'yourRedirectUri',       // The Redirect URL you specified for your app on Harvest
    'accountId'               => 'yourAccountId,          // See point 6 above
    'userAgent'               => 'My User Agent'          // This can be any string but ideally should identify your application
]);

Tip (also applies to other providers)

When you instantiate your provider, you can also pass a second parameter containing a collaborator for your httpClient.
Doing that means you can define your own Guzzle client and do things such as:

  1. Setting Guzzle into debug mode, or
  2. Adding a rate limiter mildeware (composer require spatie/guzzle-rate-limiter-middleware)
  

use GuzzleHttp\Client;
use GuzzleHttp\HandlerStack;
use Spatie\GuzzleRateLimiterMiddleware\RateLimiterMiddleware;

define('CALLBACK_URI','https://xxx.yyy/zzzzzzzz.php');
define('HARVEST_CLIENT_ID','xxxxxxxxxxxxxxxxxxxxxxxx');
define('HARVEST_CLIENT_SECRET','xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx');
define('HARVEST_USER_AGENT','My Harvest Integration');
define('HARVEST_ACCOUNT_ID','xxxxxx');

// Add a rate limiter
$stack=HandlerStack::create();
$stack->push(RateLimiterMiddleware::perSecond(6));
$options=['debug' => $debug, 'exceptions' => false, 'handler' => $stack];
$httpClient = new Client($options);

$this->provider = \GlobalVisionMedia\OAuth2\HarvestClient\Provider\Harvest([
    'redirectUri'       => CALLBACK_URI,
    'clientId'          => HARVEST_CLIENT_ID,
    'clientSecret'      => HARVEST_CLIENT_SECRET,
    'accountId'         => HARVEST_ACCOUNT_ID,
    'userAgent'         => HARVEST_USER_AGENT
  ],
  ['httpClient'         => $httpClient]);

Sample application

<?php
require __DIR__ . '/vendor/autoload.php';

// This is a prebuilt rate limiter for guzzle - unfortunately MYOB does not seem to work as documented any you may need to add additional sleep() calls.

use GuzzleHttp\Client;
use GuzzleHttp\HandlerStack;
use Spatie\GuzzleRateLimiterMiddleware\RateLimiterMiddleware;

define('CALLBACK_URI','https://xxx.yyy/zzzzzzzz.php');
define('HARVEST_CLIENT_ID','xxxxxxxxxxxxxxxxxxxxxxxx');
define('HARVEST_CLIENT_SECRET','xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx');
define('HARVEST_USER_AGENT','My Harvest Integration');
define('HARVEST_ACCOUNT_ID','xxxxxx');

define('CACHEDIR','/tmp/');                                      // a writeable area for storing tokens


class myHarvest {

  public function __construct($debug=false) {
    $this->cache=CACHEDIR.'_API_TOKEN_CACHE_'.md5(__FILE__.get_class($this));

    // Add the rate limiter
    $stack=HandlerStack::create();
    $stack->push(RateLimiterMiddleware::perSecond(6));
    $options=['debug' => $debug, 'exceptions' => false, 'handler' => $stack];
    $httpClient = new Client($options);

    $this->provider = \GlobalVisionMedia\OAuth2\HarvestClient\Provider\Harvest([
        'redirectUri'       => CALLBACK_URI,
        'clientId'          => HARVEST_CLIENT_ID,
        'clientSecret'      => HARVEST_CLIENT_SECRET,
        'username'          => HARVEST_ACCOUNT_ID,
        'password'          => HARVEST_USER_AGENT
      ],
      ['httpClient'         => $httpClient]);

    // First check our cache to see if we have an existing token. This sppeds the application by avoiding the need to re-authenticate.
    if (file_exists($this->cache)) {
      $this->accessToken=unserialize(file_get_contents($this->cache));
      if ($this->accessToken->hasExpired()) {
        $this->accessToken=$this->provider->getAccessToken('refresh_token', ['refresh_token'=>8]);
      }
    } elseif (!isset($_GET['code'])) {
      // If we don't have an authorization code then get one
      $authUrl = $this->provider->getAuthorizationUrl();
      $_SESSION['oauth2state'] = $this->provider->getState();

      header('Location: '.$authUrl);
      exit;

      // Check given state against previously stored one to mitigate CSRF attack
    } elseif (empty($_GET['state']) ||
              (isset($_SESSION['oauth2state']) && $_GET['state'] !== $_SESSION['oauth2state'])) {
      if (isset($_SESSION['oauth2state'])) unset($_SESSION['oauth2state']);
      exit('Invalid state');

      // Try to get an access token using the authorisation code grant.
    } else try {
      $this->accessToken = $this->provider->getAccessToken('authorization_code', [ 'code' => $_GET['code'] ]);

      // Cache the token
      file_put_contents($this->cache,serialize($this->accessToken));

    } catch (\League\OAuth2\Client\Provider\Exception\IdentityProviderException $e) {
      // Failed to get the access token or user details.
      exit($e->getMessage());
    }
  }

  public function getItemsAsArray($result) {
    $keys=array_keys($result);
    //find whichever key is not in the following list - it must be our data.
    $dataKey=array_diff($keys,['page','total_pages','total_entries','next_page','previous_page','links']);
    return $result[$dataKey[0]];
  }

  public function apiCall($method, $url, $pageSize=100) {
    if (strpos($url,"https://")===false) {  // is this a nextpage link? if so leave url unchanged
      $url="https://api.harvestapp.com/v2$url?per_page=$pageSize";
    }
    $request=$this->provider->AuthenticatedRequest($method, $url, $this->accessToken);
    return $this->provider->getParsedResponse($request);
  }

  // This function retrieves paginated data as a single array
  public function fetchAll($method, $url, $pageSize=100) {
    $allResults=array();
    do {
      $result=$this->apiCall($method,$url,$pageSize);
      $allResults=array_merge($allResults,$this->getItemsAsArray($result));
      $url = $result['links']['next'];
    } while (!empty($url));
    return $allResults;
  }

}

session_start();
$myHarvest=new myHarvest();
print_r($myHarvest->fetchAll('GET', '/contacts'));

globalvisionmedia/oauth2-harvest 适用场景与选型建议

globalvisionmedia/oauth2-harvest 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 16 次下载、GitHub Stars 达 0, 最近一次更新时间为 2022 年 09 月 12 日, 在 PHP 生态内属于活跃度较高的组件。

它主要适用于以下技术方向: 「authorization」 「client」 「oauth」 「oauth2」 「Harvest」 「authorisation」 等业务场景。在实际项目中,围绕这些方向常见需要落地的问题包括:接口对接、性能调优、并发安全、与既有框架(Laravel / ThinkPHP / Yii / Webman 等)的兼容适配,以及生产环境的日志埋点与稳定性保障。

我们在过去多个企业项目中使用过 globalvisionmedia/oauth2-harvest 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。

围绕 globalvisionmedia/oauth2-harvest 我们能提供哪些服务?
定制开发 / 二次开发

基于 globalvisionmedia/oauth2-harvest 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。

BUG 修复 & 性能优化

线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。

项目外包 & 长期维护

承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。

yvsm@zunyunkeji.com QQ:316430983 微信:yvsm316 西安尊云信息科技 · 专注 PHP / Go / 分布式系统研发

统计信息

  • 总下载量: 16
  • 月度下载量: 0
  • 日度下载量: 0
  • 收藏数: 0
  • 点击次数: 20
  • 依赖项目数: 0
  • 推荐数: 0

GitHub 信息

  • Stars: 0
  • Watchers: 1
  • Forks: 0
  • 开发语言: PHP

其他信息

  • 授权协议: MIT
  • 更新时间: 2022-09-12