wordpress-domains-plugin/mozout-domains/includes/class-api.php
2026-12-01 14:09:09 +02:00

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_DOMAINS_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_DOMAINS_Settings::api_key());
if ($key === '' && !$public) {
if (MOZOUT_DOMAINS_Settings::key_unreadable()) {
return new WP_Error('mozout_domains_key_unreadable', __('The saved API key can no longer be read (the WordPress security keys changed). Save the key again.', 'mozout-domains'));
}
return new WP_Error('mozout_domains_no_key', __('The API key is missing. Save it in the plugin settings.', 'mozout-domains'));
}
$base = MOZOUT_DOMAINS_Brands::api_base();
if ($base === '') {
return new WP_Error('mozout_domains_no_brand', __('Choose the brand in the plugin settings.', 'mozout-domains'));
}
$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_DOMAINS_I18n::lang();
$headers = array(
'Accept' => 'application/json',
'Accept-Language' => $lang === 'pt' ? 'pt' : 'en',
'User-Agent' => 'mozout-domains/' . MOZOUT_DOMAINS_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_domains_network', sprintf(
/* translators: %s: technical reason */
__('Could not reach the API: %s', 'mozout-domains'),
$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_DOMAINS_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-domains'),
$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-domains');
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-domains');
break;
case $code === 'insufficient_scope':
$msg = __('The API key does not have the permission this feature needs. Create a key with that permission.', 'mozout-domains');
break;
case $code === 'ip_not_allowed':
$msg = __('The IP address of this server is not on the key list of allowed IPs.', 'mozout-domains');
break;
case $reason === 'email_account_required':
$msg = __('E-mail Center is not active on this account. Activate it first.', 'mozout-domains');
break;
case $code === 'sms_not_active':
$msg = __('SMS is not active on this account. Activate it first.', 'mozout-domains');
break;
case $code === 'spending_limit_exceeded':
$msg = __('This operation goes over the spending limit of the key. Nothing was charged.', 'mozout-domains');
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-domains'),
$wait
)
: __('Too many requests. Try again in a moment.', 'mozout-domains');
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-domains');
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-domains'),
$status
);
}
if ($corr) {
$msg .= ' ' . sprintf(
/* translators: %s: request reference to give to support */
__('(reference %s)', 'mozout-domains'),
$corr
);
}
return new WP_Error($code, $msg, array(
'status' => $status,
'reason' => $reason,
'details' => $details,
'correlation_id' => $corr,
'api_message' => $api_msg,
));
}
}