sarmadmakhdoom / payments-sdk
QuickBooks Online Payments API的官方PHP SDK
Requires
- guzzlehttp/guzzle: ^7
- psr/log: ^1.0 || ^2.0 || ^3.0
Requires (Dev)
- phpunit/phpunit: ^8
This package is auto-updated.
Last update: 2024-09-15 22:13:26 UTC
README
QuickBooks Payments PHP SDK
此SDK旨在通过提供一套方法来简化开发者使用QuickBooks Payments API,使其更容易操作。它支持以下操作
- 标准的OAuth 2.0和OpenID Connect协议
- 日志记录和错误处理的拦截器
- 标准的支付API端点以及请求/响应处理
如果您之前没有使用过QuickBooks Payments API,请访问我们的文档: https://developer.intuit.com/app/developer/qbpayments/docs/get-started
要求
- PHP 7.2.0及更高版本。
- QuickBooks Online Payments API应用程序。
Composer
您可以通过以下命令使用Composer安装此包:Composer
composer require quickbooks/payments-sdk
如果您在Composer安装过程中遇到问题,请先尝试更新Composer
composer update
并查看指定版本是否解决了问题,例如
composer require quickbooks/payments-sdk 1.0.5
要使用此包,请使用Composer的自动加载
require "vendor/autoload.php";
手动安装
如果您不想使用Composer,可以下载最新版本。然后,为了使用此包,请包含config.php文件。
require_once('/path/to/config.php');
依赖项
以下扩展是正常工作的必要条件
如果您指定了Guzzle客户端,则需要Guzzle。
如果您使用Composer,这些依赖项应该会自动处理。如果您手动安装,请确保这些扩展可用。
入门
要开始使用Payment SDK,第一步是创建PaymentClient。必需的最小属性是access_token和environment。access_token是访问API的OAuth 2.0令牌,environment定义API端点的基础URL。这可以是sandbox或production。如果您不提供这两个属性,仍然会创建PaymentClient,但它将无法进行任何支付API调用。
$client = new PaymentClient([ 'access_token' => "your access token", 'environment' => "sandbox" // or 'environment' => "production" ]);
创建Payment Client后,您就可以开始向支付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()进行检查。请参阅我们的响应接口以诊断失败请求的支持操作列表。
OAuth支持
开发者可以使用此库来处理OAuth 2.0协议。它支持
- 生成授权URL
generateAuthCodeURL(string $scope, string $userDefinedState = "state") : string - 获取OAuth 2.0 Bearer令牌
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支持所有六个支付端点: BankAccounts、Cards、Charges、EChecks、Tokens、Transactions。这些可以在我们的QuickBooks Payments API Explorer中找到。
为了构建每个API端点的正文,开发者需要首先以数组格式构建请求正文,然后使用Operations的buildFrom方法将数组转换为对象。
例如,要将表示卡的数组转换为$card对象,使用
CardOperations::buildFrom($cardarray);
所有支持的operations都可以在这里找到:Operations
对象创建后,可以使用它发送请求。所有端点的函数名称都源自于API参考。例如,要创建一张卡,应该使用
$client->createCard($card);
如果您想要为请求提供自定义的Request-Id,使用
$client->createCard($card, $requestId);
否则,将提供由系统生成的随机请求ID。
要查看可用函数的列表,请参阅此处:API端点操作
拦截器
拦截器用于拦截请求和响应。它可以用来记录请求或响应。这可以用作解决连接超时或令牌过期等问题时的重试机制。
此SDK提供的默认拦截器有
- StackTraceLoggerInterceptor:类似于log4j,它将堆栈跟踪记录到日志文件中。StackTraceLoggerIntercepto会将所有内容记录到一个错误日志中。
- 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的任何错误,或者希望请求一个新功能,请在我们提供的支持票务系统中创建支持工单,或者向我们发送pull request。贡献总是受欢迎的!
