一、环境要求与配置
1. 系统要求
- PHP ≥ 7.4
- 扩展:cURL、JSON、OpenSSL
- Composer(推荐)
2. 安装依赖
bash
composer require guzzlehttp/guzzle
3. 基础配置类
php
<?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 客户端实现
1. 基础客户端类
php
<?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 => '服务器内部错误',
];
return [
'code' => $statusCode,
'message' => $errorMap[$statusCode] ?? '未知错误',
'error' => $exception->getMessage()
];
}
}
?>
2. 股票数据接口实现
php
<?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线数据
*/
public function getKlineData($pid, $interval = 'PT15M') {
$params = [
'pid' => $pid,
'interval' => $interval
];
return $this->makeRequest('GET', '/stock/kline', $params);
}
/**
* 获取印尼指数数据
*/
public function getIndices() {
$params = [
'countryId' => $this->config->getCountryId()
];
return $this->makeRequest('GET', '/stock/indices', $params);
}
}
?>
3. 公司信息服务
php
<?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 实时数据对接
1. WebSocket 客户端
php
<?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;
// 连接成功回调
$conn->on('message', function(MessageInterface $msg) {
$this->handleMessage($msg);
});
$conn->on('close', function($code = null, $reason = null) {
$this->handleClose($code, $reason);
});
// 发送心跳包
$this->startHeartbeat();
},
function(\Exception $e) {
echo "连接失败: {$e->getMessage()}\n";
}
);
}
private function handleMessage(MessageInterface $msg) {
$data = json_decode($msg->__toString(), true);
if (isset($data['pid'])) {
// 处理实时行情数据
$this->processMarketData($data);
}
}
private function processMarketData($data) {
echo "收到行情数据: PID={$data['pid']}, 价格={$data['last_numeric']}\n";
// 这里可以添加业务逻辑处理
// 例如:存入数据库、触发交易策略等
}
private function startHeartbeat() {
// 每30秒发送心跳
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
<?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 "最新价: {$stock['last']} \n";
echo "涨跌幅: {$stock['chgPct']}% \n\n";
}
}
// 获取K线数据
$klineData = $stockService->getKlineData(7310, 'PT1H');
if ($klineData['code'] == 200) {
foreach ($klineData['data'] as $kline) {
echo "时间: " . date('Y-m-d H:i:s', $kline['time']/1000) . "\n";
echo "开盘: {$kline['open']}, 收盘: {$kline['close']}\n";
}
}
?>
2. 实时数据订阅示例
php
<?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);
// 保持脚本运行
while (true) {
sleep(1);
}
?>
五、错误处理与日志
1. 日志记录类
php
<?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. 增强的错误处理
php
// 在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;
}
}
六、性能优化建议
1. 缓存机制
php
<?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. 目录结构
arduino
project/
├── config/
│ └── StockTVConfig.php
├── src/
│ ├── StockTVClient.php
│ ├── StockDataService.php
│ ├── CompanyService.php
│ ├── WebSocketClient.php
│ ├── Logger.php
│ └── CacheService.php
├── logs/
├── vendor/
├── composer.json
└── index.php
2. 环境变量配置
创建 .env
文件:
ini
STOCKTV_API_KEY=your_api_key_here
STOCKTV_COUNTRY_ID=42
REDIS_HOST=127.0.0.1
REDIS_PORT=6379
通过本PHP对接方案,您可以快速集成StockTV的印尼金融市场数据到您的应用中。建议在生产环境中添加监控和告警机制,确保数据服务的稳定性。