咨询/justgiving-api-sdk

一个现代的PHP SDK,用于与JustGiving API通信。

0.6.3 2021-09-22 12:58 UTC

README

Build Status Code Coverage Scrutinizer Code Quality

一个用于与JustGiving API通信的PHP SDK。基于原始SDK,由JustGiving和贡献者创建。

安装

通过composer安装

composer require konsulting/justgiving-api-sdk

快速入门

$auth = new AppAuth('abcde123');
$client = new JustGivingClient($auth);
$response = $client->account->isEmailRegistered('test@example.com');

if ($response->existenceCheck()) {
    echo 'An account has been registered with that email.';
}
$response = $client->charity->getById(2050);

if (! $response->wasSuccessful()) {
    throw new Exception(implode(', ', $response->errors));
}

$response->name;          // 'The Demo Charity1'
$response->websiteUrl;    // 'http://www.democharity.co.uk'
$response->pageShortName; // 'jgdemo'

有关更多信息,请参阅JustGiving API文档

使用

设置

客户端需要一个包含您的JustGiving API凭证的认证对象。可用的类有

  • AppAuth($appId, $secretKey = null) 用于未受保护的端点
    • 注意:如果JustGiving为您的应用ID生成了一个密钥,您必须在这里包含它(即使端点不需要授权)。如果没有,只需提供应用ID。
  • BasicAuth($appId, $username, $password) 用于受保护的端点,您有用户名和密码。
  • BearerAuth($appId, $secretKey, $token) 用于受保护的端点,您有一个Bearer令牌(来自OAuth)。

您还可以将PSR-18 HTTP客户端作为第二个参数传入。如果不提供(或设置为null),将使用默认的Guzzle客户端。

API基本URL和版本会自动设置,但可以通过传递包含键root_domainapi_version的关联数组作为第三个参数来覆盖。

例如

$auth = new BasicAuth('abced123', 'user@example.com', 'pass123');
$httpClient = new \My\Own\Psr18Client;
$options = [
    'root_domain' => 'https://api.staging.justgiving.com', 
    'api_version' => 2,
];

$client = new JustGivingClient($auth, $httpClient, $options);

查询API

SDK为每个由API文档定义的资源定义了一个单独的客户端类,并且这些类包含与API操作相对应的方法。要获取资源类,请调用我们之前构建的$client中的资源名称作为属性,例如$client->account$client->charity。然后在上面调用相关方法。

方法别名

类中的实际方法以驼峰命名,通常从原始API操作中缩短以节省空间。但是,为每个资源类定义了别名,以便可以使用API操作名称与SDK交互。

例如,这两个示例都将用来获取捐赠的状态

$client->donation->getStatus($donationId);                  // The actual method

$client->donation->RetrieveDonationStatus($donationId);     // The alias method that's the same as the API action name

模型

某些API操作(例如创建或更新资源)需要将一组数据分组到一个对象中。为此,已定义了一个模型类,用于每次需要此类操作时,例如TeamJoinTeamRequest。这些模型类都扩展了父Model类,它添加了一些有用的功能。

可以通过几种方式向模型添加数据:可以将数组传递给构造函数,传递给fill()方法的数组,或者单独设置每个属性。可以多次使用fill()方法设置不同的属性,并且如果显式作为数组项传递,则将仅覆盖现有属性。

// Data set via constructor
$team = new Team([
    'name'      => 'My Team',
    'story'     => 'This is my story',
    'target'    => 1000,
]);

// Data set via fill() method
$team = new Team;
$team->fill([
    'name'      => 'My Team',
    'story'     => 'This is my story',
    'target'    => 1000,
]);

// Data set by setting public properties individually
$team = new Team;
$team->name = 'My Team';
$team->story = 'This is my story';
$team->target = 1000;

自定义API请求

客户端允许通过request()方法自定义请求。该方法接受HTTP方法、端点URI和任何请求选项(例如头部)。您还可以覆盖客户端选项,例如API版本。这些覆盖只适用于单个请求。

例如,要向beta活动端点发起请求

$endpoint = 'campaign/' . $campaignGUID;

$client->request('GET', $endpoint, [], ['api_version' => 2]);

如果端点需要有效载荷,可以通过HTTP选项传递JSON。更完整的示例

