Search by

shadpay / sdk

safarishahim

Official PHP client library for the ShadPay merchant API (/v1). All amounts are integer Rial.

v1.2.0 2026-11-30 06:24 UTC

This package is not auto-updated.

Last update: 2026-12-01 05:36:39 UTC


README

Packagist Version PHP Version

Official PHP client library for the ShadPay Merchant API (/v1).

Built for production e-commerce and enterprise backends, shadpay/sdk supports PHP 8.1+ using ext-curl and ext-json (zero external runtime dependencies), enforces strict integer Rial (int) monetary amounts, returns associative arrays matching API field names directly, and implements automatic jittered exponential backoff for transient network and gateway failures.

Table of Contents

Installation

composer require shadpay/sdk

Quick Start

<?php

declare(strict_types=1);

use ShadPay\ApiError;
use ShadPay\Client;

$client = new Client(
    getenv('SHADPAY_BASE_URL') ?: 'https://pay.shad.ir/backend',
    getenv('SHADPAY_TOKEN') ?: ''
);

// 1. Create a payment (idempotent on merchant_ref)
$payment = $client->createPayment(
    merchantRef: 'ORD-100245',                        // Your unique order ID (idempotency key)
    amountRial: 500_000,                              // 500,000 Rial (= 50,000 Toman)
    callbackUrl: 'https://shop.example.ir/pay/return' // Must be an absolute HTTPS URL
);

// Persist $payment['id'] alongside your order, then redirect the customer's browser to:
// $payment['redirect_url']
echo "Payment ID: {$payment['id']} -> Redirect: {$payment['redirect_url']}\n";

Client Configuration

Client is lightweight and safe to reuse across requests.

