Skip to Content
Docs

PHP

Call the Pay.com API from PHP with a method for each operation, typed responses, automatic paging, and webhook verification.

pay-com/pay-com-php has a method for each API operation, named after its resource: $pay->charges->create(), $pay->holds->capture(), and $pay->valueLists->items->create(). Parameters are arrays with the API's own field names, in snake_case, and responses are typed objects.

Requirements and install

You need PHP 7.4 or later, with ext-json, and ext-curl for the built-in transport.

Terminal

composer require pay-com/pay-com-php

Each operation's parameters are an array shape that PHPStan and Psalm check, such as PayCom\Types\ChargesCreateParams.

Set your key

Keep the key out of your code. The SDK reads it from PAY_COM_API_KEY:

Terminal

export PAY_COM_API_KEY='sk-pay-com-sandbox-…'

The SDK selects the sandbox or live environment automatically from the key prefix (sk-pay-com-sandbox- or sk-pay-com-live-). The key is never written to the SDK's logs or errors.

Create your first charge

Charge a saved payment method. Amounts are integers in minor units (for example, 2000 is $20.00 USD):

charge.php

<?php

require __DIR__ . '/vendor/autoload.php';

use PayCom\Pay;

$pay = new Pay();

$charge = $pay->charges->create([
    'amount' => 2000,
    'currency' => 'usd',
    'source' => 'pm_card_685125127054035968',
    'reference' => 'order-6735',
]);

echo $charge->id, ' ', $charge->status, "\n";

A field you leave out isn't sent. A response has a property for each field, null when the response leaves it out, and is also a read-only array: $charge['amount'].

The SDK sends a new idempotency key with each POST and DELETE, and the same one when it retries. To use your own, pass it after the parameters: $pay->charges->create($params, ['idempotency_key' => $key]).

It retries twice by default after a network error, a timeout, 409 request_in_progress, 421, 429, 502, 503, or 504. To decide yourself, pass 'max_retries' => 0, and set a reference on payments to help you find out what was created.

The SDK retries these only after a 429, or when they never left your server: every PUT and PATCH, webhookEndpoints->create(), and networkTokens->retrieveCryptogram(). If one of these requests receives no response, check whether it succeeded before sending it again.

When you call paymentLinks->update(), pass every field you want to keep, amount and currency included. An update without amount sets the link's amount to 0.

List every item

A list method returns its first page, which is also every item on every page, fetched as you reach them:

list.php

<?php

require __DIR__ . '/vendor/autoload.php';

use PayCom\Pay;

$pay = new Pay();

$page = $pay->charges->list(['limit' => 10]);
echo count($page->data ?? []), "\n";

foreach ($pay->charges->list(['created.greater_than' => new DateTimeImmutable('2026-11-01')]) as $charge) {
    echo $charge->id, "\n";
}

To collect them, with a limit, use $pay->charges->list()->take(500). Lists that use page numbers work the same way.

Catch a decline

A decline throws PaymentMethodException:

decline.php

<?php

require __DIR__ . '/vendor/autoload.php';

use PayCom\Exception\InvalidRequestException;
use PayCom\Exception\PaymentMethodException;
use PayCom\Pay;

$pay = new Pay();

try {
    $pay->charges->create(['amount' => 2000, 'currency' => 'usd', 'source' => 'pm_card_685125127054035968']);
} catch (PaymentMethodException $e) {
    echo 'Declined: ', $e->getDeclineCode(), "\n";
} catch (InvalidRequestException $e) {
    echo 'Fix the request: ', $e->getErrorCode(), ' ', $e->getMessage(), "\n";
}

A declined charge, hold, refund, or payout is still created, and its ID is in getError(), under its type.

Every exception is a PayCom\Exception\PayException, with getErrorType(), getErrorCode(), getHttpStatus(), and the API's body as getRaw(). Include getRequestId() when contacting Pay.com support. It is null when the API didn't get or couldn't read the request. After retries, getPrevious() holds an earlier attempt's error. The exception's class tells you what happened:

Error classCause
PaymentMethodExceptionPayment declined by the issuer or blocked by a risk rule (400)
InvalidRequestException400 or 422. NotFoundException, for 404, is one too
AuthenticationException401
PermissionException403
IdempotencyExceptionAn idempotency key in use, or used for another request
ConflictExceptionAny other 409
RateLimitException429
ApiException5xx, a redirect (none is followed), or a response the SDK didn't expect
ApiConnectionExceptionNo complete response. ApiTimeoutException is one too

ApiConnectionException::mayHaveReachedApi() is false only when the request surely never left your server. See Handle errors for what to do with each.

Verify a webhook

Pass the raw body, the Pay-Signature header, and the endpoint's whole signing secret. Return HTTP 400 only when SignatureVerificationException is thrown. Let other errors return 500 so Pay.com retries delivery:

webhooks.php

<?php

require __DIR__ . '/vendor/autoload.php';

use PayCom\Exception\SignatureVerificationException;
use PayCom\Webhook\Events\ChargeSucceededEvent;
use PayCom\Webhook\Webhooks;

$payload = (string) file_get_contents('php://input');
try {
    $event = (new Webhooks())->constructEvent($payload, $_SERVER['HTTP_PAY_SIGNATURE'] ?? null, (string) getenv('PAY_COM_WEBHOOK_SECRET'));
} catch (SignatureVerificationException $e) {
    http_response_code(400);
    exit;
}

if ($event instanceof ChargeSucceededEvent) {
    error_log('Paid: ' . $event->data->id);
}
http_response_code(200);

Any other exception is a 500, and Pay.com sends the event again. While you replace a secret, pass both, [$new, $old], and either one verifies. Skip events whose id you've already handled.

Each event type has a class, such as ChargeSucceededEvent, whose data is the typed object. In your tests, $pay->webhooks->generateTestHeader($payload, $secret) makes a valid header.

Options

Pass these to new Pay([...]).

api_keystring
The secret key.

Default: PAY_COM_API_KEY

environmentstring
sandbox or live, for a key without either prefix.
merchant_idstring
Target merchant ID for multi-workspace API keys.
timeout_msint
How long each attempt can take, in milliseconds, reading the response included.

Default: 60000

max_retriesint
Maximum number of automatic retry attempts.

Default: 2

base_urlstring
Custom API base URL for local mocks or proxies.
default_headersarray
Headers sent with every request.
transportPayCom\Http\Transport
Sends the requests, for a platform's own HTTP client. It never follows a redirect.

Default: CurlTransport

log_levelstring
Log verbosity level (debug, info, warning, error, or off), written to logger or error_log(). Also read from PAY_COM_LOG.

Default: warning

app_infostring
Your product and version, added to the User-Agent.

idempotency_key, merchant_id, timeout_ms, max_retries, and headers can also be set for one request, in the method's last argument. Passing an unrecognized option throws an exception. The sandbox's simulate endpoints are under $pay->testHelpers. $pay->documents->upload() takes the file's bytes, a stream, or an SplFileInfo, with its content_type. See Upload and download files.

In a WordPress or other plugin, prefix the SDK's namespace with Strauss or PHP-Scoper, since two plugins on one site may bundle different versions.

Was this page helpful?