印度尼西亞數(shù)據(jù)源 PHP 對接文檔
一、環(huán)境要求與配置
1. 系統(tǒng)要求
- PHP ≥ 7.4
- 擴(kuò)展:cURL、JSON、OpenSSL
- Composer(推薦)
2. 安裝依賴
composer require guzzlehttp/guzzle
3. 基礎(chǔ)配置類
<?php
// config/StockTVConfig.php
class StockTVConfig {
const BASE_URL = 'https://api.stocktv.top';
const WS_URL = 'wss://ws-api.stocktv.top/connect';
private $apiKey;
private $countryId = 42; // 印尼國家ID
public function __construct($apiKey) {
$this->apiKey = $apiKey;
}
public function getApiKey() {
return $this->apiKey;
}
public function getBaseUrl() {
return self::BASE_URL;
}
public function getWsUrl() {
return self::WS_URL;
}
public function getCountryId() {
return $this->countryId;
}
}
?>
二、HTTP API 客戶端實(shí)現(xiàn)
1. 基礎(chǔ)客戶端類
<?php
// src/StockTVClient.php
require_once 'vendor/autoload.php';
use GuzzleHttp\Client;
use GuzzleHttp\Exception\RequestException;
class StockTVClient {
private $client;
private $config;
public function __construct(StockTVConfig $config) {
$this->config = $config;
$this->client = new Client([
'base_uri' => $config->getBaseUrl(),
'timeout' => 30,
'verify' => true,
]);
}
private function makeRequest($method, $endpoint, $params = []) {
try {
// 添加API密鑰
$params['key'] = $this->config->getApiKey();
$response = $this->client->request($method, $endpoint, [
'query' => $params
]);
return json_decode($response->getBody(), true);
} catch (RequestException $e) {
return $this->handleError($e);
}
}
private function handleError($exception) {
$statusCode = $exception->getResponse() ? $exception->getResponse()->getStatusCode() : 500;
$errorMap = [
401 => 'API密鑰無效',
429 => '請求頻率超限',
500 => '服務(wù)器內(nèi)部錯(cuò)誤',
];
return [
'code' => $statusCode,
'message' => $errorMap[$statusCode] ?? '未知錯(cuò)誤',
'error' => $exception->getMessage()
];
}
}
?>
2. 股票數(shù)據(jù)接口實(shí)現(xiàn)
<?php
// src/StockDataService.php
class StockDataService extends StockTVClient {
/**
* 獲取印尼股票列表
*/
public function getStockList($pageSize = 10, $page = 1) {
$params = [
'countryId' => $this->config->getCountryId(),
'pageSize' => $pageSize,
'page' => $page
];
return $this->makeRequest('GET', '/stock/stocks', $params);
}
/**
* 查詢特定股票
*/
public function queryStock($symbol = null, $pid = null) {
$params = [];
if ($symbol) $params['symbol'] = $symbol;
if ($pid) $params['id'] = $pid;
return $this->makeRequest('GET', '/stock/queryStocks', $params);
}
/**
* 獲取股票K線數(shù)據(jù)
*/
public function getKlineData($pid, $interval = 'PT15M') {
$params = [
'pid' => $pid,
'interval' => $interval
];
return $this->makeRequest('GET', '/stock/kline', $params);
}
/**
* 獲取印尼指數(shù)數(shù)據(jù)
*/
public function getIndices() {
$params = [
'countryId' => $this->config->getCountryId()
];
return $this->makeRequest('GET', '/stock/indices', $params);
}
}
?>
3. 公司信息服務(wù)
<?php
// src/CompanyService.php
class CompanyService extends StockTVClient {
/**
* 獲取公司列表
*/
public function getCompanyList($pageSize = 10, $page = 1) {
$params = [
'countryId' => $this->config->getCountryId(),
'pageSize' => $pageSize,
'page' => $page
];
return $this->makeRequest('GET', '/stock/companies', $params);
}
/**
* 通過URL獲取公司詳情
*/
public function getCompanyByUrl($url) {
$params = ['url' => $url];
return $this->makeRequest('GET', '/stock/companyUrl', $params);
}
}
?>
三、WebSocket 實(shí)時(shí)數(shù)據(jù)對接
1. WebSocket 客戶端
<?php
// src/WebSocketClient.php
use Ratchet\Client\WebSocket;
use Ratchet\RFC6455\Messaging\MessageInterface;
class StockTVWebSocketClient {
private $config;
private $connection;
public function __construct(StockTVConfig $config) {
$this->config = $config;
}
public function connect() {
$wsUrl = $this->config->getWsUrl() . '?key=' . $this->config->getApiKey();
\Ratchet\Client\connect($wsUrl)->then(
function(WebSocket $conn) {
$this->connection = $conn;
// 連接成功回調(diào)
$conn->on('message', function(MessageInterface $msg) {
$this->handleMessage($msg);
});
$conn->on('close', function($code = null, $reason = null) {
$this->handleClose($code, $reason);
});
// 發(fā)送心跳包
$this->startHeartbeat();
},
function(\Exception $e) {
echo "連接失敗: {$e->getMessage()}\n";
}
);
}
private function handleMessage(MessageInterface $msg) {
$data = json_decode($msg->__toString(), true);
if (isset($data['pid'])) {
// 處理實(shí)時(shí)行情數(shù)據(jù)
$this->processMarketData($data);
}
}
private function processMarketData($data) {
echo "收到行情數(shù)據(jù): PID={$data['pid']}, 價(jià)格={$data['last_numeric']}\n";
// 這里可以添加業(yè)務(wù)邏輯處理
// 例如:存入數(shù)據(jù)庫、觸發(fā)交易策略等
}
private function startHeartbeat() {
// 每30秒發(fā)送心跳
swoole_timer_tick(30000, function() {
if ($this->connection) {
$this->connection->send(json_encode(['action' => 'ping']));
}
});
}
public function subscribe($pids) {
$message = [
'action' => 'subscribe',
'pids' => $pids
];
if ($this->connection) {
$this->connection->send(json_encode($message));
}
}
}
?>
四、使用示例
1. 初始化配置
<?php
// index.php
require_once 'config/StockTVConfig.php';
require_once 'src/StockTVClient.php';
require_once 'src/StockDataService.php';
require_once 'src/CompanyService.php';
// 初始化配置
$config = new StockTVConfig('您的API_KEY');
$stockService = new StockDataService($config);
$companyService = new CompanyService($config);
// 獲取股票列表
$stocks = $stockService->getStockList(20, 1);
if ($stocks['code'] == 200) {
foreach ($stocks['data']['records'] as $stock) {
echo "股票: {$stock['symbol']} - {$stock['name']} \n";
echo "最新價(jià): {$stock['last']} \n";
echo "漲跌幅: {$stock['chgPct']}% \n\n";
}
}
// 獲取K線數(shù)據(jù)
$klineData = $stockService->getKlineData(7310, 'PT1H');
if ($klineData['code'] == 200) {
foreach ($klineData['data'] as $kline) {
echo "時(shí)間: " . date('Y-m-d H:i:s', $kline['time']/1000) . "\n";
echo "開盤: {$kline['open']}, 收盤: {$kline['close']}\n";
}
}
?>
2. 實(shí)時(shí)數(shù)據(jù)訂閱示例
<?php
// realtime.php
require_once 'src/WebSocketClient.php';
$config = new StockTVConfig('您的API_KEY');
$wsClient = new StockTVWebSocketClient($config);
// 連接WebSocket
$wsClient->connect();
// 訂閱特定股票(需要先獲取PID)
$pidsToSubscribe = [7310, 41602, 50123];
$wsClient->subscribe($pidsToSubscribe);
// 保持腳本運(yùn)行
while (true) {
sleep(1);
}
?>
五、錯(cuò)誤處理與日志
1. 日志記錄類
<?php
// src/Logger.php
class Logger {
const LOG_FILE = 'logs/stocktv.log';
public static function info($message, $context = []) {
self::writeLog('INFO', $message, $context);
}
public static function error($message, $context = []) {
self::writeLog('ERROR', $message, $context);
}
private static function writeLog($level, $message, $context) {
$logEntry = sprintf(
"[%s] %s: %s %s\n",
date('Y-m-d H:i:s'),
$level,
$message,
!empty($context) ? json_encode($context) : ''
);
// 確保日志目錄存在
if (!is_dir('logs')) {
mkdir('logs', 0755, true);
}
file_put_contents(self::LOG_FILE, $logEntry, FILE_APPEND | LOCK_EX);
}
}
?>
2. 增強(qiáng)的錯(cuò)誤處理
// 在StockTVClient中添加日志
private function makeRequest($method, $endpoint, $params = []) {
try {
Logger::info("API請求開始", [
'endpoint' => $endpoint,
'params' => $params
]);
$response = $this->client->request($method, $endpoint, [
'query' => $params
]);
$result = json_decode($response->getBody(), true);
Logger::info("API請求成功", [
'endpoint' => $endpoint,
'code' => $result['code'] ?? null
]);
return $result;
} catch (RequestException $e) {
$errorData = $this->handleError($e);
Logger::error("API請求失敗", $errorData);
return $errorData;
}
}
六、性能優(yōu)化建議
1. 緩存機(jī)制
<?php
// src/CacheService.php
class CacheService {
private $redis;
public function __construct() {
$this->redis = new Redis();
$this->redis->connect('127.0.0.1', 6379);
}
public function getWithCache($key, $callback, $ttl = 300) {
$cached = $this->redis->get($key);
if ($cached !== false) {
return json_decode($cached, true);
}
$result = $callback();
if ($result && $result['code'] == 200) {
$this->redis->setex($key, $ttl, json_encode($result));
}
return $result;
}
}
// 使用示例
$cacheService = new CacheService();
$stocks = $cacheService->getWithCache(
'indonesia_stocks_page_1',
function() use ($stockService) {
return $stockService->getStockList(20, 1);
},
600 // 10分鐘緩存
);
?>
七、部署說明
1. 目錄結(jié)構(gòu)
project/
├── config/
│ └── StockTVConfig.php
├── src/
│ ├── StockTVClient.php
│ ├── StockDataService.php
│ ├── CompanyService.php
│ ├── WebSocketClient.php
│ ├── Logger.php
│ └── CacheService.php
├── logs/
├── vendor/
├── composer.json
└── index.php
2. 環(huán)境變量配置
創(chuàng)建 .env 文件:
STOCKTV_API_KEY=your_api_key_here
STOCKTV_COUNTRY_ID=42
REDIS_HOST=127.0.0.1
REDIS_PORT=6379
通過本PHP對接方案,您可以快速集成StockTV的印尼金融市場數(shù)據(jù)到您的應(yīng)用中。建議在生產(chǎn)環(huán)境中添加監(jiān)控和告警機(jī)制,確保數(shù)據(jù)服務(wù)的穩(wěn)定性。

浙公網(wǎng)安備 33010602011771號