quickbooks/payments-sdk

QuickBooks Online Payments API 的官方 PHP SDK

v1.0.8 2020-09-23 00:24 UTC

README

Rate your SDKYesNo

QuickBooks Payments PHP SDK

Build status Latest Stable Version

此 SDK 设计用于简化开发者使用 QuickBooks Payments API,提供了一系列易于使用的方法。它支持以下操作

  • 标准 OAuth 2.0 和 OpenID Connect 协议
  • 用于日志记录和错误处理的拦截器
  • 标准 Payments API 端点以及请求/响应处理

如果您之前未使用过 QuickBooks Payments API,请访问我们的文档: https://developer.intuit.com/app/developer/qbpayments/docs/get-started

要求

  1. PHP 7.2.0 及以上版本。
  2. QuickBooks Online Payments API 应用。

Composer

您可以通过 Composer 安装此包。运行以下命令

composer require quickbooks/payments-sdk

如果在 composer 安装过程中遇到问题,请先尝试更新 composer

composer update

并查看指定版本是否可以解决问题,例如

composer require quickbooks/payments-sdk 1.0.5

要使用此包,使用 Composer 的 autoload

require "vendor/autoload.php";

手动安装

如果您不想使用 Composer,可以下载 最新版本。然后,要使用此包,请包含 config.php 文件。

require_once('/path/to/config.php');

依赖

以下扩展对于正常工作是必需的

  • curl,尽管如果您愿意,也可以使用自己的非 cURL 客户端
  • json

如果您指定了 Guzzle 客户端,那么也需要 Guzzle。

如果您使用 Composer,这些依赖项应该会自动处理。如果您手动安装,请确保这些扩展可用。

入门指南

要开始使用 Payments SDK,第一步是创建 PaymentClient。所需的最小属性是 access_tokenenvironmentaccess_token 是用于访问 API 的 OAuth 2.0 令牌,environment 定义了 API 端点的基本 URL。这可以是 sandboxproduction。如果您不提供这两个属性,PaymentClient 仍然会被创建,但它将无法进行任何 Payments API 调用。

$client = new PaymentClient([
 'access_token' => "your access token",
 'environment' => "sandbox" //  or 'environment' => "production"
]);

一旦创建了 Payment Client,您就可以开始对 Payments API 端点进行 API 调用了。简单的使用方式如下

<?php
require "vendor/autoload.php";

use QuickBooksOnline\Payments\PaymentClient;
use QuickBooksOnline\Payments\Operations\ChargeOperations;


$client = new PaymentClient([
  'access_token' => "your access token",
  'environment' => "sandbox" //  or 'environment' => "production"
]);

$array = [
  "amount" => "10.55",
  "currency" => "USD",
  "card" => [
      "name" => "emulate=0",
      "number" => "4111111111111111",
      "address" => [
        "streetAddress" => "1130 Kifer Rd",
        "city" => "Sunnyvale",
        "region" => "CA",
        "country" => "US",
        "postalCode" => "94086"
      ],
      "expMonth" => "02",
      "expYear" => "2020",
      "cvc" => "123"
  ],
  "context" => [
    "mobile" => "false",
    "isEcommerce" => "true"
  ]
];
$charge = ChargeOperations::buildFrom($array);
$response = $client->charge($charge);

if($response->failed()){
    $code = $response->getStatusCode();
    $errorMessage = $response->getBody();
    echo "code is $code \n";
    echo "body is $errorMessage \n";
}else{
    $responseCharge = $response->getBody();
    //Get the Id of the charge request
    $id = $responseCharge->id;
    //Get the Status of the charge request
    $status = $responseCharge->status;
    echo "Id is " . $id . "\n";
    echo "status is " . $status . "\n";
}

如果请求成功执行,则 getBody() 函数将返回转换后的对象。上面的示例将从 $response->getBody() 返回以下 $responseCharge 对象

class QuickBooksOnline\Payments\Modules\Charge#11 (19) {
  public $status =>
  string(8) "CAPTURED"
  public $amount =>
  string(5) "10.55"
  public $currency =>
  string(3) "USD"
  public $token =>
  NULL
  public $card =>
  class QuickBooksOnline\Payments\Modules\Card#12 (18) {
    public $updated =>
    NULL
    public $name =>
    string(9) "emulate=0"
    public $number =>
    string(16) "xxxxxxxxxxxx1111"
    public $address =>
    class QuickBooksOnline\Payments\Modules\Address#13 (5) {
      public $streetAddress =>
      string(13) "1130 Kifer Rd"
      public $city =>
      string(9) "Sunnyvale"
      public $region =>
      string(2) "CA"
      public $country =>
      string(2) "US"
      public $postalCode =>
      string(5) "94086"
    }
    public $commercialCardCode =>
    NULL
    ...

每个转换后的对象都将具有我们在 API 参考中声明的相同属性名称: https://developer.intuit.com/app/developer/qbpayments/docs/api/resources/all-entities/charges 页面,

调用可能因过期令牌、服务器中断或无效请求体等原因而失败。您可以使用 $response->failed() 来检查。有关失败的请求的诊断,请参阅我们的 Response 接口 中支持的操作列表。

OAuth 支持

开发者可以使用这个库来处理 OAuth 2.0 协议。它支持

  • 生成授权URL
    generateAuthCodeURL(string $scope, string $userDefinedState = "state") : string
  • 获取OAuth 2.0令牌
    createRequestToExchange(string $code) : RequestInterface
  • 获取用户信息
    createRequestForUserInfo(string $accessToken) : RequestInterface
  • 刷新OAuth 2.0令牌
    createRequestToRefresh(string $refreshToken) : RequestInterface
  • 撤销OAuth 2.0令牌
    createRequestToRevoke(string $token)
  • 从OAuth 1.0迁移令牌到OAuth 2.0 createRequestToMigrateToken(string $consumerKey, string $consumerSecret, string $oauth1AccessToken, string $oauth1TokenSecret, string $scopes) : RequestInterface

