ilrwebservices / cardpointe-gateway-rest-api-client
CardPointe Gateway API的PHP库
Requires
- php: >=7.4.0
- ext-json: *
- guzzlehttp/guzzle: >=6.0
README
这是一个简单的用于CardPointe Gateway REST API的PHP HTTP客户端。针对JSON和通过用户名和密码进行身份验证进行优化。基于Guzzle。
CardPointeGatewayRestClient
是扩展了GuzzleHttp\Client
的,因此它可以执行Guzzle能做的所有事情,还有更多。
请务必参考CardPointe Gateway API文档以获取详细信息。
安装
通过composer
composer require ilrwebservices/cardpointe-gateway-rest-api-client
用法
<?php require __DIR__ . '/../vendor/autoload.php'; use CardPointeGateway\CardPointeGatewayRestClient; $client = new CardPointeGatewayRestClient([ 'cp_user' => $_ENV['CARDPOINTE_GATEWAY_API_USER'], 'cp_pass' => $_ENV['CARDPOINTE_GATEWAY_API_PASS'], 'cp_site' => 'fts', ]);
注意这些设置是如何传递到客户端构造函数选项中的,以及其他Guzzle兼容选项。在这个例子中,一些敏感设置存储在环境变量中,因为这些设置不应该存储在代码中。
CardPointeGatewayRestClient
将自动将base_uri
选项设置为https://<cp_site>.cardconnect.com/cardconnect/rest/
。
现在您可以像在Guzzle中一样进行API调用
$client_response = $client->request('GET', 'https://<cp_site>.cardconnect.com/cardconnect/rest/inquireMerchant/<merchid>');
由于base_uri
选项已预先配置,您可以使用相对URL(但请确保不要添加开头的/
)
$client_response = $client->request('GET', 'inquireMerchant/<merchid>');
因为它是Guzzle,所以有简写方法
$client_response = $client->get('inquireMerchant/<merchid>');
响应是PSR-7响应消息,就像Guzzle一样,因此您可以通过getBody()
获取返回的数据
$client_data_raw = (string) $client_response->getBody(); // Returns: // { // "site": "fts", // "acctupdater": "N", // "cvv": "N", // "cardproc": "RPCT", // "fee_type": "N", // "enabled": true, // "echeck": "N", // "merchid": "xxxxxxxxxxxx", // "avs": "N" // }
对于application/json
响应,CardPointeGatewayRestClient
添加了一个非标准的getData()
方法,它会为您解码JSON响应
$client_data = $client_response->getData(); // Returns: // Array // ( // [site] => fts // [acctupdater] => N // [cvv] => N // [cardproc] => RPCT // [fee_type] => N // [enabled] => 1 // [echeck] => N // [merchid] => xxxxxxxxxxxx // [avs] => N // )
但是,请注意大型响应,因为它们可能会消耗太多内存。
可以通过Guzzle的json
请求选项将JSON数据发送到API端点
$new_client_response = $client->post('auth', [ 'json' => [ 'merchid' => 'xxxxxxxxxxxx', 'amount' => '20.01', 'expiry' => 'MMYY', 'account' => '4111111111111111', 'cvv2' => '123', ], ]);
错误处理
您可以使用Guzzle异常进行错误处理。CardPointe Gateway API端点通常使用4xx代码表示错误,因此GuzzleHttp\Exception\ClientException
是捕获这些错误的理想选择。
try { $new_client_response = $client->post('auth', [ 'json' => [ 'merchid': 'xxxxxxxxxxxx', 'amount': '20.01', 'expiry': 'MMYY', 'account': '4111111111111111', 'cvv2': '123', ], ]); } // Could not connect to server or other network issue. catch (\GuzzleHttp\Exception\ConnectException $e) { print_r($e->getMessage()); } // 4xx error. This is either a 400 Bad Request (e.g. invalid syntax) or // 401 Unauthorized (e.g. bad credentials). catch (\GuzzleHttp\Exception\ClientException $e) { print_r($e->getResponse()->getData()); print_r($e->getMessage()); } // 5xx error. This is an 'Internal Server Error'. catch (\GuzzleHttp\Exception\ServerException $e) { print_r($e->getResponse()->getData()); print_r($e->getMessage()); }
灵感来自drewm/mailchimp-api。