gr4vy / gr4vy-php
Requires
- php: ^8.2
- brick/date-time: ^0.7.0
- brick/math: ^0.12.1
- galbar/jsonpath: ^3.0
- guzzlehttp/guzzle: ^7.0
- lcobucci/jwt: ^5.5.0
- paragonie/sodium_compat_ext_sodium: >= 1
- phpdocumentor/type-resolver: ^1.8
- ramsey/uuid: ^4.7.6
- speakeasy/serializer: ^4.0.3
Requires (Dev)
- laravel/pint: ^1.21.2
- phpstan/phpstan: ^2.1.0
- phpunit/phpunit: ^10
- roave/security-advisories: dev-latest
- dev-main
- v1.0.0-beta.20
- v1.0.0-beta.19
- v1.0.0-beta.18
- v1.0.0-beta.17
- v1.0.0-beta.16
- v1.0.0-beta.15
- v1.0.0-beta.14
- v1.0.0-beta.13
- v1.0.0-beta.12
- v1.0.0-beta.11
- v1.0.0-beta.10
- v1.0.0-beta.9
- v1.0.0-beta.8
- v1.0.0-beta.7
- v1.0.0-beta.6
- v1.0.0-beta.5
- v1.0.0-beta.4
- v1.0.0-beta.2
- v1.0.0-beta.1
- v0.26.0
- v0.25.0
- v0.24.1
- v0.24.0
- v0.23.2
- v0.23.1
- v0.23.0
- v0.22.0
- v0.21.4
- v0.21.3
- v0.21.2
- v0.21.1
- v0.21.0
- v0.20.0
- v0.19.0
- v0.18.21
- v0.18.3
- v0.18.2
- v0.18.1
- v0.18.0
- v0.17.0
- v0.16.0
- v0.15.0
- v0.14.0
- v0.13.0
- v0.12.0
- v0.11.0
- v0.10.0
- v0.9.1
- v0.9.0
- v0.8.0
- v0.7.0
- v0.6.0
- v0.5.0
- v0.4.0
- v0.3.0
- v0.2.0
- v0.1.0
- dev-speakeasy-sdk-regen-1749154288
- dev-speakeasy-sdk-regen-1749145525
- dev-speakeasy-sdk-regen-1749141138
- dev-speakeasy-sdk-regen-1749055466
- dev-speakeasy-sdk-regen-1749045089
- dev-speakeasy-sdk-regen-1749027921
- dev-speakeasy-sdk-regen-1748963295
- dev-speakeasy-sdk-regen-1748954131
- dev-speakeasy-sdk-regen-1748952958
- dev-speakeasy-sdk-regen-1748947396
- dev-legacy
This package is auto-updated.
Last update: 2025-06-05 20:15:25 UTC
README
Developer-friendly & type-safe PHP SDK specifically catered to leverage the Gr4vy API.
Important
This is a Beta release of our latest SDK. Please refer to the legacy PHP SDK for the latest stable build.
Summary
Gr4vy Typescript SDK
The official Gr4vy SDK for Typescript provides a convenient way to interact with the Gr4vy API from your server-side application. This SDK allows you to seamlessly integrate Gr4vy's powerful payment orchestration capabilities, including:
- Creating Transactions: Initiate and process payments with various payment methods and services.
- Managing Buyers: Store and manage buyer information securely.
- Storing Payment Methods: Securely store and tokenize payment methods for future use.
- Handling Webhooks: Easily process and respond to webhook events from Gr4vy.
- And much more: Access the full suite of Gr4vy API payment features.
This SDK is designed to simplify development, reduce boilerplate code, and help you get up and running with Gr4vy quickly and efficiently. It handles authentication, request signing, and provides easy-to-use methods for most API endpoints.
Table of Contents
SDK Installation
The SDK relies on Composer to manage its dependencies.
To install the SDK and add it as a dependency to an existing composer.json
file:
composer require "gr4vy/gr4vy-php"
SDK Example Usage
Example
declare(strict_types=1); require 'vendor/autoload.php'; use Gr4vy; use Gr4vy\Auth; // Loaded the key from a file, env variable, // or anywhere else $privateKey = "..."; $sdk = Gr4vy\SDK::builder() ->setId('example') ->setServer('sandbox') ->setSecuritySource(Auth::withToken($privateKey)) ->setMerchantAccountId('default') ->build(); $response = $sdk->transactions->list(); if ($response->transactions !== null) { // handle response }
Important
Please use ->setSecuritySource(Auth::withToken($privateKey))
where the documentation mentions ->setSecurity('<YOUR_BEARER_TOKEN_HERE>')
.
Bearer token generation
Alternatively, you can create a token for use with the SDK or with your own client library.
use Gr4vy\Auth; $token = Auth::getToken($privateKey),
Note: This will only create a token once. Use
Auth::withToken
with our SDK to dynamically generate a token for every request.
Embed token generation
Alternatively, you can create a token for use with Embed as follows.
use Gr4vy; use Gr4vy\Auth; // Loaded the key from a file, env variable, // or anywhere else $privateKey = "..."; $sdk = Gr4vy\SDK::builder() ->setId('example') ->setServer('sandbox') ->setSecuritySource(Auth::withToken($privateKey)) ->setMerchantAccountId('default') ->build(); $response = $sdk->checkout_sessions.create(); $token = $token = Auth::getEmbedToken( privateKey: $privateKey, expiresIn: '+1 hour', checkoutSessionId: $response->checkoutSession->id, );
Note: This will only create a token once. Use
Auth::withToken
with our SDK to dynamically generate a token for every request.
Merchant account ID selection
Depending on the key used, you might need to explicitly define a merchant account ID to use. In our API,
this uses the X-GR4VY-MERCHANT-ACCOUNT-ID
header. When using the SDK, you can set the merchantAccountId
when initializing the SDK.
$sdk = Gr4vy\SDK::builder() ->setId('example') ->setServer('sandbox') ->setSecuritySource(Auth::withToken($privateKey)) ->setMerchantAccountId('your-merchant-account-id') ->build();
Webhooks verification
The SDK makes it easy to verify that incoming webhooks were actually sent by Gr4vy. Once you have configured the webhook subscription with its corresponding secret, that can be verified the following way:
use Gr4vy; // Webhook payload and headers $payload = "your-webhook-payload"; $secret = "your-webhook-secret"; $signatureHeader = "signatures-from-header"; $timestampHeader = "timestamp-from-header"; $timestampTolerance = 300; // optional, in seconds (default: 0) try { Webhooks::verifyWebhook( secret: $secret$, payload: $payload, signatureHeader: $signatureHeader$, timestampHeader: $timestampHeader, timestampTolerance: $timestampTolerance ); } catch(Throwable $th$) { // handle the exception }
Parameters
payload
: The raw payload string received in the webhook request.secret
: The secret used to sign the webhook. This is provided in your Gr4vy dashboard.signatureHeader
: TheX-Gr4vy-Signature
header from the webhook request.timestampHeader
: TheX-Gr4vy-Timestamp
header from the webhook request.timestampTolerance
: (Optional) The maximum allowed difference (in seconds) between the current time and the timestamp in the webhook. Defaults to0
(no tolerance).
Authentication
Per-Client Security Schemes
This SDK supports the following security scheme globally:
Name | Type | Scheme |
---|---|---|
bearerAuth |
http | HTTP Bearer |
To authenticate with the API the bearerAuth
parameter must be set when initializing the SDK. For example:
declare(strict_types=1); require 'vendor/autoload.php'; use Gr4vy; $sdk = Gr4vy\SDK::builder() ->setSecurity( '<YOUR_BEARER_TOKEN_HERE>' ) ->setMerchantAccountId('default') ->build(); $accountUpdaterJobCreate = new Gr4vy\AccountUpdaterJobCreate( paymentMethodIds: [ 'ef9496d8-53a5-4aad-8ca2-00eb68334389', 'f29e886e-93cc-4714-b4a3-12b7a718e595', ], ); $response = $sdk->accountUpdater->jobs->create( accountUpdaterJobCreate: $accountUpdaterJobCreate ); if ($response->accountUpdaterJob !== null) { // handle response }
Available Resources and Operations
Available methods
accountUpdater
accountUpdater->jobs
- create - Create account updater job
auditLogs
- list - List audit log entries
buyers
- list - List all buyers
- create - Add a buyer
- get - Get a buyer
- update - Update a buyer
- delete - Delete a buyer
buyers->giftCards
- list - List gift cards for a buyer
buyers->paymentMethods
- list - List payment methods for a buyer
buyers->shippingDetails
- create - Add buyer shipping details
- list - List a buyer's shipping details
- get - Get buyer shipping details
- update - Update a buyer's shipping details
- delete - Delete a buyer's shipping details
cardSchemeDefinitions
- list - List card scheme definitions
checkoutSessions
- create - Create checkout session
- update - Update checkout session
- get - Get checkout session
- delete - Delete checkout session
digitalWallets
- create - Register digital wallet
- list - List digital wallets
- get - Get digital wallet
- delete - Delete digital wallet
- update - Update digital wallet
digitalWallets->domains
digitalWallets->sessions
- googlePay - Create a Google Pay session
- applePay - Create a Apple Pay session
- clickToPay - Create a Click to Pay session
giftCards
giftCards->balances
- list - List gift card balances
merchantAccounts
- list - List all merchant accounts
- create - Create a merchant account
- get - Get a merchant account
- update - Update a merchant account
paymentLinks
- create - Add a payment link
- list - List all payment links
- expire - Expire a payment link
- get - Get payment link
paymentMethods
- list - List all payment methods
- create - Create payment method
- get - Get payment method
- delete - Delete payment method
paymentMethods->networkTokens
- list - List network tokens
- create - Provision network token
- suspend - Suspend network token
- resume - Resume network token
- delete - Delete network token
paymentMethods->networkTokens->cryptogram
- create - Provision network token cryptogram
paymentMethods->paymentServiceTokens
- list - List payment service tokens
- create - Create payment service token
- delete - Delete payment service token
paymentOptions
- list - List payment options
paymentServiceDefinitions
- list - List payment service definitions
- get - Get a payment service definition
- session - Create a session for apayment service definition
paymentServices
- list - List payment services
- create - Update a configured payment service
- get - Get payment service
- update - Configure a payment service
- delete - Delete a configured payment service
- verify - Verify payment service credentials
- session - Create a session for apayment service definition
payouts
refunds
- get - Get refund
reportExecutions
- list - List executed reports
reports
reports->executions
transactions
- list - List transactions
- create - Create transaction
- get - Get transaction
- capture - Capture transaction
- void - Void transaction
- sync - Sync transaction
transactions->events
- list - List transaction events
transactions->refunds
transactions->refunds->all
- create - Create batch transaction refund
transactions->settlements
Global Parameters
A parameter is configured globally. This parameter may be set on the SDK client instance itself during initialization. When configured as an option during SDK initialization, This global value will be used as the default on the operations that use it. When such operations are called, there is a place in each to override the global value, if needed.
For example, you can set merchant_account_id
to `` at SDK initialization and then you do not have to pass the same value on calls to operations like get
. But if you want to do so you may, which will locally override the global setting. See the example code below for a demonstration.
Available Globals
The following global parameter is available.
Name | Type | Description |
---|---|---|
merchantAccountId | string | The ID of the merchant account to use for this request. |
Example
declare(strict_types=1); require 'vendor/autoload.php'; use Gr4vy; $sdk = Gr4vy\SDK::builder() ->setMerchantAccountId('default') ->setSecurity( '<YOUR_BEARER_TOKEN_HERE>' ) ->build(); $response = $sdk->merchantAccounts->get( merchantAccountId: 'merchant-12345' ); if ($response->merchantAccount !== null) { // handle response }
Pagination
Some of the endpoints in this SDK support pagination. To use pagination, you make your SDK calls as usual, but the
returned object will be a Generator
instead of an individual response.
Working with generators is as simple as iterating over the responses in a foreach
loop, and you can see an example below:
declare(strict_types=1); require 'vendor/autoload.php'; use Gr4vy; $sdk = Gr4vy\SDK::builder() ->setMerchantAccountId('default') ->setSecurity( '<YOUR_BEARER_TOKEN_HERE>' ) ->build(); $request = new Gr4vy\ListBuyersRequest( cursor: 'ZXhhbXBsZTE', search: 'John', externalIdentifier: 'buyer-12345', ); $responses = $sdk->buyers->list( request: $request ); foreach ($responses as $response) { if ($response->statusCode === 200) { // handle response } }
Retries
Some of the endpoints in this SDK support retries. If you use the SDK without any configuration, it will fall back to the default retry strategy provided by the API. However, the default retry strategy can be overridden on a per-operation basis, or across the entire SDK.
To change the default retry strategy for a single API call, simply provide an Options
object built with a RetryConfig
object to the call:
declare(strict_types=1); require 'vendor/autoload.php'; use Gr4vy; use Gr4vy\Utils\Retry; $sdk = Gr4vy\SDK::builder() ->setMerchantAccountId('default') ->setSecurity( '<YOUR_BEARER_TOKEN_HERE>' ) ->build(); $request = new Gr4vy\ListBuyersRequest( cursor: 'ZXhhbXBsZTE', search: 'John', externalIdentifier: 'buyer-12345', ); $responses = $sdk->buyers->list( request: $request, options: Utils\Options->builder()->setRetryConfig( new Retry\RetryConfigBackoff( initialInterval: 1, maxInterval: 50, exponent: 1.1, maxElapsedTime: 100, retryConnectionErrors: false, ))->build() ); foreach ($responses as $response) { if ($response->statusCode === 200) { // handle response } }
If you'd like to override the default retry strategy for all operations that support retries, you can pass a RetryConfig
object to the SDKBuilder->setRetryConfig
function when initializing the SDK:
declare(strict_types=1); require 'vendor/autoload.php'; use Gr4vy; use Gr4vy\Utils\Retry; $sdk = Gr4vy\SDK::builder() ->setRetryConfig( new Retry\RetryConfigBackoff( initialInterval: 1, maxInterval: 50, exponent: 1.1, maxElapsedTime: 100, retryConnectionErrors: false, ) ) ->setMerchantAccountId('default') ->setSecurity( '<YOUR_BEARER_TOKEN_HERE>' ) ->build(); $request = new Gr4vy\ListBuyersRequest( cursor: 'ZXhhbXBsZTE', search: 'John', externalIdentifier: 'buyer-12345', ); $responses = $sdk->buyers->list( request: $request ); foreach ($responses as $response) { if ($response->statusCode === 200) { // handle response } }
Error Handling
Handling errors in this SDK should largely match your expectations. All operations return a response object or throw an exception.
By default an API error will raise a errors\APIException
exception, which has the following properties:
Property | Type | Description |
---|---|---|
$message |
string | The error message |
$statusCode |
int | The HTTP status code |
$rawResponse |
?\Psr\Http\Message\ResponseInterface | The raw HTTP response |
$body |
string | The response content |
When custom error responses are specified for an operation, the SDK may also throw their associated exception. You can refer to respective Errors tables in SDK docs for more details on possible exception types for each operation. For example, the create
method throws the following exceptions:
Error Type | Status Code | Content Type |
---|---|---|
errors\Error400 | 400 | application/json |
errors\Error401 | 401 | application/json |
errors\Error403 | 403 | application/json |
errors\Error404 | 404 | application/json |
errors\Error405 | 405 | application/json |
errors\Error409 | 409 | application/json |
errors\HTTPValidationError | 422 | application/json |
errors\Error425 | 425 | application/json |
errors\Error429 | 429 | application/json |
errors\Error500 | 500 | application/json |
errors\Error502 | 502 | application/json |
errors\Error504 | 504 | application/json |
errors\APIException | 4XX, 5XX | */* |
Example
declare(strict_types=1); require 'vendor/autoload.php'; use Gr4vy; use Gr4vy\errors; $sdk = Gr4vy\SDK::builder() ->setMerchantAccountId('default') ->setSecurity( '<YOUR_BEARER_TOKEN_HERE>' ) ->build(); try { $accountUpdaterJobCreate = new Gr4vy\AccountUpdaterJobCreate( paymentMethodIds: [ 'ef9496d8-53a5-4aad-8ca2-00eb68334389', 'f29e886e-93cc-4714-b4a3-12b7a718e595', ], ); $response = $sdk->accountUpdater->jobs->create( accountUpdaterJobCreate: $accountUpdaterJobCreate ); if ($response->accountUpdaterJob !== null) { // handle response } } catch (errors\Error400Throwable $e) { // handle $e->$container data throw $e; } catch (errors\Error401Throwable $e) { // handle $e->$container data throw $e; } catch (errors\Error403Throwable $e) { // handle $e->$container data throw $e; } catch (errors\Error404Throwable $e) { // handle $e->$container data throw $e; } catch (errors\Error405Throwable $e) { // handle $e->$container data throw $e; } catch (errors\Error409Throwable $e) { // handle $e->$container data throw $e; } catch (errors\HTTPValidationErrorThrowable $e) { // handle $e->$container data throw $e; } catch (errors\Error425Throwable $e) { // handle $e->$container data throw $e; } catch (errors\Error429Throwable $e) { // handle $e->$container data throw $e; } catch (errors\Error500Throwable $e) { // handle $e->$container data throw $e; } catch (errors\Error502Throwable $e) { // handle $e->$container data throw $e; } catch (errors\Error504Throwable $e) { // handle $e->$container data throw $e; } catch (errors\APIException $e) { // handle default exception throw $e; }
Server Selection
Select Server by Name
You can override the default server globally using the setServer(string $serverName)
builder method when initializing the SDK client instance. The selected server will then be used as the default on the operations that use it. This table lists the names associated with the available servers:
Name | Server | Variables | Description |
---|---|---|---|
production |
https://api.{id}.gr4vy.app |
id |
|
sandbox |
https://api.sandbox.{id}.gr4vy.app |
id |
If the selected server has variables, you may override its default values using the associated builder method(s):
Variable | BuilderMethod | Default | Description |
---|---|---|---|
id |
setId(string id) |
"example" |
The subdomain for your Gr4vy instance. |
Example
declare(strict_types=1); require 'vendor/autoload.php'; use Gr4vy; $sdk = Gr4vy\SDK::builder() ->setServer('sandbox') ->setId('<id>') ->setMerchantAccountId('default') ->setSecurity( '<YOUR_BEARER_TOKEN_HERE>' ) ->build(); $accountUpdaterJobCreate = new Gr4vy\AccountUpdaterJobCreate( paymentMethodIds: [ 'ef9496d8-53a5-4aad-8ca2-00eb68334389', 'f29e886e-93cc-4714-b4a3-12b7a718e595', ], ); $response = $sdk->accountUpdater->jobs->create( accountUpdaterJobCreate: $accountUpdaterJobCreate ); if ($response->accountUpdaterJob !== null) { // handle response }
Override Server URL Per-Client
The default server can also be overridden globally using the setServerUrl(string $serverUrl)
builder method when initializing the SDK client instance. For example:
declare(strict_types=1); require 'vendor/autoload.php'; use Gr4vy; $sdk = Gr4vy\SDK::builder() ->setServerURL('https://api.example.gr4vy.app') ->setMerchantAccountId('default') ->setSecurity( '<YOUR_BEARER_TOKEN_HERE>' ) ->build(); $accountUpdaterJobCreate = new Gr4vy\AccountUpdaterJobCreate( paymentMethodIds: [ 'ef9496d8-53a5-4aad-8ca2-00eb68334389', 'f29e886e-93cc-4714-b4a3-12b7a718e595', ], ); $response = $sdk->accountUpdater->jobs->create( accountUpdaterJobCreate: $accountUpdaterJobCreate ); if ($response->accountUpdaterJob !== null) { // handle response }
Development
Testing
To run the tests, install PHP and compose, ensure to download the private_key.pem
for the test environment, and run the following.
composer install
composer test
Additionally, the following tools can be used to lint the code.
# autoformat the code vendor/bin/pint tests src --repair # static code analysis vendor/bin/phpstan analyse src tests --level 7 --memory-limit 1G --no-progress --error-format=table
Maturity
This SDK is in beta, and there may be breaking changes between versions without a major version update. Therefore, we recommend pinning usage to a specific package version. This way, you can install the same version each time without breaking changes unless you are intentionally looking for the latest version.
Contributions
While we value open-source contributions to this SDK, this library is generated programmatically. Any manual changes added to internal files will be overwritten on the next generation. We look forward to hearing your feedback. Feel free to open a PR or an issue with a proof of concept and we'll do our best to include it in a future release.