PHP code example of paymos / php-sdk

1. Go to this page and download the library: Download paymos/php-sdk library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

paymos / php-sdk example snippets


use Paymos\Client;
use Paymos\ClientConfig;

$client = new Client(new ClientConfig(
    'pk_test_REPLACE_WITH_YOUR_KEY',     // API Key
    'sk_test_REPLACE_WITH_YOUR_SECRET',  // API Secret
    'https://api.paymos.io',             // Base URL (omit for default)
    30                                   // Request timeout (seconds)
));

$balances = $client->balances()->get();
foreach ($balances as $b) {
    echo $b['currency'] . ': ' . $b['available'] . PHP_EOL;
}

use Paymos\IdempotencyKey;

$invoice = $client->invoices()->create(array(
    'project_id'         => 'prj_xxxxxxxxxxxx',
    'amount'             => '49.95',
    'currency'           => 'USD',                // fiat -> network unlocked
    'external_order_id'  => IdempotencyKey::externalOrderId('order'),
    // optional:
    // 'allow_multiple_payments' => false,
    // 'customer_fee_percent'    => 0,            // 0..100
    // 'client_id'               => 'cust_42',
));

echo $invoice['payment_url'];   // hosted invoice page
echo $invoice['invoice_id'];    // "inv_..."

$invoice = $client->invoices()->create(array(
    'project_id'        => 'prj_xxxxxxxxxxxx',
    'amount'            => '10.00',
    'currency'          => 'USDT',
    'network'           => 'tron',                // network locked
    'external_order_id' => 'order-7f3c',
));

$invoice = $client->invoices()->get('inv_xxxxxxxxxxxx');
$status  = $invoice['status'];                    // "awaiting_client" | "confirming" | "paid" | ...
$paid    = $invoice['payment']['paid'] ?? null;   // string decimal, or null

$page = $client->invoices()->listPage(array(
    'project_id' => 'prj_xxxxxxxxxxxx',
    'status'     => array('paid', 'paid_over'),
    'limit'      => 50,
));

foreach ($client->invoices()->iterate(array('status' => array('paid')), 10) as $invoice) {
    echo $invoice['invoice_id'] . PHP_EOL;
}

$client->invoices()->cancel('inv_xxxxxxxxxxxx', 'customer abandoned checkout');

$client->invoices()->simulatePayment('inv_xxxxxxxxxxxx', 'paid');

$wd = $client->withdrawals()->create(array(
    'destination_address' => 'TRX...whitelisted...address',
    'network'             => 'tron',
    'currency'            => 'USDT',
    'amount'              => '50.00',
    'external_order_id'   => 'payout_2026_05_01_001',
));
echo $wd['withdrawal_id'];  // "wdr_..."

$wd = $client->withdrawals()->get('wdr_xxxxxxxxxxxx');

$client->withdrawals()->cancel('wdr_xxxxxxxxxxxx', 'merchant requested');

// Sandbox only:
$client->withdrawals()->simulateCompletion('wdr_xxxxxxxxxxxx');

$page = $client->withdrawals()->listPage(array(
    'status' => array('created', 'pending_review'),
    'limit'  => 20,
));

foreach ($client->withdrawals()->iterate(array('status' => array('completed')), 10) as $withdrawal) {
    echo $withdrawal['withdrawal_id'] . PHP_EOL;
}

$channel = $client->paymentChannels()->create(array(
    'project_id'  => 'prj_xxxxxxxxxxxx',
    'external_id' => 'customer_42',        // your own stable id for this payer
));

foreach ($channel['networks'] as $rail) {
    if (!isset($rail['address'])) {
        continue;                          // this rail has not provisioned yet
    }

    echo $rail['network'] . ' ' . $rail['address'] . PHP_EOL;

    foreach ($rail['tokens'] as $token) {
        $minimum = isset($token['minimum_deposit']) ? $token['minimum_deposit'] : null;
        echo '  ' . $token['symbol'] . ' min: ' . ($minimum === null ? 'unavailable' : $minimum) . PHP_EOL;
    }
}

$feed = $client->paymentChannelDeposits()->readPage(array(
    'cursor' => $savedCursor,              // omit (or null) on the very first poll
    'limit'  => 100,
));

foreach ($feed['items'] as $deposit) {
    $this->credit($deposit);               // idempotently, by $deposit['id']
}

$this->saveCursor($feed['next_cursor']);   // always present, even on an empty page

$client->paymentChannels()->block('pc_xxxxxxxxxxxx');    // returns the updated channel
$client->paymentChannels()->unblock('pc_xxxxxxxxxxxx');

// Sandbox only ('network' is 

use Paymos\IdempotencyKey;

$key = IdempotencyKey::externalOrderId('wc');   // "wc_550e8400-e29b-41d4-a716-446655440000"

use Paymos\Webhook\InMemoryEventStore;
use Paymos\Webhook\WebhookEventProcessor;
use Paymos\Webhook\WebhookVerifier;
use Paymos\Exception\DuplicateEventException;
use Paymos\Exception\SignatureMismatchException;
use Paymos\Exception\TimestampSkewException;

$verifier  = new WebhookVerifier('whsec_xxxxxxxxxxxx', 300);
$processor = new WebhookEventProcessor($verifier, new InMemoryEventStore());

