以下是使用 PHP 对接 StockTV API 的项目实现。我们将使用 cURL
进行 HTTP 请求,并使用 Ratchet
处理 WebSocket 连接。
项目结构
stocktv-api-php/
│
├── src/
│ ├── StockAPI.php
│ ├── ForexAPI.php
│ ├── FuturesAPI.php
│ ├── CryptoAPI.php
│ └── ApiClient.php
│
├── tests/
│ ├── StockAPITest.php
│ ├── ForexAPITest.php
│ ├── FuturesAPITest.php
│ └── CryptoAPITest.php
│
├── composer.json
├── README.md
└── index.php
1. 安装依赖
在项目根目录下创建 composer.json
文件,并添加以下内容:
json
{
"name": "yourname/stocktv-api-php",
"description": "PHP client for StockTV API",
"require": {
"php": ">=7.4",
"ext-curl": "*",
"ext-json": "*",
"ratchet/pawl": "^0.4.1"
},
"autoload": {
"psr-4": {
"StockTV\\": "src/"
}
},
"require-dev": {
"phpunit/phpunit": "^9.5"
}
}
运行以下命令安装依赖:
bash
composer install
2. 创建基础工具类
在 src/ApiClient.php
中,创建一个基础工具类来处理 API 请求:
php
<?php
namespace StockTV;
class ApiClient
{
private $apiKey;
private $baseUrl = "https://api.stocktv.top";
public function __construct(string $apiKey)
{
$this->apiKey = $apiKey;
}
protected function get(string $endpoint, array $params = []): array
{
$url = $this->baseUrl . "/" . $endpoint . "?key=" . $this->apiKey;
if (!empty($params)) {
$url .= "&" . http_build_query($params);
}
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
curl_close($ch);
return json_decode($response, true);
}
}
3. 实现股票 API
在 src/StockAPI.php
中,实现股票相关的 API:
php
<?php
namespace StockTV;
class StockAPI extends ApiClient
{
public function getStockList(int $countryId, int $pageSize = 10, int $page = 1): array
{
return $this->get("stock/stocks", [
"countryId" => $countryId,
"pageSize" => $pageSize,
"page" => $page
]);
}
public function getIndices(int $countryId, ?string $flag = null): array
{
$params = ["countryId" => $countryId];
if ($flag) {
$params["flag"] = $flag;
}
return $this->get("stock/indices", $params);
}
public function getKline(int $pid, string $interval): array
{
return $this->get("stock/kline", [
"pid" => $pid,
"interval" => $interval
]);
}
}
4. 实现外汇 API
在 src/ForexAPI.php
中,实现外汇相关的 API:
php
<?php
namespace StockTV;
class ForexAPI extends ApiClient
{
public function getCurrencyList(): array
{
return $this->get("market/currencyList");
}
public function getRealTimeRates(?string $countryType = null): array
{
$params = [];
if ($countryType) {
$params["countryType"] = $countryType;
}
return $this->get("market/currency", $params);
}
}
5. 实现期货 API
在 src/FuturesAPI.php
中,实现期货相关的 API:
php
<?php
namespace StockTV;
class FuturesAPI extends ApiClient
{
public function getFuturesList(): array
{
return $this->get("futures/list");
}
public function getFuturesMarket(string $symbol): array
{
return $this->get("futures/querySymbol", [
"symbol" => $symbol
]);
}
}
6. 实现加密货币 API
在 src/CryptoAPI.php
中,实现加密货币相关的 API:
php
<?php
namespace StockTV;
class CryptoAPI extends ApiClient
{
public function getCoinInfo(): array
{
return $this->get("crypto/getCoinInfo");
}
public function getTickerPrice(string $symbols): array
{
return $this->get("crypto/tickerPrice", [
"symbols" => $symbols
]);
}
}
7. WebSocket 支持
使用 Ratchet
库实现 WebSocket 连接:
php
<?php
require 'vendor/autoload.php';
use Ratchet\Client\WebSocket;
use Ratchet\Client\Connector;
use React\EventLoop\Factory;
$loop = Factory::create();
$connector = new Connector($loop);
$apiKey = "your_api_key_here";
$wsUrl = "wss://ws-api.stocktv.top/connect?key=" . $apiKey;
$connector($wsUrl)->then(function (WebSocket $conn) {
$conn->on('message', function ($msg) use ($conn) {
echo "Received: {$msg}\n";
});
$conn->on('close', function ($code = null, $reason = null) {
echo "Connection closed ({$code} - {$reason})\n";
});
}, function (\Exception $e) use ($loop) {
echo "Could not connect: {$e->getMessage()}\n";
$loop->stop();
});
$loop->run();
8. 测试代码
在 tests/StockAPITest.php
中,编写测试代码:
php
<?php
use PHPUnit\Framework\TestCase;
use StockTV\StockAPI;
class StockAPITest extends TestCase
{
private $stockAPI;
protected function setUp(): void
{
$this->stockAPI = new StockAPI("your_api_key_here");
}
public function testGetStockList(): void
{
$response = $this->stockAPI->getStockList(14, 10, 1);
$this->assertArrayHasKey("data", $response);
}
}
运行测试:
bash
./vendor/bin/phpunit tests
9. 使用示例
在 index.php
中,编写示例代码:
php
<?php
require 'vendor/autoload.php';
use StockTV\StockAPI;
$apiKey = "your_api_key_here";
$stockAPI = new StockAPI($apiKey);
try {
$stockList = $stockAPI->getStockList(14, 10, 1);
print_r($stockList);
} catch (Exception $e) {
echo "Error: " . $e->getMessage();
}
10. README.md
在项目根目录下创建 README.md
文件:
markdown
# StockTV API PHP Client
A PHP client for accessing StockTV's global financial data APIs.
## Installation
```bash
composer install
Usage
php
use StockTV\StockAPI;
$apiKey = "your_api_key_here";
$stockAPI = new StockAPI($apiKey);
$stockList = $stockAPI->getStockList(14, 10, 1);
print_r($stockList);
总结
这个 PHP 项目提供了对 StockTV API 的完整支持,包括股票、外汇、期货和加密货币数据。通过模块化设计和清晰的代码结构,开发者可以轻松扩展和集成到自己的项目中。