PHP Examples
Complete PHP example client for integrating with the 123hub API using cURL andhash('sha512', ...).
This is a reference implementation, not an official SDK package. It works with
PHP 8.0+ and requires only the built-in cURL and JSON extensions.
Configuration
Store your credentials in environment variables or a.env file:
export PAYMENT_API_APP_ID="1"
export PAYMENT_API_SECRET_KEY="your_secret_key"
PaymentApiClient Class
A complete, reusable client class for all API operations:<?php
class PaymentApiClient
{
private string $appId;
private string $secretKey;
private string $baseUrl;
public function __construct(
?string $appId = null,
?string $secretKey = null,
string $baseUrl = 'https://api.bafanglaicai88.com'
) {
$this->appId = $appId ?? getenv('PAYMENT_API_APP_ID') ?: '';
$this->secretKey = $secretKey ?? getenv('PAYMENT_API_SECRET_KEY') ?: '';
$this->baseUrl = $baseUrl;
if (!$this->appId || !$this->secretKey) {
throw new InvalidArgumentException('appId and secretKey are required');
}
}
/**
* Sign and send a request to the 123hub API.
*/
private function send(array $body): array
{
// Serialize once: the hash must cover exactly the bytes that are sent.
$bodyStr = json_encode($body, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE | JSON_THROW_ON_ERROR);
$headers = [
'Content-Type: application/json',
'X-Data-Application-Id: ' . $this->appId,
// Lowercase hex SHA-512 of (raw body + secret key)
'X-Data-Hash: ' . hash('sha512', $bodyStr . $this->secretKey),
// Optional replay protection: send both headers or neither. They are not part of the hash.
'X-Data-Timestamp: ' . time(),
'X-Data-Nonce: ' . bin2hex(random_bytes(16)),
];
$ch = curl_init();
$responseHeaders = [];
curl_setopt_array($ch, [
CURLOPT_URL => $this->baseUrl . '/public/api/multihub/v1',
CURLOPT_POST => true,
CURLOPT_POSTFIELDS => $bodyStr,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_CONNECTTIMEOUT => 3,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTPHEADER => $headers,
CURLOPT_HEADERFUNCTION => static function ($curl, string $line) use (&$responseHeaders): int {
if (stripos($line, 'HTTP/') === 0) {
$responseHeaders = []; // new header block (e.g. after 100 Continue)
} elseif (str_contains($line, ':')) {
[$name, $value] = explode(':', $line, 2);
$responseHeaders[strtolower(trim($name))] = trim($value);
}
return strlen($line);
},
]);
$response = curl_exec($ch);
$curlError = curl_error($ch);
$httpStatus = curl_getinfo($ch, CURLINFO_RESPONSE_CODE);
curl_close($ch);
if ($curlError) {
throw new RuntimeException('cURL error: ' . $curlError);
}
if (!is_string($response)) {
throw new RuntimeException('Empty gateway response');
}
// Check the response X-Data-Hash over the exact response bytes before trusting them
$received = $responseHeaders['x-data-hash'] ?? null;
if ($received !== null) {
$expected = hash('sha512', $response . $this->secretKey);
if (!hash_equals($expected, strtolower($received))) {
throw new RuntimeException('response signature verification failed');
}
}
$decoded = json_decode($response, true);
if (!is_array($decoded) || !is_bool($decoded['success'] ?? null)) {
// Not the standard envelope, e.g. a 503 returned before authentication
throw new RuntimeException("Unexpected HTTP {$httpStatus} response: " . substr($response, 0, 200));
}
if ($received === null && $decoded['success']) {
// Successful responses are always signed; never trust an unsigned one
throw new RuntimeException('response signature verification failed: X-Data-Hash missing');
}
// Errors raised before authentication (e.g. 3000, 3001, 3003, 3006) are
// unsigned and are returned as-is.
return $decoded;
}
/**
* Health check / connectivity test.
*/
public function ping(): array
{
return $this->send(['method' => 'gateway.ping', 'params' => new \stdClass()]);
}
/**
* Create a deposit (pay-in) payment.
*/
public function createDeposit(
int $serviceId,
int $amount,
string $currency,
string $cId,
array $extra = []
): array {
return $this->send([
'method' => 'payment.in',
'service_id' => $serviceId,
'params' => [
'payment' => array_merge([
'identifiers' => ['c_id' => $cId],
'amount' => ['value' => $amount, 'currency' => $currency],
], $extra),
],
]);
}
/**
* Create a withdrawal (payout) payment.
*/
public function createWithdrawal(
int $serviceId,
int $amount,
string $currency,
string $cId,
array $receiver,
array $extra = []
): array {
return $this->send([
'method' => 'payment.out',
'service_id' => $serviceId,
'params' => [
'payment' => array_merge([
'identifiers' => ['c_id' => $cId],
'amount' => ['value' => $amount, 'currency' => $currency],
'receiver' => $receiver,
], $extra),
],
]);
}
/**
* Check payment status by identifiers.
*/
public function getStatus(?string $cId = null, ?string $hId = null): array
{
$identifiers = [];
if ($cId !== null) $identifiers['c_id'] = $cId;
if ($hId !== null) $identifiers['h_id'] = $hId;
return $this->send([
'method' => 'payment.status',
'params' => [
'payment' => ['identifiers' => $identifiers],
],
]);
}
/**
* Retrieve account balances.
*/
public function getBalance(): array
{
return $this->send(['method' => 'balance.get', 'params' => new \stdClass()]);
}
}
Usage Examples
Ping (Health Check)
<?php
require_once 'PaymentApiClient.php';
$client = new PaymentApiClient('1', 'your_secret_key');
$result = $client->ping();
if ($result['success']) {
echo "Gateway is up\n";
} else {
echo "Error: {$result['error']['code']} - {$result['error']['message']}\n";
}
Create a Deposit Payment
The examples below use INR (India), but the same client works for every supported country — just change theserviceId, currency, and country values.
<?php
$client = new PaymentApiClient('1', 'your_secret_key');
$result = $client->createDeposit(
serviceId: 14701,
amount: 10000,
currency: 'INR',
cId: '12345',
extra: [
'description' => 'Order #12345',
'payer' => [
'email' => 'customer@example.com',
'person' => [
'first_name' => 'John',
'last_name' => 'Doe',
],
],
],
);
if ($result['success']) {
echo "Payment created successfully\n";
echo "Request ID: {$result['request_id']}\n";
} else {
echo "Error: {$result['error']['code']} - {$result['error']['message']}\n";
}
Create a Withdrawal (Payout)
<?php
$result = $client->createWithdrawal(
serviceId: 14701,
amount: 5000,
currency: 'INR',
cId: '67890',
receiver: [
'bank' => [
'account' => ['id' => '1234567890'],
'ifsc' => 'SBIN0001234',
],
'person' => [
'first_name' => 'Jane',
'last_name' => 'Doe',
],
],
extra: [
'description' => 'Payout #67890',
],
);
if ($result['success']) {
echo "Withdrawal created successfully\n";
} else {
echo "Error: {$result['error']['code']} - {$result['error']['message']}\n";
}
Check Payment Status
<?php
// Look up by client-side ID
$result = $client->getStatus(cId: '12345');
if ($result['success']) {
$status = $result['result']['payment']['status']['status'];
echo "Payment status: {$status}\n";
} else {
echo "Error: {$result['error']['code']} - {$result['error']['message']}\n";
}
// Look up by the 123hub payment ID (h_id from the create response)
$result = $client->getStatus(hId: 'pay_1774892151645_abcd');
Get Balance
<?php
$result = $client->getBalance();
if ($result['success']) {
foreach ($result['result']['balance']['amounts'] as $amount) {
echo "{$amount['currency']}: {$amount['value']}\n";
}
} else {
echo "Error: {$result['error']['code']} - {$result['error']['message']}\n";
}
Error Handling
Successful responses return HTTP 200. Most errors return HTTP 400; some use 403, 404, 409, 429 or 5xx (see Error codes). The client returns the decoded body for every standard envelope, so always use thesuccess field to determine the outcome:
<?php
$result = $client->createDeposit(14701, 10000, 'INR', '12345', [
'payer' => ['email' => 'customer@example.com'], // payer is required for payment.in
]);
if ($result['success']) {
// Operation succeeded
echo "Request ID: {$result['request_id']}\n";
echo "Processing time: {$result['processing_time']}ms\n";
} else {
// Operation failed
$error = $result['error'];
echo "Error code: {$error['code']}\n";
echo "Error message: {$error['message']}\n";
switch ($error['code']) {
case 3000:
echo "Authentication failed - check your secret key\n";
break;
case 1005:
echo "Invalid parameters - check request body\n";
break;
case 7002:
echo "Provider unavailable - check payment.status before retrying\n";
break;
default:
echo "Unhandled error code: {$error['code']}\n";
}
}
Handling Network Errors
Network-level errors can still occur independently of API responses:<?php
try {
$result = $client->ping();
if ($result['success']) {
echo "API is reachable\n";
} else {
echo "API error: {$result['error']['message']}\n";
}
} catch (RuntimeException $e) {
// cURL failures, a failed response signature check, or a non-envelope
// response (e.g. HTTP 503 before authentication)
echo "Request failed: {$e->getMessage()}\n";
} catch (InvalidArgumentException $e) {
echo "Configuration error: {$e->getMessage()}\n";
}
Laravel Integration
<?php
// app/Services/PaymentApiService.php
namespace App\Services;
class PaymentApiService
{
private string $appId;
private string $secretKey;
private string $baseUrl;
public function __construct()
{
$this->appId = config('services.payment_api.app_id');
$this->secretKey = config('services.payment_api.secret_key');
$this->baseUrl = config('services.payment_api.base_url', 'https://api.bafanglaicai88.com');
}
private function send(array $body): array
{
// Serialize once: the hash must cover exactly the bytes that are sent.
$bodyStr = json_encode($body, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE | JSON_THROW_ON_ERROR);
$headers = [
'X-Data-Application-Id' => $this->appId,
'X-Data-Hash' => hash('sha512', $bodyStr . $this->secretKey),
// Optional replay pair (both or neither); not part of the hash
'X-Data-Timestamp' => (string) time(),
'X-Data-Nonce' => bin2hex(random_bytes(16)),
];
$response = \Illuminate\Support\Facades\Http::connectTimeout(3)
->timeout(30)
->withHeaders($headers)
->withBody($bodyStr, 'application/json')
->post($this->baseUrl . '/public/api/multihub/v1');
// Verify the response X-Data-Hash over the exact response bytes
$raw = $response->body();
$received = $response->header('X-Data-Hash'); // '' when absent
if ($received !== '' && !hash_equals(hash('sha512', $raw . $this->secretKey), strtolower(trim($received)))) {
throw new \RuntimeException('response signature verification failed');
}
$decoded = json_decode($raw, true);
if (!is_array($decoded) || !is_bool($decoded['success'] ?? null)) {
throw new \RuntimeException("Unexpected HTTP {$response->status()} response: " . substr($raw, 0, 200));
}
if ($received === '' && $decoded['success']) {
throw new \RuntimeException('response signature verification failed: X-Data-Hash missing');
}
return $decoded; // unsigned errors before authentication are returned as-is
}
public function ping(): array
{
return $this->send(['method' => 'gateway.ping', 'params' => new \stdClass()]);
}
public function createDeposit(int $serviceId, int $amount, string $currency, string $cId, array $extra = []): array
{
return $this->send([
'method' => 'payment.in',
'service_id' => $serviceId,
'params' => [
'payment' => array_merge([
'identifiers' => ['c_id' => $cId],
'amount' => ['value' => $amount, 'currency' => $currency],
], $extra),
],
]);
}
public function getStatus(?string $cId = null, ?string $hId = null): array
{
$identifiers = [];
if ($cId !== null) $identifiers['c_id'] = $cId;
if ($hId !== null) $identifiers['h_id'] = $hId;
return $this->send([
'method' => 'payment.status',
'params' => ['payment' => ['identifiers' => $identifiers]],
]);
}
public function getBalance(): array
{
return $this->send(['method' => 'balance.get', 'params' => new \stdClass()]);
}
}
<?php
// config/services.php (add to existing config)
return [
// ...
'payment_api' => [
'app_id' => env('PAYMENT_API_APP_ID'),
'secret_key' => env('PAYMENT_API_SECRET_KEY'),
'base_url' => env('PAYMENT_API_BASE_URL', 'https://api.bafanglaicai88.com'),
],
];
Complete Example
<?php
/**
* 123hub API Integration Example
*
* Demonstrates the complete flow: ping, check balance, create a deposit,
* and poll for status.
*/
require_once 'PaymentApiClient.php';
function main(): void
{
$appId = getenv('PAYMENT_API_APP_ID') ?: '1';
$secretKey = getenv('PAYMENT_API_SECRET_KEY') ?: 'your_secret_key';
$client = new PaymentApiClient($appId, $secretKey);
// 1. Ping the gateway
$pingResult = $client->ping();
if (!$pingResult['success']) {
echo "Gateway unreachable: {$pingResult['error']['message']}\n";
return;
}
echo "Gateway is up\n";
// 2. Check balance
$balanceResult = $client->getBalance();
if ($balanceResult['success']) {
foreach ($balanceResult['result']['balance']['amounts'] as $b) {
echo " {$b['currency']}: {$b['value']}\n";
}
} else {
echo "Balance check failed: {$balanceResult['error']['message']}\n";
}
// 3. Create a deposit
$orderId = (string) time();
$depositResult = $client->createDeposit(
serviceId: 14701,
amount: 10000,
currency: 'INR',
cId: $orderId,
extra: [
'description' => "Order #{$orderId}",
'payer' => [
'email' => 'customer@example.com',
'person' => ['first_name' => 'John', 'last_name' => 'Doe'],
],
],
);
if ($depositResult['success']) {
echo "Deposit created (request_id={$depositResult['request_id']})\n";
} else {
echo "Deposit failed: {$depositResult['error']['message']}\n";
return;
}
// 4. Poll for status
for ($i = 0; $i < 5; $i++) {
sleep(3);
$statusResult = $client->getStatus(cId: $orderId);
if ($statusResult['success']) {
$status = $statusResult['result']['payment']['status']['status'];
echo "Payment status: {$status}\n";
if (in_array($status, ['success', 'error', 'canceled', 'declined', 'refunded', 'partially_refunded'])) {
break;
}
} else {
echo "Status check failed: {$statusResult['error']['message']}\n";
break;
}
}
}
main();
