tracardi/tracardi-php-sdk

该软件包最新版本(dev-master)没有可用的许可信息。

PHP 客户端用于连接 Tracardi API

dev-master 2024-04-30 19:42 UTC

This package is auto-updated.

Last update: 2024-09-30 20:34:27 UTC


README

入门

1. 创建 Guzzle 客户端

https://github.com/guzzle/guzzle

use GuzzleHttp\Client;

$baseUrl = 'https://<TRACARDI_API_URL>';

$client = new Client([
  'base_uri' => $baseUrl
]);

2. 创建 OAuth2 提供程序并获取访问令牌

https://github.com/thephpleague/oauth2-client

use Tracardi\TracardiPhpSdk\OAuth2\Provider\TracardiProvider;

$provider = new TracardiProvider(['baseUrl' => $baseUrl]);

$accessToken = $provider->getAccessToken('password', [
  'username' => '<USERNAME>',
  'password' => '<PASSWORD>'
]);

3. 将上述内容结合以获取 Tracardi 客户端

use Http\Adapter\Guzzle6\Client as ClientAdapter;
use Tracardi\TracardiPhpSdk\Http\ApiClient\ApiClient;

$psrClient = new ClientAdapter($client);
$apiClient = ApiClient::withProvider($psrClient, $provider, $accessToken);

4. 开始使用存储库

use Tracardi\TracardiPhpSdk\Tracardi;

$profile = Tracardi::withDefaultSerializer($apiClient)
  ->profiles()
  ->getProfile('<ID>');

5. 使用自己的 HTTP 客户端

并非必须使用 League OAuth 提供程序,您也可以仅使用 HTTP 客户端实例化 API 客户端。您自己负责确保此 HTTP 客户端执行认证请求。

此流程需要存在一些 PSR-7 请求工厂,例如 composer require nyholm/psr7。有关更多信息,请参阅 php-http 文档

use Http\Adapter\Guzzle6\Client as ClientAdapter;
use Tracardi\TracardiPhpSdk\Http\ApiClient\ApiClient;
use GuzzleHttp\Client;
use GuzzleHttp\HandlerStack;

// When using Guzzle you could create your own custom middleware
// that fetches the access token from e.g. the database.
$middleware = function (callable $handler): callable {
  return function (RequestInterface $request, array $options) use ($handler) {
    $request = $request->withHeader('Authorization', 'Bearer ' . fetchToken());

    return $handler($request, $options);
  };
};
$stack = HandlerStack::create();
$stack->push($middleware);

$client = new Client([
  'base_uri' => 'https://<TRACARDI_API_URL>',
  'handler' => $stack
]);

$psrClient = new ClientAdapter($client);
$apiClient = ApiClient::withClient($psrClient);