Skip to content

PHP Integration Examples

This section provides examples of how to integrate with the API using PHP.

Authentication

<?php

class ApiClient {
    private $baseUrl;
    private $accessKey;
    private $secretKey;

    public function __construct($baseUrl, $accessKey, $secretKey) {
        $this->baseUrl = rtrim($baseUrl, '/');
        $this->accessKey = $accessKey;
        $this->secretKey = $secretKey;
    }

    private function getTimestamp() {
        return (string)(int)(microtime(true) * 1000);
    }

    private function generateSignature($path, $timestamp, $body = '') {
        $message = $this->accessKey . $path . $timestamp . $body;
        $signature = hash_hmac('sha256', $message, $this->secretKey);
        return $signature;
    }

    public function request($method, $endpoint, $params = [], $data = null) {
        $path = "/api/v1" . $endpoint;
        $url = $this->baseUrl . $path;

        $timestamp = $this->getTimestamp();

        $headers = [
            'X-Access-Key: ' . $this->accessKey,
            'X-Timestamp: ' . $timestamp
        ];

        $body = '';
        if (in_array(strtoupper($method), ['POST', 'PUT', 'PATCH']) && $data !== null) {
            $body = json_encode($data);
            $headers[] = 'Content-Type: application/json';
        }

        $headers[] = 'X-Signature: ' . $this->generateSignature($path, $timestamp, $body);

        $ch = curl_init();

        if (strtoupper($method) === 'GET' && !empty($params)) {
            $url .= '?' . http_build_query($params);
        }

        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

        switch (strtoupper($method)) {
            case 'POST':
                curl_setopt($ch, CURLOPT_POST, true);
                curl_setopt($ch, CURLOPT_POSTFIELDS, $body);
                break;
            case 'PUT':
                curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'PUT');
                curl_setopt($ch, CURLOPT_POSTFIELDS, $body);
                break;
            case 'DELETE':
                curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'DELETE');
                break;
            default:
                // GET
                break;
        }

        $response = curl_exec($ch);
        $error = curl_error($ch);
        curl_close($ch);

        if ($error) {
            throw new Exception("cURL Error: $error");
        }

        return json_decode($response, true);
    }

    public function get($endpoint, $params = []) {
        return $this->request('GET', $endpoint, $params);
    }

    public function post($endpoint, $data = []) {
        return $this->request('POST', $endpoint, [], $data);
    }
}

Usage Examples

Check Server Status

<?php

require_once 'ApiClient.php';

// Status endpoint doesn't require authentication
$ch = curl_init('https://api.001k.world/api/v1/status');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
curl_close($ch);

$status = json_decode($response, true);
echo "Server timestamp: " . $status['timestamp'] . "\n";

// For authenticated endpoints
$api = new ApiClient('https://api.001k.world', 'your_access_key', 'your_secret_key');

Get Account Balances

<?php

require_once 'ApiClient.php';

$api = new ApiClient('https://api.001k.world', 'your_access_key', 'your_secret_key');

$balances = $api->get('/balance');
foreach ($balances as $balance) {
    echo $balance['currency'] . ': ' . $balance['available'] . ' (available), ' . $balance['frozen'] . " (frozen)\n";
}

Generate Deposit Address

<?php

require_once 'ApiClient.php';

$api = new ApiClient('https://api.001k.world', 'your_access_key', 'your_secret_key');

$response = $api->post('/deposit/generate_address', [
    'currency' => 'BTC',
    'method' => 'btc_native',
    'callback_url' => 'https://your-server.com/callbacks/deposits',
    'custom_id' => 'my-deposit-address-123'
]);

echo "Deposit address: " . $response['address'] . "\n";
if (isset($response['tag'])) {
    echo "Tag: " . $response['tag'] . "\n";
}

Create Withdrawal

<?php

require_once 'ApiClient.php';

$api = new ApiClient('https://api.001k.world', 'your_access_key', 'your_secret_key');

$response = $api->post('/withdraw', [
    'currency' => 'BTC',
    'method' => 'btc_native',
    'amount' => '0.01000000',
    'address' => 'bc1qxy2kgdygjrsqtzq2n0yrf2493p83kkfjhx0wlh',
    'callback_url' => 'https://your-server.com/callbacks/withdrawals',
    'custom_id' => 'my-withdrawal-123'
]);

echo "Withdrawal created: " . $response['code'] . "\n";
echo "Status: " . $response['status'] . "\n";

Create Swap

<?php

require_once 'ApiClient.php';

$api = new ApiClient('https://api.001k.world', 'your_access_key', 'your_secret_key');

// First, get available swap directions
$directions = $api->get('/swap-directions');
foreach ($directions as $direction) {
    echo $direction['code'] . ': ' . $direction['spend_currency'] . ' -> '
        . $direction['receive_currency'] . ' (rate: ' . $direction['rate'] . ")\n";
}

