Search by

varizet / varizet-php

varizet

PHP client for the Varizet (واریزت) card-to-card payment API: orders, refunds, webhooks and signature verification.

v1.1.0 2026-10-30 13:23 UTC

This package is not auto-updated.

Last update: 2026-12-03 03:41:57 UTC


README

PHP client for the Varizet («واریزت») public API (/v1, developer docs): orders with unique amounts, refunds, webhook endpoints, the sandbox deposit simulator and Varizet-Signature verification.

PHP 8.1+, only ext-curl and ext-json. Any PSR-18 client can replace cURL. Money is integer rial everywhere: the SDK refuses floats and strings for amounts.

composer require varizet/varizet-php

Without Composer (WHMCS, OpenCart, PrestaShop modules): bin/bundle.sh <dir> copies src/ and a standalone autoload.php into the module; require '<dir>/autoload.php';.

Quick start

use Varizet\VarizetClient;
use Varizet\Util\IdempotencyKey;

$varizet = new VarizetClient(getenv('VARIZET_API_KEY'), [
    // 'base_url' => 'http://host.docker.internal:4000',   // dev API; default https://api.varizet.ir
    'plugin' => ['kind' => 'whmcs', 'version' => '1.0.0', 'meta' => ['whmcs' => '8.10.1']],
]);

$order = $varizet->orders->create([
    'amount'            => 8_500_000,               // rial, ≥ 10 000
    'merchant_order_id' => 'INV-12345',
    'description'       => 'فاکتور #12345',
    'customer'          => ['name' => 'سارا محمدی', 'phone' => '09121234567'],
    'return_url'        => 'https://shop.ir/checkout/return?invoice=12345',
    'metadata'          => ['invoice_id' => '12345'],
], IdempotencyKey::forAttempt('whmcs', 12345, 1, $siteFingerprint));

header('Location: ' . $order->paymentUrl);        // hosted payment page

$order is a Model\Order: id, code, status, amount, uniqueAmount, paymentUrl, destination (card), expiresAt, graceUntil, paidAt, paidAmount, match, metadata, livemode, … (DateTimeImmutable in UTC, ints for money); toArray() returns the raw JSON.

API

Call HTTP
$v->orders->create(array $params, ?string $idempotencyKey) POST /v1/orders
$v->orders->retrieve($idOrCode) GET /v1/orders/{id}
$v->orders->list($filters) → Page<Order>; all($filters) → generator over every page GET /v1/orders?status=&merchant_order_id=&customer_phone=&created[gte]=&created[lte]=&limit=&starting_after=
$v->orders->retrieveMany(array $ids) → array<id, Order> (100 per request) GET /v1/orders?id[]=…
$v->orders->findByMerchantOrderId($ref) → ?Order GET /v1/orders?merchant_order_id=
$v->orders->cancel($id, ?$key) POST /v1/orders/{id}/cancel
$v->refunds->create(['order_id','amount','method' => card|iban,'reference'?,'reason'?], ?$key) POST /v1/refunds (refunds:write)
$v->refunds->retrieve($id), ->list(['order' => $orderId]), ->all() GET /v1/refunds/{id}, GET /v1/refunds?order=
VarizetClient::oneClickConnect(['app_url' => …])->start([...]) / ->exchange($code, $verifier, $siteUrl) panel /connect (PKCE) → POST /v1/integrations/connect/token (no key)
$v->webhookEndpoints->create(['url','events','description']) (→ secret, shown once) POST /v1/webhook_endpoints
->retrieve($id), ->list(), ->all(), ->update($id, [...]), ->delete($id) GET/PATCH/DELETE /v1/webhook_endpoints/{id}
->rotateSecret($id) (old secret signs for 24 h more), ->ping($id) POST …/rotate_secret, POST …/ping
$v->events->list(['type' => 'order.paid']), ->all(), ->resend($id) GET /v1/events, POST /v1/events/{id}/resend
$v->testHelpers->simulateDeposit(['amount' => $order->uniqueAmount, 'card_id' => …]) POST /v1/test/deposits (test keys only)
$v->me() → store, livemode, scopes, key prefix GET /v1/me
$v->lastResponse() → status, requestId, latency, attempts, rate-limit remaining —

Refunds are bookkeeping (the merchant moves the money); the panel and POST /v1/refunds record the same row and both send refund.created, whose data.object is the same Refund. Scopes: plugin keys from the connect flow have orders:read orders:write; webhook management needs webhooks:manage, recording refunds refunds:write (reading them orders:read or refunds:write).

One-click connect (Varizet\Connect, used by the WHMCS, OpenCart, PrestaShop and Laravel integrations): start() returns the consent URL plus state and the PKCE verifier, which the plugin keeps server-side (≤ OneClickConnect::FLOW_TTL); after the merchant approves, the browser returns to redirect_uri?code=…&state=… (or error=access_denied) and exchange() turns the code into the key and webhook secret (ConnectResult, shown once). Optional webhook_path tells the API where the plugin receives webhooks when its platform builds that URL differently.

Options: base_url, timeout (15 s; order creation ≥ 20 s), connect_timeout (5 s), max_retries (2), max_retry_delay_ms (5000), plugin, user_agent, http_client, curl_options.

Headers the SDK sends

Authorization: Bearer vz_…, Accept/Content-Type: application/json, User-Agent: varizet-php/1.0.0 PHP/8.2 …, and Varizet-Plugin: <kind>/<version>; k=v; sdk=1.0.0; php=8.2 (default sdk_php/1.0.0). The panel shows the integration's version from this header. Kinds the API knows: woocommerce edd opencart prestashop whmcs laravel.

