recurly/recurly-client

Recurly API的PHP客户端库

4.54.0 2024-08-28 20:26 UTC

This package is auto-updated.

Last update: 2024-08-28 20:29:56 UTC


README

Contributor Covenant

此仓库存放了Recurly V3 API的官方PHP客户端。

注意:如果您在寻找V2客户端,请参阅v2分支

HTTP API的文档和示例代码可以在我们的开发者门户上找到:开发者门户

入门

参考文档可以在Github Pages上找到。

安装

该软件包在Packagist上以recurly/recurly-client的名称发布,可以作为项目composer.json文件中的依赖项添加。我们建议使用Composer来安装和维护此依赖项。

{
    "require": {
        "recurly/recurly-client": "^4"
    }
}

注意:我们尝试遵循语义版本化,并且仅在主要版本中应用破坏性更改。

创建客户端

客户端实例提供了一个位置,其中可以找到对Recurly API的所有操作(而不是在类之间分散)。可以通过构造函数初始化一个新的客户端。它只需要一个API密钥,可以在API凭证页面上获得。

// You should store your API key somewhere safe
// and not in plain text if possible
$api_key = 'myApiKey';
$client = new \Recurly\Client($api_key);

要访问欧洲的Recurly API,您需要在选项中指定欧盟区域。

// You should store your API key somewhere safe
// and not in plain text if possible
$api_key = 'myApiKey';
$client = new \Recurly\Client($api_key, ['region' => 'eu']);

日志记录

客户端构造函数可以接受程序员提供的记录器。您传递的记录器应实现PSR-3记录器接口。默认情况下,客户端创建了一个\Recurly\Logger实例,这是一个基本实现,它以\Psr\Log\LogLevel::WARNING级别将日志消息打印到php://stdout

// Create an instance of the Recurly\Logger
$logger = new \Recurly\Logger('Recurly', \Psr\Log\LogLevel::INFO);

$client = new \Recurly\Client($api_key, $logger);

安全警告:在生产环境中,不应将日志级别设置为DEBUG。这可能会导致敏感数据出现在您的日志系统中。

操作

\Recurly\Client包含了您可以在网站上执行的所有操作的列表。每个方法都有文档说明每个输入和返回类型的类型和描述。例如,要使用get_plan端点,调用Client#getPlan()方法

$plan_code = "gold";
$plan = $client->getPlan("code-$plan_code");

分页

分页是通过使用\Recurly\Pager对象完成的。通过客户端的list*操作创建分页器。分页器实现了PHP的Iterator接口,因此它可以用在foreach循环中。

注意 调用list*方法不会立即调用API。它们会立即返回分页器。只有在迭代分页器或从中请求项目时才会调用API。

$accounts = $client->listAccounts();

foreach($accounts as $account) {
    echo 'Account code: ' . $account->getCode() . PHP_EOL;
}

排序和过滤

当调用list*方法并构建分页器时,您可以通过传递可选的查询参数来帮助您对列表中的资源进行排序或筛选。查询参数在方法中进行了说明,可以在任何分页端点查询参数部分中找到。

示例:筛选和排序账户

$options = array('params' = array(
    // the following params are common amongst pageable endpoints
    'limit' => 200,   // 200 resources per page (http call)
    'order' => 'asc', // asc or desc order
    'begin_time' => '2020-01-01T01:00:00Z', // don't include accounts before 2020-01-01
    'end_time' => '2020-02-01T01:00:00Z', // don't include accounts after 2020-02-01
    // the following params are specific to the list_account endpoint
    'email' => 'admin@email.com', // only accounts with this email
    'subscriber' => true, // only accounts with a subscription in the active, canceled, or future state
    'past_due' => false // no accounts with an invoice in the past_due state
));
$accounts = $client->listAccounts($options);

foreach($accounts as $account) {
    echo 'Account code: ' . $account->getCode() . PHP_EOL;
}

计算资源数量

分页器类实现了getCount()方法,允许您计算分页器迭代时返回的资源数量。它是通过使用HEAD调用端点并解析返回的Recurly-Total-Records头信息来完成的。此方法尊重您应用于分页器的任何筛选参数,但排序参数将没有效果。

$accounts = $client->listAccounts([ 'past_due' => true ]);
// make the HTTP call to get the total count
$count = $accounts->getCount();
echo "Number of accounts past due: $count"

高效获取第一个或最后一个资源

分页器类实现了getFirst()方法,允许您从服务器获取第一个或最后一个资源。除了是一个方便的抽象之外,这个方法通过仅请求您想要的一个资源来高效实现。

$accounts = $client->listAccounts([ 'order' => 'desc', 'past_due' => true ]);
// fetch only the first account with past due invoice
$account = $accounts->getFirst();

如果您想要获取此场景中的最后一个账户,将顺序从desc改为asc

$accounts = $client->listAccounts([ 'order' => 'asc', 'past_due' => true ]);
// fetch only the last account with past due invoice
$account = $accounts->getFirst();

关于头部的说明

根据RFC 2616第4.2节,HTTP头部字段不区分大小写。

创建资源

对于创建或更新资源,将普通关联数组传递给create*update*方法之一

$plan_create = array(
    "name" => "Monthly Coffee Subscription",
    "code" => "coffee-monthly",
    "currencies" => [
        array(
            "currency" => "USD",
            "unit_amount" => 20.0
        )
    ]
);

$plan = $client->createPlan($plan_create);

echo 'Created Plan:' . PHP_EOL;
var_dump($plan);

错误处理

try {
    $account = $client->deactivateAccount($account_id);
} catch (\Recurly\Errors\Validation $e) {
    // If the request was not valid, you may want to tell your user
    // why. You can find the invalid params and reasons in err.params
    // TODO show how to get params
    var_dump($e);
} catch (\Recurly\Errors\NotFound $e) {
    // You'll receive a NotFound error if one of the identifiers in your request
    // was incorrect. In this case, it's possible the $account_id is incorrect or
    // the associated account does not exist
    var_dump($e);
} catch (\Recurly\RecurlyError $e) {
    // All errors inherit from this base class, so this should catch
    // any error that this library throws. If we don't know what to
    // do with the err, we should probably re-raise and let
    // our web framework and logger handle it
    var_dump($e);
}

HTTP元数据

有时您可能想要获取有关底层HTTP请求和响应的额外信息。我们不是直接返回这些信息并强迫程序员解包,而是将此元数据注入返回的最顶层资源中。您可以通过对任何资源调用getResponse()来访问响应。

警告:不要记录或呈现整个请求或响应,因为它们可能包含PII或敏感数据。

$account = $client->getAccount("code-douglas");
$response = $account->getResponse();
echo "Request ID:" . $response->getRequestId() . PHP_EOL;
echo "Rate limit remaining:" . $response->getRateLimitRemaining() . PHP_EOL;

请求的信息也包含在\Recurly\Response类中,可以通过在响应上调用getRequest()方法来访问。

$account = $client->getAccount("code-douglas");
$response = $account->getResponse();
$request = $response->getRequest();
echo "Request path:" . $request->getPath() . PHP_EOL;
echo "Request body as JSON:" . $request->getBodyAsJson() . PHP_EOL;
foreach($request->getHeaders() as $k => $v) {
    echo "Request header: $k => $v" . PHP_EOL;
}

这同样适用于Empty资源(当没有返回体时)

$response = $client->removeLineItem("a959576b2b10b012")->getResponse();
echo "Request ID:" . $response->getRequestId() . PHP_EOL;