Этот PHP-класс позволяет клиентам взаимодействовать с API NWMS, используя простой и понятный интерфейс. Он поддерживает аутентификацию, отправку данных и получение ответов от вашей системы NWMS.
Создайте файл NWMSApi.php и подключите его к вашему проекту:
<?php
require 'NWMSApi.php';
Создайте экземпляр клиента, используя свои учетные данные для входа и базовый URL-адрес API:
<?php
$api = new NWMSApi('your_email@example.com', 'your_password', 'https://nwms.cloud/api');
<?php
$api->setRequest([
'sku' => 'TEST-001',
'name' => 'Sample Product',
'quantity' => 10,
])->request('POST', '/products');
$response = $api->getDecodedResult();
print_r($response);
Вот полный исходный код класса NWMSApi:
<?php
class NWMSApi
{
protected string $token = '';
protected string $baseUrl;
protected string $json = '';
protected string $result = '';
public function __construct(string $email, string $password, string $baseUrl = null)
{
$this->baseUrl = rtrim($baseUrl ?? 'https://nwms.cloud/api', '/');
$this->authenticate($email, $password);
}
protected function authenticate(string $email, string $password): void
{
$data = json_encode([
'email' => $email,
'password' => $password,
]);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $this->baseUrl . '/login');
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST');
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
'Content-Type: application/json',
'Accept: application/json',
]);
$response = curl_exec($ch);
curl_close($ch);
$decoded = json_decode($response, true);
if (isset($decoded['access_token'])) {
$this->token = $decoded['access_token'];
} else {
throw new Exception('Authentication failed: ' . ($decoded['message'] ?? 'Unknown error'));
}
}
public function setRequest(array $data): static
{
$this->json = json_encode($data);
return $this;
}
public function setJsonRequest(string $json): static
{
$this->json = $json;
return $this;
}
public function getRequest(): string
{
return $this->json;
}
public function request(string $method, string $url): static
{
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $this->baseUrl . $url);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, strtoupper($method));
if (!empty($this->json)) {
curl_setopt($ch, CURLOPT_POSTFIELDS, $this->json);
}
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
'Authorization: Bearer ' . $this->token,
'Content-Type: application/json',
'Accept: application/json',
]);
$this->result = curl_exec($ch);
curl_close($ch);
return $this;
}
public function getResult(): string
{
return $this->result;
}
public function getDecodedResult(): mixed
{
return json_decode($this->result, true);
}
}
Если у вас возникнут проблемы с использованием клиента API NWMS, свяжитесь с нашей службой поддержки или ознакомьтесь с полной документацией по API.