WC_Helper::get_api_error │ public static │ WC 11.2.0

The last failed Helper API subscriptions response, if one is still current.

Method of the class: WC_Helper{}

No Hooks.

Returns

array{code:int, message:string, retry_after:int|null}|null. Null when the last fetch succeeded.

Usage

$result = WC_Helper::get_api_error(): ?array;

Changelog

Since 11.2.0 Introduced.

WC_Helper::get_api_error() code WC 11.2.1

public static function get_api_error(): ?array {
	$error = get_transient( self::CACHE_KEY_API_ERROR );

	if ( ! is_array( $error ) || ! isset( $error['code'] ) ) {
		return null;
	}

	$code           = (int) $error['code'];
	$stored_message = (string) ( $error['message'] ?? '' );

	// A rate limit is the one failure with a known end, and the generic copy
	// ("a few minutes") understates a window that can run to hours. Read the
	// backoff live so the figure counts down across page loads.
	$retry_after = 429 === $code
		? WC_Helper_API_Backoff::get_retry_after( WC_Helper_API_Backoff::REQUEST_TYPE_SUBSCRIPTIONS )
		: null;

	if ( null !== $retry_after ) {
		$now = time();

		$message = sprintf(
			/* translators: %s: localized duration until the request limit resets, e.g. "5 minutes" or "3 hours". */
			__( 'You have exceeded the request limit. Please try again in %s.', 'woocommerce' ),
			human_time_diff( $now, $now + $retry_after )
		);
	} elseif ( in_array( $code, self::RESPONSE_CODES_WITH_SPECIFIC_MESSAGES, true ) ) {
		// We have copy written for this status, so rebuilding it costs nothing
		// and gains the viewer's locale.
		$message = self::get_message_for_response_code( $code );
	} elseif ( $code < 100 ) {
		// No HTTP status means the request never completed, so the recorded
		// message is raw transport text ("cURL error 28: Operation timed
		// out...") — untranslated developer detail that tells a merchant
		// nothing. record_api_error() logs the specifics instead. The copy
		// points at the store's own connectivity because that is the
		// overwhelmingly likelier cause of a failed connection.
		$message = __( 'Your store could not connect to WooCommerce.com. Please try again after a few minutes. If the issue persists, check whether your server can make outgoing requests.', 'woocommerce' );
	} elseif ( '' !== $stored_message ) {
		// Otherwise the recorded message wins. Rebuilding from the status
		// would replace real guidance — the reconnect instructions on a 401,
		// the invalid-response explanation on a 422 — with a bare
		// "HTTP status code %d".
		$message = $stored_message;
	} else {
		$message = self::get_message_for_response_code( $code );
	}

	if ( '' === $message ) {
		return null;
	}

	return array(
		'code'        => $code,
		'message'     => $message,
		'retry_after' => $retry_after,
	);
}