By default, it configures a 30-second per-request timeout and performs up to 2 automatic retries with jittered exponential backoff (honoring the server's Retry-After header) on transport failures and HTTP 429, 502, 503, and 504 responses.

use ShadPay\Client;

$client = new Client(
    baseUrl: getenv('SHADPAY_BASE_URL') ?: 'https://pay.shad.ir/backend',
    token: getenv('SHADPAY_TOKEN') ?: '',
    timeout: 15,     // Per-request timeout in seconds (default: 30)
    transport: null, // Optional callable override for testing (default: cURL)
    retries: 3       // Set to 0 to disable automatic retries (default: 2)
);

Payment Operations

1. Create a Payment

If you know the paying user's Shad identifier ($shadIdentifier), pass it when creating the payment. It is optional, puts the payment into the user's ShadPay wallet history regardless of payment method, and gives a card payment a fallback wallet destination if an upstream bank cannot return funds to the card.

$res = $client->createPayment(
    merchantRef: 'ORD-100245',
    amountRial: 2_500_000, // 2,500,000 Rial
    callbackUrl: 'https://shop.example.ir/payments/callback',
    shadIdentifier: '09123456789' // Optional
);

2. Verify a Payment (Callback Handler)

When the payer completes or cancels payment, ShadPay redirects their browser to your $callbackUrl with query parameters ?payment_id=<UUID>&merchant_ref=<REF>&sig=<HMAC>.

Important Security Invariant: Browser redirect parameters are never authoritative. Always call verify() server-to-server to confirm and capture the funds. verify() is completely idempotent and serialized via database row locks.

use ShadPay\ApiError;

$paymentId = $_GET['payment_id'] ?? '';
$merchantRef = $_GET['merchant_ref'] ?? '';

// 1. Load your order by $merchantRef and confirm $paymentId matches the stored ID.
// 2. Call verify() server-to-server:
try {
    $payment = $client->verify($paymentId);
    if ($payment['state'] === 'VERIFIED') {
        // Payment is captured into your settleable balance! Fulfill the order.
        header('Location: /checkout/success');
        exit;
    }
    header('Location: /checkout/failed?state=' . urlencode($payment['state']));
} catch (ApiError $e) {
    error_log(sprintf('Verify failed for %s: %s (HTTP %d) - %s', $merchantRef, $e->code, $e->status, $e->getMessage()));
    header('Location: /checkout/failed');
}

3. Reverse a Payment (Before Verification)

If a payer returns from the gateway (PAID_UNVERIFIED), but your backend cannot fulfill the order (e.g., inventory ran out during checkout), call reverse() instead of verify() to immediately return the funds to the payer:

use ShadPay\ApiError;
use ShadPay\Client;

try {
    $reversed = $client->reverse($paymentId);
    echo $reversed['state']; // "REVERSED"
} catch (ApiError $e) {
    if ($e->code === Client::CODE_REVERSE_NOT_SUPPORTED) {
        // This PSP does not support explicit pre-verify reversal; leaving the payment
        // unverified causes the watchdog/PSP to auto-return the funds when the decision window expires.
    } else {
        throw $e;
    }
}

4. Refund a Verified Payment (Wallet Share)

For a VERIFIED payment funded partially or fully by the payer's Shad Wallets, refund() returns the specified amount back to the payer's wallets (idempotent on $merchantRefundRef). A PENDING refund completes on its own — read it again with listRefunds() rather than calling refund() again. Card-funded portions are settled and refunded via the PSP banking rail.

$refund = $client->refund(
    paymentId: $paymentId,
    merchantRefundRef: 'RFD-100245-1', // Unique idempotency key for this refund
    amountRial: 500_000,
    reason: 'Customer cancelled item #2'
);
echo "Refund status: {$refund['status']}\n"; // "PENDING" | "SUCCEEDED" | "FAILED"

// List all refunds for a payment (oldest first):
$refunds = $client->listRefunds($paymentId);

5. Query a Single Payment

$p = $client->getPayment($paymentId);
echo "State: {$p['state']}, Amount: {$p['amount_rial']} Rial\n";

Financial & Reporting Operations

1. Get Merchant Balance

$bal = $client->balance();
echo "Settleable: {$bal['settleable_rial']} Rial | Settled: {$bal['settled_rial']} Rial\n";

2. Iterate Paginated Payments, Ledger & Settlements

All list endpoints use cursor-based keyset pagination ($cursor and $limit, up to 100 items per page):

$cursor = null;
do {
    $page = $client->listLedger($cursor, 50);
    foreach ($page['items'] as $entry) {
        // $entry['entry_type']: "capture" (+), "fee" (-), "reversal" (-), "adjustment" (+/-)
        echo "[{$entry['created_at']}] {$entry['entry_type']}: {$entry['amount_rial']} Rial (Payment: {$entry['payment_id']})\n";
    }
    $cursor = $page['has_more'] ? $page['next_cursor'] : null;
} while ($cursor !== null);

Similarly, use $client->listPayments($cursor, 50) and $client->listSettlements($cursor, 50) to paginate transactions and settlement payouts.

Error Handling

All non-2xx responses throw ShadPay\ApiError exposing code, status, getMessage(), details (for validation errors), and retryAfterSeconds:

use ShadPay\ApiError;
use ShadPay\Client;

try {
    $p = $client->verify($paymentId);
} catch (ApiError $e) {
    switch ($e->code) {
        case Client::CODE_PAYMENT_NOT_PAYABLE:
            // Payment was not paid, expired, or failed
            break;
        case Client::CODE_INVALID_STATE:
            // Payment was already reversed or expired
            break;
        case Client::CODE_IP_NOT_ALLOWED:
        case Client::CODE_UNAUTHENTICATED:
            // Configuration / credential issue — alert ops!
            break;
        case Client::CODE_VALIDATION:
            foreach ($e->details as $d) {
                error_log("Invalid field {$d['field']}: {$d['message']}");
            }
            break;
    }
}

Error Code Constants (ShadPay\Client)

Constant Wire Value HTTP Meaning
Client::CODE_VALIDATION VALIDATION_ERROR 400 Invalid input field (inspect $e->details)
Client::CODE_UNAUTHENTICATED UNAUTHENTICATED 401 Missing, invalid, or revoked X-Token
Client::CODE_IP_NOT_ALLOWED IP_NOT_ALLOWED 403 Source IP is not in the merchant's IP allowlist
Client::CODE_FORBIDDEN FORBIDDEN 403 Merchant account is suspended or unauthorized
Client::CODE_NOT_FOUND NOT_FOUND 404 Payment ID not found for this merchant
Client::CODE_DUPLICATE_REF DUPLICATE_REF 409 merchant_ref already exists with different parameters
Client::CODE_INVALID_STATE INVALID_STATE 409 Action not allowed from current payment state
Client::CODE_PAYMENT_NOT_PAYABLE PAYMENT_NOT_PAYABLE 409 Payment is unpaid, expired, or failed
Client::CODE_PAYMENT_NOT_REFUNDABLE PAYMENT_NOT_REFUNDABLE 409 Payment is not verified or has no wallet share
Client::CODE_REFUND_EXCEEDS_REFUNDABLE REFUND_EXCEEDS_REFUNDABLE 409 Refund exceeds remaining refundable wallet amount
Client::CODE_REVERSE_NOT_SUPPORTED REVERSE_NOT_SUPPORTED 409 PSP does not support explicit pre-verify reversal
Client::CODE_RATE_LIMITED RATE_LIMITED 429 Too many requests (auto-retried via Retry-After)
Client::CODE_PSP_ERROR PSP_ERROR 502 Upstream PSP error (auto-retried)
Client::CODE_INTERNAL INTERNAL_ERROR 500 Unexpected server error

Development & Testing

composer install
composer test

Production Best Practices

  1. Always Persist $payment['id'] Before Redirecting: Store the UUID returned by createPayment() alongside your order record before redirecting the customer's browser.
  2. Never Use float or Toman at the API Boundary: Convert Toman to integer Rial ($amountToman * 10) before calling createPayment() or refund().
  3. Verify Promptly Within the Decision Window: Call verify() immediately inside your callback handler. Any PAID_UNVERIFIED transaction left unverified past the decision window is automatically reversed back to the payer by ShadPay's watchdog so no customer funds are ever stranded.
  4. Keep Credentials Server-Side & Allowlisted: Send X-Token only from your backend servers whose outbound IP addresses or CIDR blocks are registered in your ShadPay merchant IP allowlist.