348 linhas
13 KiB
PHP
348 linhas
13 KiB
PHP
<?php
|
|
/**
|
|
* Client of the public API (v1) for the domain module.
|
|
* Only uses the documented routes, with the reseller's key (Bearer).
|
|
* The key and the transfer codes never go to the logs.
|
|
*/
|
|
|
|
namespace MozoutDomains;
|
|
|
|
if (!defined('WHMCS')) {
|
|
die('This file cannot be accessed directly');
|
|
}
|
|
|
|
require_once __DIR__ . '/I18n.php';
|
|
|
|
class ApiException extends \Exception
|
|
{
|
|
public $httpStatus;
|
|
public $apiCode;
|
|
public $details;
|
|
public $correlationId;
|
|
|
|
public function __construct($message, $httpStatus = 0, $apiCode = '', $details = array(), $correlationId = '')
|
|
{
|
|
parent::__construct($message, (int) $httpStatus);
|
|
$this->httpStatus = (int) $httpStatus;
|
|
$this->apiCode = (string) $apiCode;
|
|
$this->details = is_array($details) ? $details : array();
|
|
$this->correlationId = (string) $correlationId;
|
|
}
|
|
}
|
|
|
|
class Api
|
|
{
|
|
const VERSION = '1.0.1';
|
|
const MODULE = 'mozout_domains';
|
|
|
|
/** Brands: name, English name, API address and panel address (used when there is no brand.php). */
|
|
public static function brands()
|
|
{
|
|
return array(
|
|
'mozout' => array('name' => 'MozOut', 'name_en' => 'MozOut', 'api' => 'https://api.mozout.com', 'panel' => 'https://www.my.mozout.com'),
|
|
);
|
|
}
|
|
|
|
/**
|
|
* Fixed brand of a brand edition: brand.php next to the module file returns
|
|
* array('key', 'name', 'name_en', 'api', 'panel', 'panel_name'). With it, the
|
|
* module always uses that API address and ignores any other one.
|
|
*/
|
|
public static function fixedBrand()
|
|
{
|
|
static $brand = false;
|
|
if ($brand === false) {
|
|
$brand = null;
|
|
$file = dirname(__DIR__) . '/brand.php';
|
|
if (is_file($file)) {
|
|
$b = include $file;
|
|
$b = is_array($b) ? $b : array();
|
|
$brand = array();
|
|
foreach (array('key', 'name', 'name_en', 'api', 'panel', 'panel_name') as $k) {
|
|
$brand[$k] = isset($b[$k]) ? trim((string) $b[$k]) : '';
|
|
}
|
|
if ($brand['name_en'] === '') {
|
|
$brand['name_en'] = $brand['name'];
|
|
}
|
|
}
|
|
}
|
|
return $brand;
|
|
}
|
|
|
|
/** Brand name for the texts: the fixed brand in 'pt' or 'en', or the neutral name. */
|
|
public static function brandName($lang)
|
|
{
|
|
$b = self::fixedBrand();
|
|
if ($b && $b['name'] !== '') {
|
|
return $lang === 'pt' ? $b['name'] : $b['name_en'];
|
|
}
|
|
return I18n::t($lang, 'brand_neutral');
|
|
}
|
|
|
|
private $base;
|
|
private $key;
|
|
private $lang;
|
|
private $mode;
|
|
private $secrets = array();
|
|
private $hideResponse = false;
|
|
|
|
public function __construct($base, $key, $lang = 'en', $mode = '')
|
|
{
|
|
$this->base = rtrim((string) $base, '/');
|
|
$this->key = trim((string) $key);
|
|
$this->lang = $lang === 'pt' ? 'pt' : 'en';
|
|
$this->mode = in_array($mode, array('sandbox', 'production'), true) ? $mode : '';
|
|
if ($this->key !== '') {
|
|
$this->secrets[] = $this->key;
|
|
}
|
|
}
|
|
|
|
/** Creates the client from the registrar settings in WHMCS. */
|
|
public static function fromParams(array $params)
|
|
{
|
|
$lang = self::langFromParams($params);
|
|
$brands = self::brands();
|
|
$brandKey = self::brandKey(isset($params['Brand']) ? $params['Brand'] : '');
|
|
$base = isset($brands[$brandKey]) ? $brands[$brandKey]['api'] : '';
|
|
$custom = trim(isset($params['ApiUrl']) ? (string) $params['ApiUrl'] : '');
|
|
if ($custom !== '') {
|
|
$base = $custom;
|
|
}
|
|
$fixed = self::fixedBrand();
|
|
if ($fixed) {
|
|
$base = $fixed['api']; /* brand edition: the Brand and API address settings are ignored */
|
|
}
|
|
if (!preg_match('~^https://[a-z0-9.-]+(:\d+)?/?$~i', $base)) {
|
|
throw new ApiException(self::t($lang, 'bad_url'));
|
|
}
|
|
$key = isset($params['ApiKey']) ? (string) $params['ApiKey'] : '';
|
|
if (trim($key) === '') {
|
|
throw new ApiException(self::t($lang, 'no_key'));
|
|
}
|
|
$mode = '';
|
|
if (isset($params['ExpectedMode'])) {
|
|
if (stripos($params['ExpectedMode'], 'sandbox') === 0) { $mode = 'sandbox'; }
|
|
if (stripos($params['ExpectedMode'], 'produ') === 0) { $mode = 'production'; }
|
|
}
|
|
return new self($base, $key, $lang, $mode);
|
|
}
|
|
|
|
/** Accepts the brand code or the brand name saved by version 1.0.0. */
|
|
public static function brandKey($label)
|
|
{
|
|
foreach (self::brands() as $k => $b) {
|
|
if ($label === $k || $label === $b['name']) {
|
|
return $k;
|
|
}
|
|
}
|
|
return 'mozout';
|
|
}
|
|
|
|
/** Message language: the module setting, or the admin/client language when it is "auto". */
|
|
public static function langFromParams(array $params)
|
|
{
|
|
return I18n::setting(isset($params['Language']) ? $params['Language'] : '', $params);
|
|
}
|
|
|
|
public static function panelUrl(array $params)
|
|
{
|
|
$fixed = self::fixedBrand();
|
|
if ($fixed) {
|
|
return $fixed['panel'];
|
|
}
|
|
$b = self::brands();
|
|
$k = self::brandKey(isset($params['Brand']) ? $params['Brand'] : '');
|
|
return $b[$k]['panel'];
|
|
}
|
|
|
|
/** Values that must never appear in the logs (EPP codes, passwords). */
|
|
public function addSecret($value)
|
|
{
|
|
$value = (string) $value;
|
|
if ($value !== '') {
|
|
$this->secrets[] = $value;
|
|
}
|
|
}
|
|
|
|
/** The next answer carries a secret (password, panel login): it does not go to the log. */
|
|
public function hideNextResponse()
|
|
{
|
|
$this->hideResponse = true;
|
|
return $this;
|
|
}
|
|
|
|
public function lang()
|
|
{
|
|
return $this->lang;
|
|
}
|
|
|
|
/** Stable idempotency key for the same operation with the same body. */
|
|
public static function idempotencyKey($operation, $ref, array $body)
|
|
{
|
|
return 'whmcs-' . self::MODULE . '-' . substr(hash('sha256', $operation . '|' . $ref . '|' . json_encode($body)), 0, 48);
|
|
}
|
|
|
|
public function get($path, array $query = array(), $action = '')
|
|
{
|
|
return $this->request('GET', $path, $query, null, '', $action);
|
|
}
|
|
|
|
public function post($path, array $body, $idempotencyKey = '', $action = '')
|
|
{
|
|
return $this->request('POST', $path, array(), $body, $idempotencyKey, $action);
|
|
}
|
|
|
|
public function put($path, array $body, $action = '')
|
|
{
|
|
return $this->request('PUT', $path, array(), $body, '', $action);
|
|
}
|
|
|
|
public function request($method, $path, array $query = array(), $body = null, $idempotencyKey = '', $action = '')
|
|
{
|
|
$url = $this->base . $path . ($query ? '?' . http_build_query($query) : '');
|
|
$headers = array(
|
|
'Authorization: Bearer ' . $this->key,
|
|
'Accept: application/json',
|
|
'Accept-Language: ' . $this->lang,
|
|
'User-Agent: WHMCS-' . self::MODULE . '/' . self::VERSION,
|
|
);
|
|
if ($this->mode !== '') {
|
|
$headers[] = 'X-API-Mode: ' . $this->mode;
|
|
}
|
|
if ($idempotencyKey !== '') {
|
|
$headers[] = 'Idempotency-Key: ' . $idempotencyKey;
|
|
}
|
|
$payload = null;
|
|
if ($body !== null) {
|
|
$payload = json_encode($body);
|
|
$headers[] = 'Content-Type: application/json';
|
|
}
|
|
|
|
$ch = curl_init($url);
|
|
curl_setopt_array($ch, array(
|
|
CURLOPT_CUSTOMREQUEST => $method,
|
|
CURLOPT_RETURNTRANSFER => true,
|
|
CURLOPT_HEADER => true,
|
|
CURLOPT_HTTPHEADER => $headers,
|
|
CURLOPT_CONNECTTIMEOUT => 15,
|
|
CURLOPT_TIMEOUT => 60,
|
|
CURLOPT_SSL_VERIFYPEER => true,
|
|
CURLOPT_SSL_VERIFYHOST => 2,
|
|
CURLOPT_PROTOCOLS => CURLPROTO_HTTPS,
|
|
));
|
|
if ($payload !== null) {
|
|
curl_setopt($ch, CURLOPT_POSTFIELDS, $payload);
|
|
}
|
|
$raw = curl_exec($ch);
|
|
$errno = curl_errno($ch);
|
|
$status = (int) curl_getinfo($ch, CURLINFO_HTTP_CODE);
|
|
$hsize = (int) curl_getinfo($ch, CURLINFO_HEADER_SIZE);
|
|
curl_close($ch);
|
|
|
|
$respHeaders = '';
|
|
$respBody = '';
|
|
if ($raw !== false) {
|
|
$respHeaders = substr($raw, 0, $hsize);
|
|
$respBody = (string) substr($raw, $hsize);
|
|
}
|
|
$json = json_decode($respBody, true);
|
|
|
|
$hiddenAll = $this->hideResponse;
|
|
$hidden = $hiddenAll && $status >= 200 && $status < 300;
|
|
$this->hideResponse = false;
|
|
$this->log($action !== '' ? $action : $method . ' ' . $path, $method . ' ' . $url . ($payload !== null ? "\n" . ($hiddenAll ? '[hidden]' : $payload) : ''), $status . "\n" . ($hidden ? '[hidden]' : $respBody), $hidden ? '' : $json);
|
|
|
|
if ($raw === false || $errno) {
|
|
throw new ApiException(self::t($this->lang, 'network'), 0, 'network_error');
|
|
}
|
|
if ($status >= 200 && $status < 300) {
|
|
if (!is_array($json)) {
|
|
throw new ApiException(self::t($this->lang, 'bad_answer'), $status, 'bad_answer');
|
|
}
|
|
$json['_simulated'] = (stripos($respHeaders, "x-api-simulated: true") !== false);
|
|
$json['_replayed'] = (stripos($respHeaders, "idempotent-replayed: true") !== false);
|
|
if ($json['_simulated'] && isset($json['data']) && is_array($json['data']) && function_exists('logActivity')) {
|
|
$d = $json['data'];
|
|
if ((isset($d['credit_sufficient']) && $d['credit_sufficient'] === false) || (isset($d['within_spending_limit']) && $d['within_spending_limit'] === false)) {
|
|
logActivity(self::MODULE . ': ' . self::t($this->lang, 'sandbox_refused') . ' (' . $method . ' ' . $path . ')');
|
|
}
|
|
}
|
|
$json['_status'] = $status;
|
|
return $json;
|
|
}
|
|
$err = (is_array($json) && isset($json['error']) && is_array($json['error'])) ? $json['error'] : array();
|
|
$code = isset($err['code']) ? (string) $err['code'] : '';
|
|
$details = isset($err['details']) && is_array($err['details']) ? $err['details'] : array();
|
|
if ($status === 429 && !isset($details['retry_after']) && preg_match('~^retry-after:\s*(\d+)~mi', $respHeaders, $m)) {
|
|
$details['retry_after'] = (int) $m[1];
|
|
}
|
|
$msg = isset($err['message']) ? (string) $err['message'] : '';
|
|
throw new ApiException(
|
|
$this->friendly($status, $code, $msg, $details),
|
|
$status,
|
|
$code,
|
|
$details,
|
|
isset($err['correlation_id']) ? (string) $err['correlation_id'] : ''
|
|
);
|
|
}
|
|
|
|
/** Clear messages for the errors the reseller has to solve. */
|
|
private function friendly($status, $code, $msg, array $details)
|
|
{
|
|
$l = $this->lang;
|
|
if ($status === 401) {
|
|
return self::t($l, 'unauthorized');
|
|
}
|
|
if ($status === 402 || $code === 'insufficient_credit') {
|
|
$s = self::t($l, 'no_credit');
|
|
if (isset($details['credit_missing'])) {
|
|
$s .= ' ' . sprintf(self::t($l, 'missing'), $details['credit_missing'] . (isset($details['currency']) ? ' ' . $details['currency'] : ''));
|
|
}
|
|
if (!empty($details['add_funds_url'])) {
|
|
$s .= ' ' . $details['add_funds_url'];
|
|
}
|
|
return $s;
|
|
}
|
|
if ($status === 429) {
|
|
$s = self::t($l, 'rate_limited');
|
|
if (isset($details['retry_after'])) {
|
|
$s .= ' ' . sprintf(self::t($l, 'retry_in'), (int) $details['retry_after']);
|
|
}
|
|
return $s;
|
|
}
|
|
if ($code === 'insufficient_scope') {
|
|
return self::t($l, 'scope') . ($msg !== '' ? ' (' . $msg . ')' : '');
|
|
}
|
|
if ($code === 'spending_limit_exceeded') {
|
|
return self::t($l, 'spending');
|
|
}
|
|
if ($code === 'ip_not_allowed') {
|
|
return self::t($l, 'ip');
|
|
}
|
|
$s = $msg !== '' ? $msg : sprintf(self::t($l, 'http'), $status);
|
|
if (!empty($details['portal_url'])) {
|
|
$s .= ' ' . $details['portal_url'];
|
|
}
|
|
return $s;
|
|
}
|
|
|
|
private function log($action, $request, $response, $processed)
|
|
{
|
|
if (!function_exists('logModuleCall')) {
|
|
return;
|
|
}
|
|
$replace = array();
|
|
foreach ($this->secrets as $s) {
|
|
$replace[] = $s;
|
|
$replace[] = json_encode($s);
|
|
$replace[] = trim(json_encode($s), '"');
|
|
}
|
|
logModuleCall(self::MODULE, $action, $request, $response, is_array($processed) ? $processed : '', array_values(array_unique($replace)));
|
|
}
|
|
|
|
/** Client messages, from lang/english.php and lang/portuguese.php (keys api_*). */
|
|
public static function t($lang, $k)
|
|
{
|
|
return I18n::t($lang === 'pt' ? 'pt' : 'en', 'api_' . $k);
|
|
}
|
|
}
|