PHP

<?php
class PureServers {
    private $email;
    private $password;
    private $session;

    public function __construct($email, $password) {
        $this->email = $email;
        $this->password = $password;
        $this->session = null;
    }

    private function parseHeaders($curl, $header) {
        $len = strlen($header);
        if (preg_match('/^session:\s*(.*)$/i', $header, $match)) {
            $this->session = trim($match[1]);
        }
        return $len;
    }

    public function request($url, $method, $data = [], $secured = false) {
        $curl = curl_init();
        $headers = [];

        if ($secured && $this->session) {
            $headers[] = "Session: {$this->session}";
        }

        if ($method === 'POST') {
            $headers[] = 'Content-Type: application/json';
        }

        $options = [
            CURLOPT_URL => "https://cp.pureservers.org/api/" . $url,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_CUSTOMREQUEST => strtoupper($method),
            CURLOPT_HTTPHEADER => $headers,
            CURLOPT_HEADERFUNCTION => [$this, 'parseHeaders'],
        ];

        if ($method === 'POST' && !empty($data)) {
            $options[CURLOPT_POSTFIELDS] = json_encode($data);
        }

        curl_setopt_array($curl, $options);
        $response = curl_exec($curl);
        $err = curl_error($curl);

        curl_close($curl);

        if ($err) {
            return ['data' => $err, 'success' => false];
        } else {
            return ['data' => json_decode($response, true), 'success' => true]; // Успех на основе HTTP кода здесь упрощён
        }
    }

    public function login() {
        $res = $this->request('auth/login', 'POST', ['email' => $this->email, 'password' => $this->password], false);
        if ($res['success']) {
            return true;
        }

        return $res;
    }
}

Пример использования с получением списка серверов:

<?php
$email = "<email>";
$password = "<password>";
$api = new PureServers($email, $password);

$login = $api->login();
if ($login === true) {
    echo json_encode($api->request('servers/list', 'GET', [], true));
} else {
    echo $login;
}

Last updated