How to Use PHP to Request OKX API for Bitcoin Price and K-Line Data

ยท

Introduction

This guide demonstrates how to use PHP to interact with OKX's API to retrieve Bitcoin price data and K-line information. We'll cover environment setup, request configuration, signature generation, and provide a complete code implementation.

Prerequisites

Development Environment

For this tutorial, we'll use:

Install Guzzle via Composer:

composer require guzzlehttp/guzzle

API Configuration

Required Credentials

You'll need to obtain these from your OKX account:

๐Ÿ‘‰ Create an OKX account if you don't have one.

Request Headers

All private REST requests must include these headers:

Signature Generation

The signature is created by:

  1. Concatenating: timestamp + method + requestPath + body
  2. Hashing with HMAC SHA256 using your Secret Key
  3. Encoding with Base64

Example structure:

$string = $timestamp . "GET" . $url . $body;
$signature = base64_encode(hash_hmac('sha256', $string, $secret_key));

Implementation Code

Configuration Setup

$api_key = "your_api_key";
$secret_key = "your_secret_key";
$passphrase = "your_passphrase";

// Set timezone to UTC
date_default_timezone_set('UTC');
$dateTime = new DateTime();
$timestamp = $dateTime->format('Y-m-d\TH:i:s.u\Z');

$url = "";
$body = "";
$string = $timestamp . "GET" . $url . $body;
$signature = base64_encode(hash_hmac('sha256', $string, $secret_key));

$headers = [
    "OK-ACCESS-KEY" => $api_key,
    "OK-ACCESS-SIGN" => $signature,
    "OK-ACCESS-TIMESTAMP" => $timestamp,
    "OK-ACCESS-PASSPHRASE" => $passphrase
];

Proxy Configuration

$this->client = new Client([
    "proxy" => "http://127.0.0.1:23457",
    "headers" => $headers
]);

Complete Code Structure

Response Handler (res.php)

class Res {
    function success($msg, $data = null) {
        return json([
            "code" => 200,
            "msg" => $msg,
            "data" => $data
        ]);
    }
    
    function error($msg) {
        return json([
            "code" => 400,
            "msg" => $msg,
            "data" => null
        ]);
    }
}

OKX Controller (okx.php)

class Okx {
    private $result;
    private $client;

    public function __construct() {
        $api_key = "your_api_key";
        $secret_key = "your_secret_key";
        $passphrase = "your_passphrase";

        date_default_timezone_set('UTC');
        $dateTime = new DateTime();
        $timestamp = $dateTime->format('Y-m-d\TH:i:s.u\Z');

        $url = "";
        $body = "";
        $string = $timestamp . "GET" . $url . $body;
        $signature = base64_encode(hash_hmac('sha256', $string, $secret_key));

        $headers = [
            "OK-ACCESS-KEY" => $api_key,
            "OK-ACCESS-SIGN" => $signature,
            "OK-ACCESS-TIMESTAMP" => $timestamp,
            "OK-ACCESS-PASSPHRASE" => $passphrase
        ];

        $this->result = new Res();
        $this->client = new Client([
            "proxy" => "http://127.0.0.1:23457",
            "verify" => false,
            "headers" => $headers
        ]);
    }

    public function getPrice($type) {
        $style = strtoupper($type);
        $url = "https://www.okx.com/join/BLOCKSTARapi/v5/public/mark-price?instType=SWAP&instId={$style}-USDT-SWAP";
        $res = $this->client->get($url)->getBody()->getContents();
        return $this->result->success("Data retrieved successfully", json_decode($res));
    }
}

Route Configuration

Route::group("/okx", function(){
    Route::get("/price/:type", "okx/getPrice");
});

FAQ Section

How do I get my OKX API credentials?

๐Ÿ‘‰ Register for an OKX account and generate API keys in the account settings.

Why do I need to set the timezone to UTC?

OKX API requires timestamps in UTC format for authentication. This ensures time synchronization between your server and OKX's systems.

What if I'm not using ThinkPHP?

The core principles remain the same. You'll just need to adapt the framework-specific code (like routing) to your preferred framework.

How can I test the API without a proxy?

While possible, using a proxy is recommended for reliable connections to OKX's international servers.

What other data can I retrieve?

The OKX API offers various endpoints for:

Explore the full capabilities in the OKX API documentation.