gopay/payments-sdk-php
Composer 安装命令:
composer require gopay/payments-sdk-php
包简介
GoPay's PHP SDK for Payments REST API
README 文档
README
Requirements
- PHP >= 8.1
- enabled extension
curl,json
Installation
The simplest way to install SDK is to use Composer:
composer require gopay/payments-sdk-php
Basic usage
// minimal configuration $gopay = GoPay\Api::payments([ 'goid' => 'my goid', 'clientId' => 'my id', 'clientSecret' => 'my secret', 'gatewayUrl' => 'gateway url' ]); // full configuration $gopay = GoPay\Api::payments([ 'goid' => 'my goid', 'clientId' => 'my id', 'clientSecret' => 'my secret', 'gatewayUrl' => 'gateway url', 'scope' => GoPay\Definition\TokenScope::ALL, 'language' => GoPay\Definition\Language::CZECH, 'timeout' => 30 ]);
Configuration
Required fields
| Required field | Data type | Documentation |
|---|---|---|
goid |
string | default GoPay account used in createPayment if target is not specified |
clientId |
string | https://doc.gopay.com/#access-token |
clientSecret |
string | https://doc.gopay.com/#access-token |
gatewayUrl |
string | test or production environment? |
Optional fields
| Optional field | Data type | Default value | Documentation |
|---|---|---|---|
scope |
string | GoPay\Definition\TokenScope::ALL |
https://doc.gopay.com/#access-token |
language |
string | GoPay\Definition\Language::ENGLISH |
language used in createPayment if lang is not specified + used for localization of errors |
timeout |
int | 30 | Browser timeout in seconds |
Available methods
| API | SDK method |
|---|---|
| Create a payment | $gopay->createPayment(array $payment) |
| Get status of a payment | $gopay->getStatus($id) |
| Refund a payment | $gopay->refundPayment($id, $amount) |
| Create a recurring payment | $gopay->createRecurrence($id, array $payment) |
| Cancel a recurring payment | $gopay->voidRecurrence($id) |
| Capture a preauthorized payment | $gopay->captureAuthorization($id) |
| Capture a preauthorized payment partially | $gopay->captureAuthorizationPartial($id, array $capturePayment) |
| Void a preauthorized payment | $gopay->voidAuthorization($id) |
| Get payment card details | $gopay->getCardDetails($cardId) |
| Delete a saved card | $gopay->deleteCard($cardId) |
| Get allowed payment methods for a currency | $gopay->getPaymentInstruments($goid, $currency) |
| Get all allowed payment methods | $gopay->getPaymentInstrumentsAll($goid) |
| Generate an account statement | $gopay->getAccountStatement(array $accountStatement) |
SDK response? Has my call succeed?
SDK returns wrapped API response. Every method returns
GoPay\Http\Response object. Structure of json/__toString
should be same as in documentation.
SDK throws no exception. Please create an issue if you catch one.
$response = $gopay->createPayment([/* define your payment */]); if ($response->hasSucceed()) { echo "hooray, API returned {$response}"; return $response->json['gw_url']; // url for initiation of gateway } else { // errors format: https://doc.gopay.com/en/?shell#http-result-codes echo "oops, API returned {$response->statusCode}: {$response}"; }
| Method | Description |
|---|---|
$response->hasSucceed() |
checks if API returns status code 200 |
$response->json |
decoded response, returned objects are converted into associative arrays |
$response->statusCode |
HTTP status code |
$response->rawBody |
raw body from HTTP response |
Are required fields and allowed values validated?
No. API validates fields pretty extensively so there is no need to duplicate validation in SDK. It would only introduce new type of error. Or we would have to perfectly simulate API error messages. That's why SDK just calls API which behavior is well documented in doc.gopay.com.
Advanced usage
Initiation of the payment gateway
// create payment and pass url to template $response = $gopay->createPayment([/* define your payment */]); if ($response->hasSucceed()) { $gatewayUrl => $response->json['gw_url'], $embedJs => $gopay->urlToEmbedJs() // render template }
Inline gateway
<form action="<?= $gatewayUrl ?>" method="post" id="gopay-payment-button"> <button name="pay" type="submit">Pay</button> <script type="text/javascript" src="<?= $embedJs ?>"></script> </form>
Redirect gateway
<form action="<?= $gatewayUrl ?>" method="post"> <button name="pay" type="submit">Pay</button> </form>
Asynchronous initialization using JavaScript
Enums (Code lists)
Instead of hardcoding bank codes string you can use predefined enums. Check using enums in create-payment example
| Type | Description |
|---|---|
| Language | Payment language, localization of error messages |
| Token scope | Authorization scope for OAuth2 |
| Payment enums | Enums for creating payment |
| Response enums | Result of creating payment, executing payment operations |
| ItemType enums | Type of an item |
| VatRate enums | VatRate of an item |
Framework integration
Cache access token
Access token expires after 30 minutes so it's expensive to use new token for every request.
Unfortunately it's default behavior of GoPay\Token\InMemoryTokenCache.
But you can implement your cache and store tokens in Memcache, Redis, files, ... It's up to you.
Your cache must implement GoPay\Token\TokenCache interface.
Be aware that there are two scopes (TokenScope) and
SDK can be used for different clients (clientId, gatewayUrl). So client passed to
methods is unique identifier (string) that is built for current environment.
Below you can see example implementation of caching tokens in file:
// register cache in optional service configuration $gopay = GoPay\payments( [/* your config */], ['cache' => new PrimitiveFileCache()] );
<?php use GoPay\Token\TokenCache; use GoPay\Token\AccessToken; class PrimitiveFileCache implements TokenCache { public function setAccessToken($client, AccessToken $t) { file_put_contents(__DIR__ . "/{$client}", serialize($t)); } public function getAccessToken($client) { $file = __DIR__ . "/{$client}"; if (file_exists($file)) { return unserialize(file_get_contents($file)); } return null; } }
Log HTTP communication
You can log every request and response from communication with API. Check available loggers
below. Or you can implement your own logger,
just implement GoPay\Http\Log\Logger interface.
// register logger in optional service configuration $gopay = GoPay\payments( [/* your config */], ['logger' => new GoPay\Http\Log\PrintHttpRequest()] );
| Available logger | Description |
|---|---|
| NullLogger | Default logger which does nothing |
| PrintHttpRequest | Prints basic information about request and response, used in remote tests |
Contributing
Contributions from others would be very much appreciated! Send pull request/ issue. Thanks!
License
Copyright (c) 2015 GoPay.com. MIT Licensed, see LICENSE for details.
gopay/payments-sdk-php 适用场景与选型建议
gopay/payments-sdk-php 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 1.74M 次下载、GitHub Stars 达 85, 最近一次更新时间为 2015 年 11 月 04 日, 在 PHP 生态内属于活跃度较高的组件。
它主要适用于以下技术方向: 「rest」 「api」 「payments」 「sdk」 「gopay」 等业务场景。在实际项目中,围绕这些方向常见需要落地的问题包括:接口对接、性能调优、并发安全、与既有框架(Laravel / ThinkPHP / Yii / Webman 等)的兼容适配,以及生产环境的日志埋点与稳定性保障。
我们在过去多个企业项目中使用过 gopay/payments-sdk-php 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。
基于 gopay/payments-sdk-php 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。
线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。
承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。
与 gopay/payments-sdk-php 相关的其它包
同方向 / 同关键字的高下载量 PHP Composer 包推荐,方便对比选型:
Dealing with payments through the Egyptian payment gateway PayMob
Librería para la gestión sencilla de pagos mediante TPV Redsys y Paypal
A PSR-7 compatible library for making CRUD API endpoints
Api bundle
A Flickr wrapper to allow you to call the Flickr api with Guzzle as the backend.Goal is to have 100% Flickr api coverage rather than just upload/display photos (currently at 23%).
BlockCypher's PHP SDK for REST API
统计信息
- 总下载量: 1.74M
- 月度下载量: 0
- 日度下载量: 0
- 收藏数: 88
- 点击次数: 17
- 依赖项目数: 15
- 推荐数: 0
其他信息
- 授权协议: MIT
- 更新时间: 2015-11-04