paycow/paycow-php-sdk
Official client library supporting both Composer and standalone PSR-4 autoloading.
v1.0.0
17 KB
PHP 7.4 - 8.3+
Zero Dependencies
PSR-4 Compatible
ext-curl & ext-json
Core Architectural Principles
Pure Decimal String Arithmetic
Cryptocurrency amounts are preserved and evaluated strictly as decimal strings. Eliminates IEEE-754 binary floating-point precision loss and round-off drift.
Timing-Safe HMAC-SHA256
Webhook signatures are evaluated via timing-attack safe comparisons (hash_equals) over timestamp.rawPayload, with strict 300s timestamp freshness verification.
Dual Distribution (Zero Dependency)
Works seamlessly with Composer in modern frameworks (Laravel, Symfony) or via the embedded standalone autoload.php in legacy systems and WordPress plugins.
100% Non-Custodial
The SDK handles session creation, status polling, and webhook verification without ever touching or storing private keys. Funds settle directly into merchant vault addresses.
1 Installation
You can integrate the PayCow PHP SDK using Composer or manual download:
Option A: Composer (Recommended)
composer require paycow/paycow-php-sdk
Option B: Standalone PSR-4 Autoloader (No Composer required)
Download and extract paycow-php-sdk.zip into your project, then require the autoloader:
<?php
require_once __DIR__ . '/paycow-php-sdk/autoload.php';
use PayCow\Sdk\PayCowClient;
2 Client Initialization
Initialize the client with your Merchant API Key and API Secret obtained from the PayCow Merchant Dashboard:
<?php
use PayCow\Sdk\PayCowClient;
use PayCow\Sdk\Config;
// Initialize with credentials
$client = new PayCowClient([
'apiKey' => 'your_merchant_api_key',
'apiSecret' => 'your_merchant_api_secret',
'environment' => 'production', // or 'sandbox'
'timeout' => 30, // cURL timeout in seconds
]);
3 Creating a Checkout Session
To accept payment, create a checkout session by specifying the amount in USDT, customer information, and callback URLs:
<?php
try {
$session = $client->payments()->createSession([
'amount' => '50.00', // Amount in USDT (string format)
'currency' => 'USDT', // Must be USDT
'network' => 'TRC20', // 'TRC20' or 'ERC20'
'orderId' => 'INV-10948', // Your internal order reference
'customerEmail'=> '
[email protected]', // Optional
'successUrl' => 'https://example.com/checkout/success',
'cancelUrl' => 'https://example.com/checkout/cancel',
]);
// Access typed response data
$sessionId = $session->getSessionId();
$paymentUrl = $session->getPaymentUrl();
$depositAddress = $session->getDepositAddress();
$amountPayable = $session->getAmount();
// Redirect the customer to the PayCow hosted checkout
header('Location: ' . $paymentUrl);
exit;
} catch (\PayCow\Sdk\Exceptions\AuthenticationException $e) {
// Invalid API credentials
error_log('Authentication failed: ' . $e->getMessage());
} catch (\PayCow\Sdk\Exceptions\ApiException $e) {
// Validation or protocol error
error_log('API Error (' . $e->getStatusCode() . '): ' . $e->getMessage());
}
4 Querying Payment Status
You can actively poll or check the status of any session by its sessionId:
<?php
$status = $client->payments()->getStatus('sess_live_9a8b7c6d5e');
if ($status->isPaid()) {
$txHash = $status->getTxHash();
$amountReceived = $status->getReceivedAmount();
// Complete customer fulfillment
} elseif ($status->isConfirming()) {
$confirmations = $status->getConfirmations();
// Waiting for required block confirmations
} elseif ($status->isExpired()) {
// Payment window elapsed without valid transaction
}
5 Secure Webhook Verification
PayCow dispatches real-time HTTPS POST notifications upon state changes. The SDK provides a high-security verifier that protects against forged payloads and replay attacks:
<?php
use PayCow\Sdk\PayCowClient;
use PayCow\Sdk\Exceptions\WebhookVerificationException;
// Read raw request body and signature header
$rawPayload = file_get_contents('php://input');
$signatureHeader = $_SERVER['HTTP_X_PAYCOW_SIGNATURE'] ?? '';
$webhookSecret = 'whsec_your_webhook_signing_secret';
$client = new PayCowClient([
'apiKey' => 'your_api_key',
'apiSecret' => 'your_api_secret',
]);
try {
// Verify signature with 300-second timestamp tolerance
$event = $client->webhooks()->verifyHeaderSignature($rawPayload, $signatureHeader, $webhookSecret);
$eventType = $event->getType(); // e.g. 'payment.paid'
$sessionId = $event->getSessionId();
$amount = $event->getAmount();
$txHash = $event->getTxHash();
switch ($eventType) {
case 'payment.paid':
// Order is fully settled on-chain
updateOrderAsPaid($event->getOrderId(), $txHash);
break;
case 'payment.confirming':
// Block confirmations accruing
break;
case 'payment.expired':
// Session expired
break;
}
// Acknowledge delivery
http_response_code(200);
echo json_encode(['status' => 'success']);
} catch (WebhookVerificationException $e) {
http_response_code(400);
echo json_encode(['error' => 'Invalid webhook signature: ' . $e->getMessage()]);
exit;
}
Replay Attack Prevention
The x-paycow-signature header contains t={timestamp},v1={hash}. The verifier checks that the timestamp is within 300 seconds of the server clock to prevent replay attacks by malicious intermediaries.
6 Exact Decimal String Comparison
In cryptocurrency accounting, floating-point arithmetic (like float or epsilon subtraction) introduces rounding errors that lead to reconciliation discrepancies. The SDK provides a pure decimal string comparator:
<?php
use PayCow\Sdk\Payments\PaymentService;
$receivedAmount = '54.000000';
$requiredAmount = '54.00';
// Compare amounts safely without floating-point conversion
// Returns: -1 if $received < $required, 0 if equal, 1 if $received > $required
$comparison = PaymentService::compareDecimalStrings($receivedAmount, $requiredAmount);
if ($comparison >= 0) {
// Sufficient payment received
} else {
// Underpaid
}
Official Implementations Powered by this SDK
The official PayCow plugins for popular e-commerce and billing systems rely directly on this SDK for all protocol operations:
WooCommerce Plugin
Embeds the PayCow PHP SDK for classic checkout and modern Cart & Checkout Blocks with HPOS order synchronization.
View WooCommerce Guide →
WHMCS Payment Gateway
Uses the PayCow PHP SDK for hosting invoice reconciliation, client network selection, and zero-float monetary checks.
View WHMCS Guide →