Files
dev-chiefworks f76abffdcd first commit
2022-05-31 16:21:53 -04:00

118 lines
3.8 KiB
PHP

<?php
class Api
{
private static $instance;
private static $httpAuthToken;
private static $encryptionAlg;
private static $encryptionKey;
private static $encryptionIV;
private static $baseURL;
public function __construct()
{
}
public static function initConfig()
{
global $savvyext;
self::$httpAuthToken = $savvyext->cfgReadChar('system.oauth2_token');
self::$encryptionAlg = $savvyext->cfgReadChar('encryption.algorithm');
self::$encryptionKey = $savvyext->cfgReadChar('encryption.key');
self::$encryptionIV = $savvyext->cfgReadChar('encryption.iv');
self::$baseURL = $savvyext->cfgReadChar('system.api_url');
}
public static function getInstance()
{
if (null === static::$instance) {
static::$instance = new static;
self::initConfig();
return static::$instance;
}
return static::$instance;
}
public static function postData($endpoint, $payload)
{
self::getInstance();
$encrypted_payload = bin2hex(
openssl_encrypt(
$payload,
self::$encryptionAlg,
self::$encryptionKey,
OPENSSL_RAW_DATA,
self::$encryptionIV
));
$postdata = "{\"encrypted_payload\": \"${encrypted_payload}\"}";
$url = self::$baseURL . $endpoint;
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $postdata);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_VERBOSE, false);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json',
'Content-Length: ' . strlen($postdata),
'Authorization: Server-Token ' . self::$httpAuthToken,
"client_id: BATCH"
)
);
$body = curl_exec($ch);
$result = json_decode($body, true);
$decrypted = openssl_decrypt(
hex2bin(
$result['payload']
),
self::$encryptionAlg,
self::$encryptionKey,
OPENSSL_RAW_DATA,
self::$encryptionIV
);
$payload = json_decode($decrypted, true);
return $payload;
}
public static function getData($endpoint)
{
self::getInstance();
if ($endpoint != "") { // minimal sanity
sleep(1);
$url = self::$baseURL . $endpoint;
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "GET");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_VERBOSE, false);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json',
'Authorization: Server-Token ' . self::$httpAuthToken,
"client_id: BATCH"
)
);
$body = curl_exec($ch);
$result = json_decode($body, true);
$decrypted = openssl_decrypt(
hex2bin(
$result['payload']
),
self::$encryptionAlg,
self::$encryptionKey,
OPENSSL_RAW_DATA,
self::$encryptionIV
);
$payload = json_decode($decrypted, true);
return [$payload, $decrypted, $result, $body];
}
return [null, null, null, null];
}
}