为了使用OAuth 2.0,开发者需要创建两个对象

  • OAuth2Authenticator : 用于创建与OAuth 2.0相关的请求
  • PaymentClient: 用于发送与OAuth 2.0相关的请求

支付SDK不提供解析OAuth 2.0响应的支持。由于OAuth 2.0请求的响应始终是JSON格式,可以使用简单的 json_decode($response->getBody(), true) 进行解析。

示例

<?php
require "vendor/autoload.php";

use QuickBooksOnline\Payments\OAuth\OAuth2Authenticator;
use QuickBooksOnline\Payments\PaymentClient;

$client = new PaymentClient();
$oauth2Helper = OAuth2Authenticator::create([
  'client_id' => 'Your Client ID',
  'client_secret' => 'Your Client Secret',
  'redirect_uri' => 'The redirect URI under the app's Keys tab',
  'environment' => 'development' // or 'environment' => 'production' 
]);

//The scope for the token. 
$scope = "com.intuit.quickbooks.accounting openid profile email phone address";

$authorizationCodeURL = $oauth2Helper->generateAuthCodeURL($scope);
//Sample URL: https://appcenter.intuit.com/connect/oauth2?client_id=L0vmMZIfwUBfv9PPM96dzMTYATnLs6TSAe5SyVkt1Z4MAsvlCU&scope=com.intuit.quickbooks.accounting%20openid%20profile%20email%20phone%20address&redirect_uri=https%3A%2F%2Fdeveloper.intuit.com%2Fv2%2FOAuth2Playground%2FRedirectUrl&response_type=code&state=JBAJE

//Redirect User to the $authorizationCodeURL, and a code will be sent to your redirect_uri as query paramter
$code = $_GET['code'];
$request = $oauth2Helper->createRequestToExchange($code);
$response = $client->send($request);
if($response->failed()){
  $code = $response->getStatusCode();
  $errorMessage = $response->getBody();
  echo "code is $code \n";
  echo "body is $errorMessage \n";
}else{
  //Get the keys
  $array = json_decode($response->getBody(), true);
  $refreshToken = $array["refresh_token"];
  //AB11570127472xkApQcZmbTMGfzzEOgMWl2Br5h8IEgxRULUbO
}

操作

PHP支付SDK支持所有六个支付端点: BankAccountsCardsChargesEChecksTokensTransactions。这些可以在我们的 QuickBooks Payments API资源浏览器 中找到。

为了构造每个API端点的正文,开发者需要首先以数组形式构造请求正文,然后使用OperationsbuildFrom方法将数组转换为对象。

例如,要将表示卡片的数组转换为$card对象,请使用

CardOperations::buildFrom($cardarray);

所有支持的operations都可以在这里找到:Operations

对象创建后,可以使用它发送请求。所有端点的函数名都来自API参考。例如,要创建卡片,应使用

$client->createCard($card);

如果您想为请求提供自定义的Request-Id,请使用

$client->createCard($card, $requestId);

否则,将提供一个系统生成的随机请求ID。

要查看可用的函数列表,请参阅:API端点操作

拦截器

拦截器用于拦截请求和响应。它可以用来记录请求或响应。这可以用作连接超时或令牌过期等问题的问题的重试机制。

此SDK中提供的默认拦截器有

  • StackTraceLoggerInterceptor:类似于log4j,它将堆栈跟踪记录到日志文件中。StackTraceLoggerInterceptor会将所有内容记录到一个错误日志中。
  • RequestResponseLoggerInterceptor:它将记录每次发送和接收的完整请求和响应。它将隐藏OAuth 2.0令牌。RequestResponseLoggerInterceptor将每个请求记录到一个文件中,每个响应也记录到一个文件中。
  • ExceptionOnErrorInterceptor:如果请求失败,它将抛出异常。

根据需要,您可以通过继承InterceptorInterface来定义自己的拦截器以拦截请求和响应。

  • 要更改发送给支付API的请求,定义您的before(RequestInterface &$request, PaymentClient $client)方法。
  • 要更改接收到的响应,定义您的after(ResponseInterface &$response, PaymentClient $client)方法。
  • 要拦截未经修改的请求和响应,定义您的intercept(RequestInterface $request, ResponseInterface $response, PaymentClient $client)方法。

要向客户端添加拦截器,请使用

$client->addInterceptor("interceptorName", new InterceptorImplementation());

要按名称删除拦截器,请使用

$client->removeInterceptor($name);

示例:为了启用SDK每个实际请求和响应的文件存储

$client->addInterceptor("requestresponselogger", new RequestResponseLoggerInterceptor("/your/directory/to/store/files", 'America/Los_Angeles'));

为了启用SDK每个交易的日志记录

$client->addInterceptor("tracelogger", new StackTraceLoggerInterceptor("/your/file/to/log/the/transaction", 'America/Los_Angeles'));

错误处理

默认情况下,每个$response对象都有一个failed()方法,用于判断请求是否成功执行。成功的请求是指状态码为200/201。任何其他状态码都会导致$response->failed()方法返回true。如果请求失败,您可以使用我们的支持的诊断功能来获取更多信息。

问题

如果您发现SDK的任何错误,或者想要请求一个功能,请在https://help.developer.intuit.com/s/创建一个支持工单,或者向我们发送一个pull request。贡献总是受欢迎的!