$signature = $_SERVER['HTTP_X_WEBHOOK_SIGNATURE'] ?? '';
$rawBody   = file_get_contents('php://input');

try {
    $event = $processor->process($signature, $rawBody);
    // $event === ['event_id' => '...', 'event_type' => '...', 'data' => [...], ...]
} catch (DuplicateEventException $e) {
    http_response_code(200);  // already processed - ack
    exit;
} catch (SignatureMismatchException $e) {
    http_response_code(401);
    exit;
} catch (TimestampSkewException $e) {
    http_response_code(401);
    exit;
}

// Map the event to a precise business action and update your order/payout state.
use Paymos\Plugin\StatusMapper;

if (strpos($event['event_type'], 'invoice.') === 0) {
    $action = StatusMapper::invoiceAction($event['event_type']);

    switch ($action) {
        case StatusMapper::ACTION_CONFIRMING:
            // On-chain transfer detected, waiting for confirmations.
            break;
        case StatusMapper::ACTION_AWAITING_PAYMENT:
            // Partial payment received, waiting for the rest.
            break;
        case StatusMapper::ACTION_PAYMENT_COMPLETE:
            // Terminal: invoice paid (or paid_over) - mark order paid, fulfil.
            break;
        case StatusMapper::ACTION_FAIL_ORDER:
            // Terminal: invoice underpaid past deadline.
            break;
        case StatusMapper::ACTION_CANCEL_ORDER:
            // Terminal: invoice expired or cancelled.
            break;
        case StatusMapper::ACTION_IGNORE:
            // Unrecognized / future invoice event - no state change.
            break;
    }
} else {
    $action = StatusMapper::withdrawalAction($event['event_type']);

    switch ($action) {
        case StatusMapper::ACTION_PROCESSING:
            // Withdrawal broadcast on-chain.
            break;
        case StatusMapper::ACTION_COMPLETED:
            // Terminal success.
            break;
        case StatusMapper::ACTION_FAILED:
            // Terminal failure - reversed back to balance.
            break;
        case StatusMapper::ACTION_CANCELLED:
            // Cancelled before broadcast.
            break;
        case StatusMapper::ACTION_IGNORE:
            // Informational event (withdrawal.created).
            break;
    }
}

http_response_code(200);

use Paymos\Webhook\EventStoreInterface;

final class WordPressEventStore implements EventStoreInterface
{
    public function remember($eventId, $ttlSeconds)
    {
        $key = 'paymos_evt_' . $eventId;
        if (get_transient($key)) {
            return false;
        }
        set_transient($key, 1, (int) $ttlSeconds);
        return true;
    }
}

$event = $processor->process($signature, $rawBody);

if ($event['event_type'] === 'payment_channel.deposit.confirmed' && $event['data']['is_final']) {
    $deposit = $event['data'];
    credit($deposit['payment_channel_external_id'], $deposit['net']); // idempotent by $event['event_id']
}

use Paymos\Exception\ApiException;
use Paymos\Exception\ConflictException;
use Paymos\Exception\GoneException;
use Paymos\Exception\NotFoundException;
use Paymos\Exception\RateLimitException;
use Paymos\Exception\UnavailableException;
use Paymos\Exception\ValidationException;

try {
    $client->invoices()->create($payload);
} catch (ValidationException $e) {
    foreach ($e->errors() as $err) {
        // $err = ['code' => '...', 'field' => '...|null', 'message' => '...']
    }
} catch (NotFoundException $e) {
    // 404
} catch (ConflictException $e) {
    // 409 - e.g. insufficient_balance. $e->errorCode() / $e->detail() (flat envelope).
} catch (GoneException $e) {
    // 410 - resource is in a terminal state (cancel after Paid, etc.)
} catch (RateLimitException $e) {
    // 429 - SDK retries automatically (any method); surfaces only after RetryPolicy
    // is exhausted. $e->retryAfterSeconds() gives the server's Retry-After hint.
} catch (UnavailableException $e) {
    // 503 - upstream / transient. Retried only on idempotent methods (GET/HEAD);
    // a 503 on a POST surfaces immediately (it may already have taken effect).
} catch (ApiException $e) {
    // any other API error
}

use Paymos\Client;
use Paymos\ClientConfig;
use Paymos\Http\CurlTransport;
use Paymos\Http\RetryPolicy;
use Paymos\Http\RetryingTransport;

$client = new Client(
    new ClientConfig('pk_test_...', 'sk_test_...'),
    new RetryingTransport(new CurlTransport(), new RetryPolicy(/* maxRetries */ 4, /* baseMs */ 250))
);

use Paymos\Client;
use Paymos\ClientConfig;
use Paymos\Http\MockTransport;
use Paymos\Http\HttpResponse;

$transport = new MockTransport(array(
    new HttpResponse(200, '{"invoice_id":"inv_123","status":"awaiting_client"}', array()),
));
$client = new Client(new ClientConfig('pk_test_a', 'sk_test_b'), $transport);
$client->invoices()->get('inv_123');

print_r($transport->requests());  // captured method/url/headers/body
bash
composer 
bash
docker run --rm -v "$(pwd):/sdk" -w /sdk php:7.4-cli php tests/run.php