// Create a swap
$response = $api->post('/swap/open', [
    'direction' => 'BTC-USDT',
    'spend_amount' => '0.01000000',
    'callback_url' => 'https://your-server.com/callbacks/swaps',
    'custom_id' => 'my-swap-123'
]);

echo "Swap created: " . $response['code'] . "\n";
echo "Spend: " . $response['spend_amount'] . ' ' . $response['spend_currency'] . "\n";
echo "Receive: " . $response['receive_amount'] . ' ' . $response['receive_currency'] . "\n";
echo "Status: " . $response['status'] . "\n";

Create Internal Transfer

<?php

require_once 'ApiClient.php';

$api = new ApiClient('https://api.001k.world', 'your_access_key', 'your_secret_key');

$response = $api->post('/internal-transfer', [
    'currency_code' => 'BTC',
    'amount' => '0.01000000',
    'recipient' => 'user123',
    'callback_url' => 'https://your-server.com/callbacks/transfers',
    'custom_id' => 'my-transfer-123',
    'note' => 'Payment for services'
]);

echo "Transfer created: " . $response['code'] . "\n";
echo "Status: " . $response['status'] . "\n";

Create Limit Order

<?php

require_once 'ApiClient.php';

$api = new ApiClient('https://api.001k.world', 'your_access_key', 'your_secret_key');

// First, get available trading pairs
$pairs = $api->get('/limit-pairs');
foreach ($pairs as $pair) {
    echo $pair['symbol'] . ': ' . $pair['current_price'] . ' (fee: ' . $pair['fee_percent'] . "%)\n";
}

// Create a limit order
$response = $api->post('/limit-order', [
    'pair' => 'BTCUSDT',
    'side' => 'buy',
    'receive_amount' => '0.01000000',
    'limit_price' => '29000.00',
    'callback_url' => 'https://your-server.com/callbacks/orders',
    'custom_id' => 'my-order-123'
]);

echo "Order created: " . $response['code'] . "\n";
echo "Status: " . $response['status'] . "\n";
echo "Base amount: " . $response['base_amount'] . "\n";
echo "Quote amount: " . $response['quote_amount'] . "\n";
echo "Filled base amount: " . $response['filled_base_amount'] . "\n";
echo "Filled quote amount: " . $response['filled_quote_amount'] . "\n";
echo "Fee currency: " . $response['fee_currency'] . "\n";
echo "Filled fee amount: " . $response['filled_fee_amount'] . "\n";
echo "Created at: " . $response['created_at'] . "\n";
echo "Updated at: " . $response['updated_at'] . "\n";
echo "Done at: " . ($response['done_at'] ?? 'N/A') . "\n";

Create AML Check

<?php

require_once 'ApiClient.php';

$api = new ApiClient('https://api.001k.world', 'your_access_key', 'your_secret_key');

// First, get available plans and tokens
$plans = $api->get('/aml/plan');
$tokens = $api->get('/aml/token');

foreach ($plans as $plan) {
    echo "Plan: " . $plan['code'] . ' - ' . $plan['name']
        . ' (price: ' . $plan['price'] . ' ' . $plan['currency'] . ")\n";
}

foreach ($tokens as $token) {
    echo "Token: " . $token['symbol'] . ' on ' . $token['network']
        . ' (ID: ' . $token['id'] . ")\n";
}

// Create an AML check
$response = $api->post('/aml/check', [
    'direction' => 'withdrawal',
    'token' => 1,  // Bitcoin
    'address' => 'bc1qxy2kgdygjrsqtzq2n0yrf2493p83kkfjhx0wlh',
    'callback_url' => 'https://your-server.com/callbacks/aml',
    'custom_id' => 'my-aml-check-123'
]);

echo "AML check created: " . $response['code'] . "\n";
echo "Status: " . $response['status'] . "\n";
echo "Direction: " . $response['direction'] . "\n";
echo "Token: " . $response['token'] . "\n";
echo "Address: " . $response['address'] . "\n";
echo "Transaction: " . ($response['transaction'] ?? 'N/A') . "\n";
echo "Created at: " . $response['created_at'] . "\n";
echo "Updated at: " . $response['updated_at'] . "\n";
if (isset($response['report'])) {
    echo "Report status: " . $response['report']['status'] . "\n";
    echo "Risk score: " . $response['report']['riskscore'] . "\n";
    echo "Alert grade: " . $response['report']['alert_grade'] . "\n";
}

Callback Handling

When the status of an operation changes, the API will send a callback to the URL provided in the callback_url parameter. Here's an example of how to handle these callbacks in a PHP application:

Important Note: You may not receive callbacks for every intermediate status change or field update if changes occur very rapidly. When operations transition through multiple states quickly, intermediate callbacks may be skipped. However, you will always receive callbacks for the final states of operations. Design your callback handling to be idempotent and not dependent on receiving every single state transition.