Idempotency and retries

Every POST carries Idempotency-Key: yours, or a random UUID generated once per call. Network errors, 429 and 5xx are retried up to max_retries times with exponential backoff and jitter (Retry-After honoured up to max_retry_delay_ms), always with the same key, so a retry never creates a second order. Derive keys from your own order and attempt (IdempotencyKey::forAttempt('opencart', $orderId, $attempt, $site)); bump the attempt when the customer pays again with a different amount. The API keeps keys 24 h; the same key with another body is 409 idempotency_mismatch (IdempotencyException).

Errors

All exceptions implement Varizet\Exception\ExceptionInterface.

Exception When
InvalidRequestException 400 (amount_too_small, invalid_parameter)
AuthenticationException 401 (invalid_api_key, key_revoked)
PermissionException 403 (scope_missing, plan_limit_reached, testmode_required)
NotFoundException 404 (order_not_found)
ConflictException / IdempotencyException 409 (unique_amount_exhausted, order_not_cancelable, no_active_card / idempotency_mismatch)
ValidationException 422 (merchant_order_id_duplicate)
RateLimitException 429, retryAfter seconds
ServerException 5xx after retries
NetworkException no HTTP answer after retries
UnexpectedResponseException a 2xx the SDK cannot read
InvalidArgumentException caller error, nothing sent (float money, bad key format, …)

ApiException carries httpStatus, errorType, errorCode (stable, English: branch on it), param, requestId and getMessage() (the API's Persian, user-facing text: safe to show). context() is log-safe. The SDK never logs and never puts keys or bodies into exceptions.

Webhooks

use Varizet\Webhook\Webhook;
use Varizet\Exception\{SignatureVerificationException, InvalidPayloadException};

$payload = file_get_contents('php://input');          // raw bytes, never re-encoded JSON
try {
    $event = Webhook::constructEvent($payload, Webhook::headerFromServer($_SERVER), [
        'live' => $liveSecret, 'test' => $testSecret,    // or one string, or [current, previous]
    ]);
} catch (SignatureVerificationException $e) {          // reason: malformed | expired | mismatch
    http_response_code(401); exit;
} catch (InvalidPayloadException $e) {                 // signed but not an event, or wrong mode
    http_response_code(400); exit;
}

if ($event->isPing()) { http_response_code(200); exit; }
if ($order = $event->order()) {                        // order.* events
    // dedupe on $event->id; ignore OrderStatus::isRegression($local, $order->status)
}
http_response_code(200);

Verification is identical to the API's: t=<unix>,v1=<hex hmac_sha256(secret, t + "." + body)>, several v1= during secret rotation, unknown schemes ignored, constant-time comparison against every candidate, |now − t| ≤ 300 s. With live/test labels, an event signed by one mode's secret but claiming the other mode is refused. Delivery is at least once and unordered: dedupe on event.id, never let a late event undo a settled payment (OrderStatus::isRegression()), and when in doubt read the order (orders->retrieve()). Answer 2xx within 10 s; anything else is retried (10 s … 24 h, 8 times).

Polling fallback: keep a list of local orders whose Varizet status is in OrderStatus::OPEN, and every few minutes orders->retrieveMany($ids) until graceUntil has passed (+ a margin). Do not filter by calendar day.

Helpers

  • Util\Amount::toRial('850,000', 'IRT') → 8500000 (IRR, IRT/toman, IRHR, IRHT; Persian digits; exact half-up rounding), fromRial(), uniqueDigits().
  • Util\Format::rial(8500430) → «۸٬۵۰۰٬۴۳۰ ریال», uniqueAmountHtml($amount, $uniqueAmount) (the unique suffix in <b class="vz-uniq">), toPersianDigits(), toLatinDigits().
  • Util\IdempotencyKey::forAttempt(), siteFingerprint(), random().
  • Model\OrderStatus (OPEN, SETTLED, isTerminal(), isRegression()), Model\EventType.

Development (Docker, no local PHP)

bin/docker-php.sh composer install                       # composer:2, cache volume varizet-composer-cache
bin/docker-php.sh php vendor/bin/phpunit                 # unit suite on php:8.1-cli
PHP_IMAGE=php:8.2-cli bin/docker-php.sh php vendor/bin/phpunit
bin/docker-php.sh php vendor/bin/phpstan analyse --no-progress --memory-limit=512M   # level 8
bin/docker-php.sh sh 'find src -name "*.php" -print0 | xargs -0 -n1 php -l >/dev/null && echo lint ok'

# Against the running dev API with a sandbox key (values are passed by name, never printed):
VARIZET_API_KEY=vz_test_… VARIZET_API_BASE_URL=http://host.docker.internal:4000 \
  bin/docker-php.sh php vendor/bin/phpunit --testsuite integration

Signature vectors (tests/fixtures): contracts-signature.vector.json and webhook-signature.vector.json (rotation header, UTF-8 body, ±300/301 s) are produced by the API's own implementation, so the SDK is tested against the bytes the server sends. Inside the Varizet monorepo, node packages/sdk-php/tests/vectors/webhook-vector.mts [--write] checks or regenerates them.

Release: bump Version::SDK and CHANGELOG.md, run the suites, tag v1.x.y.

Contributing and security

Issues and pull requests are welcome. This repository is published from Varizet's main repository: accepted changes are applied there and appear here with the next release.

Please report security vulnerabilities privately to support@varizet.ir, not in public issues.

License

MIT, see LICENSE.