$client->request('POST', 'new-endpoint', [
        'headers' => ['x-custom-header' => 'custom'],
        'json'    => ['title' => 'The Title'],
    ], [
        'api_version' => 2,
        'root_domain' => 'https://api.staging.justgiving.com',
    ]);

处理响应

SDK从每次请求返回JustGivingApiSdk\Support\Response的实例。这实现了PSR-7ResponseInterface,因此允许访问客户端收到的完整HTTP响应。

响应体

可以通过以下方式访问原始响应体

$response->getBody()->getContents()     // Returns the raw JSON response

然而,API返回JSON,因此这种方法可能不是处理数据的高效方式。如果将body作为响应的一个属性访问,则返回解码后的JSON体。

$response->body;                         // Returns the decoded response

从这里,响应数据由包含我们想要使用的数据的StdClass类型的数组和对象表示。

$result = $client->charity->getById(2050);
$result->body->name;            // 'The Demo Charity1'
$result->body->websiteUrl;      // 'http://www.democharity.co.uk'
$result->body->pageShortName;   // 'jgdemo'

响应类还允许直接在自身上调用body属性,即以下也是有效的

$result = $client->charity->getById(2050);
$result->name;                  // 'The Demo Charity1'
$result->websiteUrl;            // 'http://www.democharity.co.uk'
$result->pageShortName;         // 'jgdemo'

错误

API提供了两种错误消息格式:第一种是与整个请求相关的一般错误消息(例如,该电子邮件地址已被使用),第二种是与请求或数据特定部分的问题相关的错误消息列表,带有标识符和描述(例如,ID:FirstNameNotSpecified,描述:FirstName字段是必需的。)。

在API文档中,前者被称为errorMessage属性,后者指的是包含在Error对象中的错误(具有Error.idError.desc属性)。

可以通过响应对象的errors属性访问错误,该属性以统一数组格式呈现任何错误(格式为$identifier => $description)。如果存在一般错误,则将其标识符设置为General,并像任何其他错误一样添加到数组中。响应中给出的原因短语(可通过getReasonPhrase()方法访问)添加到错误数组中,并给定标识符ReasonPhrase

例如

$response = $this->client->account->create(new CreateAccountRequest([
    'email'     => "john@example.com",
    'firstName' => "John",
    'lastName'  => "Smith",
    'password'  => 'password',
    'title'     => "Mr",
    'address' => new Address([
       'line1'             => "testLine1",
       'line2'             => "testLine2",
       'country'           => "United Kingdom",
       'countyOrState'     => "testCountyOrState",
       'townOrCity'        => "testTownOrCity",
       'postcodeOrZipcode' => "M130EJ",
    ]),

    'acceptTermsAndConditions' => false
]));

$errors = $response->errors;
// $errors is:
// [
//    'ReasonPhrase'                        => 'Validation errors occured.',
//    'FirstNameNotSpecified'               => 'The FirstName field is required.',
//    'AcceptTermsAndConditionsMustBeTrue'  => 'You must agree to the terms and conditions'
// ]

现在,假设我们正确创建了该账户,然后尝试使用相同的电子邮件创建一个新账户

$response = $this->client->account->create(new CreateAccountRequest([
    'email'     => "john@example.com",
    'firstName' => "John",
    'lastName'  => "Smith",
    'password'  => 'password',
    'title'     => "Mr",
    'address' => new Address([
       'line1'             => "testLine1",
       'line2'             => "testLine2",
       'country'           => "United Kingdom",
       'countyOrState'     => "testCountyOrState",
       'townOrCity'        => "testTownOrCity",
       'postcodeOrZipcode' => "M130EJ",
    ]),

    'acceptTermsAndConditions' => true
]));

$errors = $response->errors;
// $errors is:
// [
//    'ReasonPhrase'    => 'Bad request',
//    'General'         => 'That email address is already in use'
// ]

响应辅助方法

响应有几个辅助方法可以使API调用和验证更容易

  • $response->wasSuccessful() - 如果响应具有2xx状态码,则返回true。
  • $response->hasErrorMessages() - 如果响应有任何错误消息,则返回true。注意:一些API操作在失败时不会返回任何错误消息。此标志应用于确定是否有任何有用的错误信息可以显示,而不是检查操作是否成功(请使用wasSuccessful()代替)。
  • $response->existenceCheck() - 如果响应状态码为200,则返回true,如果状态码为404,则返回false,否则抛出异常。对于检查资源存在性的API调用非常有用。