<?php

require_once 'ApiClient.php';

// Your API client
$api = new ApiClient('https://api.001k.world', 'your_access_key', 'your_secret_key');

// IP whitelist for callback security
$allowedIps = ['192.168.1.1', '10.0.0.1']; // Replace with actual IPs provided by support

// Verify client IP
function verifyIp() {
    global $allowedIps;
    $clientIp = $_SERVER['REMOTE_ADDR'];

    if (!in_array($clientIp, $allowedIps)) {
        http_response_code(403);
        echo json_encode(['error' => 'Unauthorized IP']);
        exit;
    }

    return true;
}

// Verify callback data by making an API request
function verifyData($endpoint, $code) {
    global $api;

    try {
        // Make an authenticated API request to verify the status
        $response = $api->get("$endpoint/$code");
        return $response;
    } catch (Exception $e) {
        // Handle any API request errors
        error_log("Error verifying data: " . $e->getMessage());
        return null;
    }
}

// Get the request body
$body = file_get_contents('php://input');
$data = json_decode($body, true);

// Process the callback based on the endpoint
$endpoint = $_SERVER['REQUEST_URI'];

// Verify IP for all callbacks
verifyIp();

switch ($endpoint) {
    case '/callbacks/deposits':
        // Handle deposit callbacks
        $code = $data['code'] ?? '';
        $status = $data['status'] ?? '';
        $customId = $data['custom_id'] ?? '';

        error_log("Deposit callback received: $code ($customId) - Status: $status");

        // Verify the data by making an API request
        $verifiedData = verifyData('/deposit', $code);
        if ($verifiedData && $verifiedData['status'] === $status) {
            // Process the callback (update database, send notifications, etc.)
            error_log("Deposit status verified");
        } else {
            error_log("Warning: Callback data verification failed!");
        }

        break;

    case '/callbacks/withdrawals':
        // Handle withdrawal callbacks
        $code = $data['code'] ?? '';
        $status = $data['status'] ?? '';
        $customId = $data['custom_id'] ?? '';

        error_log("Withdrawal callback received: $code ($customId) - Status: $status");

        // Verify the data by making an API request
        $verifiedData = verifyData('/withdraw', $code);
        if ($verifiedData && $verifiedData['status'] === $status) {
            // Process the callback
            error_log("Withdrawal status verified");
        } else {
            error_log("Warning: Callback data verification failed!");
        }

        break;

    case '/callbacks/swaps':
        // Handle swap callbacks
        $code = $data['code'] ?? '';
        $status = $data['status'] ?? '';
        $customId = $data['custom_id'] ?? '';

        error_log("Swap callback received: $code ($customId) - Status: $status");

        // Verify the data by making an API request
        $verifiedData = verifyData('/swap', $code);
        if ($verifiedData && $verifiedData['status'] === $status) {
            // Process the callback
            error_log("Swap status verified");
        } else {
            error_log("Warning: Callback data verification failed!");
        }

        break;

    case '/callbacks/transfers':
        // Handle transfer callbacks
        $code = $data['code'] ?? '';
        $status = $data['status'] ?? '';
        $customId = $data['custom_id'] ?? '';

        error_log("Transfer callback received: $code ($customId) - Status: $status");

        // Verify the data by making an API request
        $verifiedData = verifyData('/internal-transfer', $code);
        if ($verifiedData && $verifiedData['status'] === $status) {
            // Process the callback
            error_log("Transfer status verified");
        } else {
            error_log("Warning: Callback data verification failed!");
        }

        break;

    case '/callbacks/orders':
        // Handle order callbacks
        $code = $data['code'] ?? '';
        $status = $data['status'] ?? '';
        $customId = $data['custom_id'] ?? '';

        error_log("Order callback received: $code ($customId) - Status: $status");

        // Verify the data by making an API request
        $verifiedData = verifyData('/limit-order', $code);
        if ($verifiedData && $verifiedData['status'] === $status) {
            // Process the callback
            error_log("Order status verified");
        } else {
            error_log("Warning: Callback data verification failed!");
        }

        break;

    case '/callbacks/aml':
        // Handle AML check callbacks
        $code = $data['code'] ?? '';
        $status = $data['status'] ?? '';
        $customId = $data['custom_id'] ?? '';

        error_log("AML check callback received: $code ($customId) - Status: $status");

        // Verify the data by making an API request
        $verifiedData = verifyData('/aml/check', $code);
        if ($verifiedData && $verifiedData['status'] === $status) {
            // Process the callback
            error_log("AML check status verified");
        } else {
            error_log("Warning: Callback data verification failed!");
        }

        break;

    default:
        http_response_code(404);
        echo json_encode(['error' => 'Unknown endpoint']);
        exit;
}

// Return a success response
http_response_code(200);
echo json_encode(['success' => true]);