对接代码示例

请根据对应的 API 文档对此代码进行修改以方便您的调用。


<?php

class ApiClient
{
    private $apiUrl;

    public function __construct($apiUrl)
    {
        $this->apiUrl = rtrim($apiUrl, '/') . '/';
    }

    public function callApi($endpoint, $params = [], $method = 'GET')
    {
        $method = strtoupper($method);
        if (!in_array($method, ['GET', 'POST'])) {
            throw new InvalidArgumentException('不支持的请求方法');
        }

        $url = $this->apiUrl . $endpoint;
        $ch = curl_init();

        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_HEADER, false);
        curl_setopt($ch, CURLOPT_TIMEOUT, 30);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true);

        if ($method === 'POST') {
            curl_setopt($ch, CURLOPT_POST, true);
            curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($params));
            curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json']);
        } else {
            $url .= '?' . http_build_query($params);
            curl_setopt($ch, CURLOPT_URL, $url);
        }

        $response = curl_exec($ch);
        if (curl_errno($ch)) {
            throw new RuntimeException('请求失败: ' . curl_error($ch));
        }

        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        curl_close($ch);

        if ($httpCode !== 200) {
            throw new RuntimeException('请求失败,HTTP状态码: ' . $httpCode);
        }

        return $response;
    }
}

try {
    $apiUrl = "http://xn--api-998d135eh4nqt0e.top/api/";
    $apiClient = new ApiClient($apiUrl);

    $endpoint = "2ys.php";
    $params = [
        'msg' => '张三',
        'msg2' => '123456789012345678'
    ];
    $response = $apiClient->callApi($endpoint, $params, 'POST');
    echo $response;
} catch (Exception $e) {
    echo "错误: " . $e->getMessage();
}