capusta/php-sdk

Capusta PHP SDK

v1.14.0 2022-09-15 13:56 UTC

README

最新版本是 v1.14.0

文档: https://dev.capusta.space/

需求

PHP 7.2 及以上。

依赖

绑定需要以下扩展才能正常运行

可选

Composer

首先,您需要将 Composer 安装到您的系统上。(https://getcomposer.org/doc/00-intro.md#installation-linux-unix-macos

Composer 安装到您的系统后,您需要运行以下命令

composer require capusta/php-sdk:@dev

要使用绑定,请使用 Composer 的 自动加载

require_once('vendor/autoload.php');

如果您使用 Composer,这些依赖项应该会自动处理。

入门

我们建议使用 GuzzleHttp 客户端

初始化客户端

$guzzleClient = new GuzzleHttp\Client();
$transport = new Capusta\SDK\Transport\GuzzleApiTransport($guzzleClient);
$client = new Capusta\SDK\Client($transport);
$client->   setAuth('merchantEmail', 'token');

所有请求都按类似的步骤处理

  1. 创建 Capusta\SDK\Model\Request\AbstractRequest 的请求实例
  2. 请求序列化
  3. 向服务器发送请求
  4. 您将获得一个 Capusta\SDK\Model\Response\AbstractResponse 的响应对象实例,如果请求失败则抛出异常

所有请求都是通过适当的对象创建的,或者可以根据数组、整数和字符串创建

创建支付

使用对象创建请求

// Create a request object
$createPaymentRequest = new Capusta\SDK\Model\Request\Payment\CreatePaymentRequest();

// Set up $createPaymentRequest with required params
try {
    /** @var Capusta\SDK\Model\Response\Payment\CreatePaymentResponse $createPaymentResponse */
    $createPaymentResponse = $client->createPayment($createPaymentRequest);
} catch (\Exception $e) {
    // ...
}

或者您可以使用数组创建请求

$requestArray = [
    'id' => "YOUR_TRANSACTION_ID", // your ID of transaction, optional.
    'description' => "description", //optoinal
    'amount' => [
                    'amount' => 1000, //1000 = 10 RUB, *** OPTIONAL *** (if you want to get bill with any amount within limits)
                    'currency' => 'RUB' //name of currency
                ], //array of 'amount' in minor value and 'currency'.
    'projectCode' => "code", //required, code can be taken from my.capusta.space
    'custom' => [/*...*/], // optional array key=>value, with length < 255. 
    'expire' => new DateTime('now + 1 hour'), // optional expiration datetime object (for example payment can be paid only in 1 hour)
    'sender' => [
                    'name' => 'Vasya',
                    'phone' => '+79991234567',
                    'email' => 'vasya@vasya.ru',
                    'comment' => 'this is my order'
                ], //optional array of 'name', 'phone', 'email', 'comment'.
    'successUrl' => "https://my-site.com/payment/success", // optional redirection url after success payment.
    'failUrl' => "https://my-site.com/payment/fail" // optional redirection url after failed payment                    
];

try {
    /** @var Capusta\SDK\Model\Response\Payment\CreatePaymentResponse $createPaymentResponse */
    $createPaymentResponse = $client->createPayment($requestArray);
} catch (\Exception $e) {
    // ...
}

if ($createPaymentResponse->getStatus()=='CREATED'){
// redirect user to $createPaymentResponse->getPayUrl();
}

如果 $createPaymentResponse->getStatus() == 'CREATED',则需要将用户重定向到 URL:$createPaymentResponse->getPayUrl()

创建账单

使用对象创建请求

// Create a request object
$createBillRequest = new Capusta\SDK\Model\Request\Bill\CreateBillRequest();

// Set up $createBillRequest with required params

try {
    /** @var Capusta\SDK\Model\Response\Bill\CreateBillResponse $createBillResponse */
    $createBillResponse = $client->createBill($createBillRequest);
} catch (\Exception $e) {   
    // ...
}

或者您可以使用数组创建请求

$requestArray = [
    'id' => "YOUR_BILL_ID", //optional
    'amount' => [
                    'amount' => 1000, //1000 = 10 RUB, *** OPTIONAL *** (if you want to get payment with any amount within limits)
                    'currency' => 'RUB' //name of currency
    ], //array of 'amount' in minor value and 'currency'
    'subscription' => [
        'per' => 'WEEKLY', // period, optional. can be  'DAILY', 'MONTHLY', 'WEEKLY, 'SELECTIVELY'.
        // if per is absent it creates simple the recurring bill without any period. 
        'oneTimePayment' => false, //boolean. if false the bill can be paid several times.
        'trialDays' => 0 // optional int. The free days of trial subscription before payment.
    ], //optional settings to create recurring payment.
    'description' => "description", //optional description of bill
    'projectCode' => "code", //your project code
    'custom' => [/*...*/], // optional array of key=>value structure and length < 255.
    'expire' => new DateTime('now + 1 day'), // optional expiration datetime (for example bill can be paid within 1 day)
    'successUrl' => "https://my-site.com/payment/success", // optional redirection url after success payment.
    'failUrl' => "https://my-site.com/payment/fail" // optional redirection url after failed payment                    
];
// ^^^^^^^^ the same fields like in payment method.
 
try {
    /** @var Capusta\SDK\Model\Response\Bill\CreateBillResponse $createBillResponse */
    $createBillResponse = $client->createBill($requestArray);
} catch (\Exception $e) {
    // ...
}

if ($createBillResponse->getStatus()=='CREATED'){
    // redirect user to $createBillResponse->getPayUrl();
}

如果 $createBillResponse->getStatus() == 'CREATED',则需要将用户重定向到 URL:$createBillResponse->getPayUrl()

创建付款

使用对象创建请求

// Create a request object
$createPayoutRequest = new Capusta\SDK\Model\Request\Payout\CreatePayoutRequest();
    // Set up $createPayoutRequest with required params

try {
    /** @var Capusta\SDK\Model\Response\Payout\CreatePayoutResponse $createPayoutResponse */
    $createPayoutResponse = $client->createPayout($createPayoutRequest);
} catch (\Exception $e) {
    // ...
}

或者您可以使用数组创建请求

$requestArray = [
    'id' => 'transaction_id', // optional
    'amount' => [
                    'amount' => 1000, //1000 = 10 RUB
                    'currency' => 'RUB' //name of currency
    ], // array of 'currency' and 'amount' in minor value
    'projectCode' => 'ProjectCode', // or 'projectId' => projectId
    'pan' => 'payout card number', // i.e. 4111111111111111
    'description' => 'my payout description',  //optional
];

try {
    /** @var Capusta\SDK\Model\Response\Payout\CreatePayoutResponse $createPayoutResponse */
    $createPayoutResponse = $client->createPayout($requestArray);
} catch (\Exception $e) {
    // ...
}

获取支付状态

使用对象创建请求

// Create a request object
$getStatusRequest = new Capusta\SDK\Model\Request\Status\GetStatusRequest();

// Set up $getStatusRequest with required params

try {
    /** @var Capusta\SDK\Model\Response\Status\getStatusResponse $getStatusResponse */
    $getStatusResponse = $client->getStatus($getStatusRequest);
} catch (\Exception $e) {
// ...
}

或者您可以使用数组创建请求

$requestArray = [
    'transaction_id' => 'YOUR_TRANSACTION_ID', // here is the id of the transaction
    'withFailed' => TRUE, // Optional, Boolean. If TRUE, you can receive details of failed transaction
];

try {
    /** @var Capusta\SDK\Model\Response\Status\getStatusResponse $getStatusResponse */
    $getStatusResponse = $client->getStatus($requestArray);
} catch (\Exception $e) {
    // ...
}

获取 BILL 状态(状态 v2)

('transactions' 属性中包含成功支付的数组)

使用对象创建请求
// Create a request object
$getBillStatusRequest = new Capusta\SDK\Model\Request\Status\GetStatusRequest();

// Set up $getStatusRequest with required params

try {
    /** @var Capusta\SDK\Model\Response\Status\getStatusResponse $getStatusResponse */
    $getStatusResponse = $client->getBillStatus($getBillStatusRequest);
} catch (\Exception $e) {
    // ...
}

或者您可以使用数组创建请求

$requestArray = [
    'transaction_id' => 'YOUR_TRANSACTION_ID', // here is the id of the transaction 
    'withFailed' => TRUE, // OPTIONAL BOOLEAN. If you want to get all transactions even failed with details of failure - you need to set it to TRUE, otherwise FALSE.
];   
try {
    /** @var Capusta\SDK\Model\Response\Status\getStatusResponse $getStatusResponse */
    $getStatusResponse = $client->getBillStatus($requestArray);
} catch (\Exception $e) {
    // ...
}

如果您想获取账单或支付的数组形式的成功交易,需要调用方法 $getStatusResponse->getTransactions()。

获取支付登记册

成功支付的数组。

  • 注意:日期范围之差不要超过 24 小时。
$registry = new Capusta\SDK\Model\Request\Registry\GetRegistryRequest();
$registry->setFrom(new \DateTime('1 day ago'))
    ->setTo(new \DateTime())
    ->setProjectCode('projectCode');

$response = $client->getRegistry($registry);
    

或者您可以使用数组请求获取支付登记册

$requestArray = [
    'projectCode' => 'projectCode', // here is the id of the transaction
    'from' => '2020-04-30T08:19:47.000-04:00', // start date
    'to' => '2020-05-01T08:19:47.000-04:00',
    'withFailed' => TRUE, // If you want to get all (even failed) transactions.
];
    
try {
    /** @var $getRegistryResponse array */
    $getRegistryResponse = $client->getRegistry($requestArray);
} catch (\Exception $e) {
    // ...
}

创建项目

(此方法默认禁用,您需要联系支持以启用此功能)

使用对象创建请求

// Create a request object
$createProjectRequest = new Capusta\SDK\Model\Request\Project\CreateProjectRequest();

// Set up $createProjectRequest with required params

try {
    /** @var Capusta\SDK\Model\Response\Project\CreateProjectResponse $createProjectResponse */
    $createProjectResponse = $client->createProject($createProjectRequest);
} catch (\Exception $e) {   
    // ...
}

或者您可以使用数组创建请求

$requestArray = [
    'email' => 'email@email.org',
    'projectLink' => "https://project.link", // URL of the project site
    'callbackUrl' => "https://project.link/callback", // callback address
    'failUrl' => "https://project.link/fail", //failed transactions redirect URL
    'successUrl' => "https://project.link/success", //success transactions redirect URL
];

try {
    /** @var Capusta\SDK\Model\Response\Project\CreateProjectResponse $createProjectResponse */
    $createProjectResponse = $client->createProject($requestArray);
} catch (\Exception $e) {
    // ...
}

返回的对象 $createProjectResponse 包含 'status' 属性中的属性。如果 'status' 是 "NEW",则项目已成功创建。

异常

  • Capusta\SDK\Exception\TransportException - 在 API 传输错误的情况下抛出。例如,当未提供授权数据时。
  • Capusta\SDK\Exception\JsonParseException - 服务器响应不包含有效的 JSON。
  • Capusta\SDK\Exception\ServerResponse\ResponseException - 4xx 和 5xx 服务器错误。
  • Capusta\SDK\Exception\Response\ResponseParseException - 创建响应错误。
  • Capusta\SDK\Exception\Request\RequestParseException - 创建请求错误。

处理来自服务器的通知

此代码负责处理支付结果。您需要创建处理器,使其在您的应用程序的URL上可用,并在项目设置中将URL指定为 my.capusta.space。此处理器将在用户在capusta.space上的表单中进行支付后调用。

$notification = new \Capusta\SDK\Notification();
$notification->setAuth('merchantEmail', 'token');
$responseNotification = $notification->process();

$responseNotification 包含通知参数的对象。例如,您可以这样获取主要参数

$callbackPaymentData  = [
    'amount' => $responseNotification->getAmount(),
    'currency' => $responseNotification->getAmount()->getCurrency(),
    'commission' => $responseNotification->getAmount()->getCommission(),
    'status' => $responseNotification->getStatus()
];

例如,您可以这样获取主要参数

$callbackPaymentData  = [
    'amount' => $responseNotification->getAmount(),
    'currency' => $responseNotification->getAmount()->getCurrency(),
    'commission' => $responseNotification->getAmount()->getCommission(),
    'status' => $responseNotification->getStatus()
];

您可以手动响应服务器

$notification->process(false);

// if success
$notification->successResponse();
// if error
$notification->errorResponse('Error message');

如果您使用代理服务器,则可以跳过IP检查

$notification->setSkipIpCheck();

自定义Api传输

您可以通过扩展 Capusta\SDK\Transport\AbstractApiTransport 来创建自己的api传输

class MyApiTransport extends \Capusta\SDK\Transport\AbstractApiTransport {
    protected function sendRequest(Psr7\Request $request) {
        // Implementing the sendRequest() method
    }
}