greenhollowtech/ght-api-client

3.0.0 2016-10-10 19:33 UTC

This package is auto-updated.

Last update: 2024-08-27 07:53:48 UTC


README

GHT API 客户端提供与 API 应用程序的连接。

安装

使用 Composer 安装,运行 composer require greenhollowtech/ght-api-client

用法

要使用客户端

use GHT\ApiClient\Entity\ApiConnector;
use GHT\ApiClient\GHTApiClient;

// Store credentials in an untracked configuration file
$apiHost = 'https://sandbox.greenhollowtech.com';
$apiUser = 'example-user';
$apiKey = 'example-key';
$apiSecret = 'example-secret';
$connector = new ApiConnector($apiHost, $apiUser, $apiKey, $apiSecret);

// Instantiate the client using the authenticating connector
$sandboxMode = true;
$client = new GHTApiClient($connector, $sandboxMode);

// Make an API request
$response = $client->post('/api/example', array(
    'example' => 'example-request-value',
));

// The response will be a JSON-encoded string, so decode it
$response = json_decode($response, true);

// Other request methods
$response = $client->get('/api/example', array(
    'example' => 'example-request-value',
));

$response = $client->put('/api/example', array(
    'example' => 'example-put-value',
));

$response = $client->delete('/api/example', array(
    'example' => 'example-delete-value',
));

// Uploading files with PHP >= 5.5.0
$exampleFile = new \CURLFile('/tmp/example.png', mime_content_type('/tmp/example.png'));
$response = $client->put('/api/example', array(
    'example' => $exampleFile,
));

// Uploading files with PHP < 5.5.0
$response = $client->put('/api/example', array(
    'example' => '@/tmp/example.png;filename=example.png',
));

// Get the HTTP response code for the last request
$responseCode = $client->getResponseCode();

OAuth2 连接

您还可以使用 OAuth2 令牌连接到 API

use GHT\ApiClient\Entity\OauthConnector;
use GHT\ApiClient\GHTApiClient;

// Get the token from the target API's OAuth2 provider
$apiHost = 'https://sandbox.greenhollowtech.com';
$token = 'tokenProvidedByTheTargetApi';
$connector = new OauthConnector($apiHost, $token);

// Instantiate the client using the OAuth2 connector
$sandboxMode = true;
$client = new GHTApiClient($connector, $sandboxMode);

如何从目标 API 获取令牌取决于您的应用程序。您可能需要扩展 OAuth2 连接器类以包含自己的用户标识和令牌过期时间,然后使用该类来存储数据。

处理大量数据结果

可以将响应数据直接流到一个文件中,以避免将整个响应加载到内存中。

在下面的示例中,$responseFile 是一个包含响应数据的临时文件的文件句柄资源。然后您可以将文件内容写入输出缓冲区以提供 CSV 下载,例如,或将文件重命名为永久位置。

$responseFile = $client->getToFile('/api/example', array(
    'example' => 'example-request-value',
));

if ($responseFile !== false) {
    // Do something with $responseFile

    fclose($responseFile);
}

设置自定义 cURL 选项

可以使用 CurlConfig 实体设置任何 cURL 选项。基本客户端内部设置的选项被忽略(CURLOPT_CUSTOMREQUESTCURLOPT_HTTPHEADERCURLOPT_POSTFIELDSCURLOPT_WRITEFUNCTION)。

use GHT\ApiClient\Entity\CurlConfig;
...
$curlConfig = new CurlConfig(array(
    'connecttimeout' => 20,
    'timeout' => 20,
));
$client->setCurlConfig($curlConfig);