176 lines
8.5 KiB
PHP
176 lines
8.5 KiB
PHP
<?php
|
|
if (!defined('ABSPATH')) {
|
|
exit;
|
|
}
|
|
|
|
/**
|
|
* Client of the public API. Only documented operations, with the customer's key in the Authorization header.
|
|
* The key is never written to logs, notes or error messages.
|
|
*/
|
|
class MOZOUT_RESELLER_Api
|
|
{
|
|
/**
|
|
* @param string $method GET, POST, PUT, PATCH or DELETE.
|
|
* @param string $path For example "/v1/email/messages".
|
|
* @param array|null $body Sent as JSON.
|
|
* @param array $opts idempotency_key (string|true), query (array), timeout (int), lang ("pt"|"en"),
|
|
* key (a key to check before it is saved; default: the saved key),
|
|
* public (true: sent without a key, for the operations that do not need one).
|
|
* @return array|WP_Error array('status' => int, 'data' => mixed, 'meta' => array, 'headers' => array)
|
|
*/
|
|
public static function request($method, $path, $body = null, array $opts = array())
|
|
{
|
|
$public = !empty($opts['public']);
|
|
$key = isset($opts['key']) ? trim((string) $opts['key']) : (MOZOUT_RESELLER_Settings::api_key());
|
|
if ($key === '' && !$public) {
|
|
if (MOZOUT_RESELLER_Settings::key_unreadable()) {
|
|
return new WP_Error('mozout_reseller_key_unreadable', __('The saved API key can no longer be read (the WordPress security keys changed). Save the key again.', 'mozout-reseller'));
|
|
}
|
|
return new WP_Error('mozout_reseller_no_key', __('The API key is missing. Save it in the plugin settings.', 'mozout-reseller'));
|
|
}
|
|
$base = MOZOUT_RESELLER_Brands::api_base();
|
|
if ($base === '') {
|
|
return new WP_Error('mozout_reseller_no_brand', __('Choose the brand in the plugin settings.', 'mozout-reseller'));
|
|
}
|
|
|
|
$url = $base . '/' . ltrim($path, '/');
|
|
if (!empty($opts['query']) && is_array($opts['query'])) {
|
|
$url = add_query_arg(array_map('rawurlencode', $opts['query']), $url);
|
|
}
|
|
$lang = !empty($opts['lang']) ? $opts['lang'] : MOZOUT_RESELLER_I18n::lang();
|
|
|
|
$headers = array(
|
|
'Accept' => 'application/json',
|
|
'Accept-Language' => $lang === 'pt' ? 'pt' : 'en',
|
|
'User-Agent' => 'mozout-reseller/' . MOZOUT_RESELLER_VERSION . ' WordPress/' . get_bloginfo('version'),
|
|
);
|
|
if ($key !== '') {
|
|
$headers['Authorization'] = 'Bearer ' . $key;
|
|
}
|
|
if (!empty($opts['idempotency_key'])) {
|
|
$headers['Idempotency-Key'] = ($opts['idempotency_key'] === true) ? wp_generate_uuid4() : substr((string) $opts['idempotency_key'], 0, 255);
|
|
}
|
|
$args = array(
|
|
'method' => strtoupper($method),
|
|
'headers' => $headers,
|
|
'timeout' => isset($opts['timeout']) ? (int) $opts['timeout'] : 15,
|
|
'redirection' => 0,
|
|
'sslverify' => true,
|
|
);
|
|
if ($body !== null) {
|
|
$args['headers']['Content-Type'] = 'application/json';
|
|
$args['body'] = wp_json_encode($body);
|
|
}
|
|
|
|
$res = wp_remote_request($url, $args);
|
|
if (is_wp_error($res)) {
|
|
return new WP_Error('mozout_reseller_network', sprintf(
|
|
/* translators: %s: technical reason */
|
|
__('Could not reach the API: %s', 'mozout-reseller'),
|
|
$res->get_error_message()
|
|
), array('status' => 0));
|
|
}
|
|
|
|
$status = (int) wp_remote_retrieve_response_code($res);
|
|
$raw = wp_remote_retrieve_body($res);
|
|
$json = json_decode($raw, true);
|
|
$hdrs = array(
|
|
'correlation_id' => wp_remote_retrieve_header($res, 'x-correlation-id'),
|
|
'retry_after' => wp_remote_retrieve_header($res, 'retry-after'),
|
|
);
|
|
|
|
if ($status >= 200 && $status < 300) {
|
|
return array(
|
|
'status' => $status,
|
|
'data' => (is_array($json) && array_key_exists('data', $json)) ? $json['data'] : $json,
|
|
'meta' => (is_array($json) && isset($json['meta'])) ? $json['meta'] : array(),
|
|
'raw' => $json,
|
|
'headers' => $hdrs,
|
|
);
|
|
}
|
|
return self::to_error($status, is_array($json) ? $json : array(), $hdrs);
|
|
}
|
|
|
|
/** Turns an API error into a WP_Error with a clear message. */
|
|
private static function to_error($status, array $json, array $hdrs)
|
|
{
|
|
$err = isset($json['error']) && is_array($json['error']) ? $json['error'] : array();
|
|
$code = isset($err['code']) ? (string) $err['code'] : 'http_' . $status;
|
|
$api_msg = isset($err['message']) ? (string) $err['message'] : '';
|
|
$details = isset($err['details']) && is_array($err['details']) ? $err['details'] : array();
|
|
$corr = isset($err['correlation_id']) ? $err['correlation_id'] : $hdrs['correlation_id'];
|
|
$reason = isset($details['reason']) ? (string) $details['reason'] : '';
|
|
$portal = MOZOUT_RESELLER_Brands::portal_name();
|
|
|
|
switch (true) {
|
|
case $status === 401:
|
|
$msg = sprintf(
|
|
/* translators: %s: name of the customer area, for example "My MozOut" */
|
|
__('The API key is not valid, was revoked or expired. Create a new key in %s, on the API page, and save it here.', 'mozout-reseller'),
|
|
$portal
|
|
);
|
|
break;
|
|
case $code === 'insufficient_credit':
|
|
$msg = __('The account balance is not enough for this operation. Nothing was charged. Add funds and try again.', 'mozout-reseller');
|
|
if (!empty($details['add_funds_url'])) {
|
|
$msg .= ' ' . esc_url_raw($details['add_funds_url']);
|
|
}
|
|
break;
|
|
case $code === 'insufficient_credits':
|
|
$msg = ($api_msg !== '') ? $api_msg : __('There are not enough credits for this operation. Nothing was charged.', 'mozout-reseller');
|
|
break;
|
|
case $code === 'insufficient_scope':
|
|
$msg = __('The API key does not have the permission this feature needs. Create a key with that permission.', 'mozout-reseller');
|
|
break;
|
|
case $code === 'ip_not_allowed':
|
|
$msg = __('The IP address of this server is not on the key list of allowed IPs.', 'mozout-reseller');
|
|
break;
|
|
case $reason === 'email_account_required':
|
|
$msg = __('E-mail Center is not active on this account. Activate it first.', 'mozout-reseller');
|
|
break;
|
|
case $code === 'sms_not_active':
|
|
$msg = __('SMS is not active on this account. Activate it first.', 'mozout-reseller');
|
|
break;
|
|
case $code === 'spending_limit_exceeded':
|
|
$msg = __('This operation goes over the spending limit of the key. Nothing was charged.', 'mozout-reseller');
|
|
break;
|
|
case $status === 429:
|
|
$wait = isset($details['retry_after']) ? (int) $details['retry_after'] : (int) $hdrs['retry_after'];
|
|
$msg = $wait > 0
|
|
? sprintf(
|
|
/* translators: %d: seconds */
|
|
__('Too many requests. Try again in %d seconds.', 'mozout-reseller'),
|
|
$wait
|
|
)
|
|
: __('Too many requests. Try again in a moment.', 'mozout-reseller');
|
|
if ($code === 'plan_limit_reached' && $api_msg !== '') {
|
|
$msg = $api_msg;
|
|
}
|
|
break;
|
|
case $status >= 500:
|
|
$msg = __('The API did not answer as expected. Try again later.', 'mozout-reseller');
|
|
break;
|
|
default:
|
|
// 404, 409, 422: the API text says what to fix and is meant to be shown as it comes.
|
|
$msg = $api_msg !== '' ? $api_msg : sprintf(
|
|
/* translators: %d: HTTP status */
|
|
__('The API refused the request (HTTP %d).', 'mozout-reseller'),
|
|
$status
|
|
);
|
|
}
|
|
if ($corr) {
|
|
$msg .= ' ' . sprintf(
|
|
/* translators: %s: request reference to give to support */
|
|
__('(reference %s)', 'mozout-reseller'),
|
|
$corr
|
|
);
|
|
}
|
|
return new WP_Error($code, $msg, array(
|
|
'status' => $status,
|
|
'reason' => $reason,
|
|
'details' => $details,
|
|
'correlation_id' => $corr,
|
|
'api_message' => $api_msg,
|
|
));
|
|
}
|
|
}
|