Skip to main content
ApiConnectionManager is a generic, connection-agnostic HTTP auth manager. You instantiate it with a connection ID that matches a record in the UTB Integrations Hub, and it takes care of token negotiation, caching, and injecting the correct Authorization header into your requests.
use UTB\ProductBuilder\Core\ApiConnectionManager;

$api  = new ApiConnectionManager('cep_integrator');
$base = $api->get_api_base(); // e.g. 'https://api.cep.edu.co'
$args = $api->get_auth_request_args();

$response = wp_remote_get($base . '/programs', $args);

Constructor

public function __construct(string $connection_id)
connection_id
string
required
The ID of the connection as configured in UTB Builder → Configuración API. For CEP and CertificadosFlow the canonical ID is cep_integrator.
The constructor does not perform any network calls or database reads. Configuration is loaded lazily the first time a method that needs it is called.

Methods

get_api_base(): string

Returns the base URL configured for this connection, with a trailing slash stripped.
public function get_api_base(): string
$base = $api->get_api_base();
// 'https://api.cep.edu.co'

get_auth_headers(): array

Returns an array of HTTP headers required to authenticate a request. The content depends on the connection’s auth_type:
public function get_auth_headers(): array
auth_typeHeader emitted
none(empty array)
basic_authAuthorization: Basic base64(client_id:client_secret)
bearer_tokenAuthorization: Bearer {bearer_token}
oauth2_client_credentialsAuthorization: Bearer {access_token} (token fetched and cached automatically)
For oauth2_client_credentials, the method calls the token endpoint at {api_base}/oauth/token using the Client Credentials grant, then caches the token in a WordPress Transient for expires_in - 60 seconds (minimum 60 s). Subsequent calls within the TTL return the cached token without a network request.
If the auth_type in the database is an unrecognised value, this method throws \Exception. Wrap calls in a try/catch in production code.
$headers  = $api->get_auth_headers();
// ['Authorization' => 'Bearer eyJhbGci...']

get_auth_request_args(array $additional_args = []): array

Builds a complete wp_remote_get()/wp_remote_post() args array with authentication headers pre-filled and a default Accept: application/json header. Additional args are deep-merged so you can override timeout, add body parameters, etc.
public function get_auth_request_args(array $additional_args = []): array
additional_args
array
Optional array of additional wp_remote_* args. Custom headers are merged with (not replaced by) the auth headers.
// Simple GET:
$args     = $api->get_auth_request_args();
$response = wp_remote_get($api->get_api_base() . '/programs', $args);

// POST with body:
$args = $api->get_auth_request_args([
    'method'  => 'POST',
    'body'    => wp_json_encode(['name' => 'Test']),
    'headers' => ['Content-Type' => 'application/json'],
    'timeout' => 30,
]);
$response = wp_remote_post($api->get_api_base() . '/enrollments', $args);

Supported auth types

none

No authorization header is sent. Useful for public APIs or when authentication is handled at the network level.

basic_auth

The connection’s client_id and client_secret fields are base64-encoded and sent as HTTP Basic Auth:
Authorization: Basic base64(client_id:client_secret)

bearer_token

The connection’s bearer_token field is sent as-is:
Authorization: Bearer {bearer_token}

oauth2_client_credentials

The manager fetches a token from {api_base}/oauth/token using the OAuth 2.0 Client Credentials grant:
POST {api_base}/oauth/token
Authorization: Basic base64(client_id:client_secret)
Content-Type: application/x-www-form-urlencoded

grant_type=client_credentials
The token is stored in a WordPress Transient keyed oauth_token_{connection_id}. The TTL is expires_in - 60 seconds (to account for clock skew), with a floor of 60 seconds.

Configuration storage

Connections are stored in the plugin’s global configuration (retrieved via UTB_PB_DB_Schema::get_config()) under the api_connections array key. Each connection object must have:
FieldRequiredDescription
idYesUnique connection identifier
api_baseYesBase URL for the API
auth_typeYesOne of none, basic_auth, bearer_token, oauth2_client_credentials
client_idOAuth2 / BasicClient ID or username
client_secretOAuth2 / BasicClient secret or password
bearer_tokenBearerStatic token
Backward compatibility: If api_connections is absent but the legacy oauth block is present, new ApiConnectionManager('cep_integrator') automatically maps the old CEP OAuth fields (cep_api_base, cep_client_id, cep_client_secret) to the new structure.

Usage in CEPFlow and CertificadosFlow

Both built-in flows use connection ID 'cep_integrator':
use UTB\ProductBuilder\Core\ApiConnectionManager;

$api      = new ApiConnectionManager('cep_integrator');
$args     = $api->get_auth_request_args();
$response = wp_remote_get($api->get_api_base() . '/api/programas', $args);

if (is_wp_error($response)) {
    // handle error
}

$programs = json_decode(wp_remote_retrieve_body($response), true);

Error handling

ApiConnectionManager throws \Exception in three situations:
SituationMessage pattern
Connection ID not found in DBLa conexión API '{id}' no está configurada en el sistema.
OAuth token fetch fails (network)Error comunicándose con el servidor OAuth para la conexión {id}.
OAuth server returns non-200Error de autenticación OAuth en {id}: HTTP {code}
Unknown auth_typeTipo de autenticación desconocido para la conexión {id}: {type}
try {
    $api  = new ApiConnectionManager('my_connection');
    $args = $api->get_auth_request_args();
} catch (\Exception $e) {
    wc_get_logger()->error('API connection error: ' . $e->getMessage(), ['source' => 'my_plugin']);
}

Build docs developers (and LLMs) love