WordPress wp_remote_post(): POST Requests with JSON Body, Bearer Token, and Error Handling

wp_remote_post(): send JSON with a token and handle the errors

Sending data to another service is a daily task: an order to a CRM, a form to a mailing service, an event to a webhook. wp_remote_post() is the WordPress way to do it. It works on any host (cURL or PHP streams, whatever is available), respects proxy settings and lets you set headers, the body and timeouts in one array. The part that is easy to get wrong is error handling: a network failure and an error answer from the API are two different things.

Problem: A plugin must send order data to a CRM API as JSON with a Bearer token and handle both failed connections and error responses from the API.

Solution: Call wp_remote_post() with the JSON-encoded body and the headers, check is_wp_error() for network errors, then the status code with wp_remote_retrieve_response_code() for API errors, and decode the body.

JSON with a Bearer token

<?php
function ha_push_order_to_crm( array $order ) {
    $response = wp_remote_post( 'https://api.crm.example.com/v2/orders', array(
        'timeout' => 15,
        'headers' => array(
            'Authorization' => 'Bearer ' . HA_CRM_TOKEN,
            'Content-Type'  => 'application/json',
            'Accept'        => 'application/json',
        ),
        'body'    => wp_json_encode( $order ),
    ) );

    // 1. The request did not reach the API: DNS, timeout, SSL problem
    if ( is_wp_error( $response ) ) {
        return $response;
    }

    // 2. The API answered with an error
    $code = wp_remote_retrieve_response_code( $response );
    $data = json_decode( wp_remote_retrieve_body( $response ), true );

    if ( $code < 200 || $code >= 300 ) {
        $message = is_array( $data ) && isset( $data['message'] ) ? $data['message'] : 'HTTP ' . $code;
        return new WP_Error( 'ha_crm_error', $message, array( 'status' => $code ) );
    }

    return is_array( $data ) ? $data : array();
}

A string body is sent as it is; with the Content-Type header the API knows it is JSON. The default timeout is 5 seconds, which is short for many APIs; set it explicitly, but keep it well below the PHP time limit.

Rate limits: 429 and Retry-After

Many APIs answer 429 Too Many Requests when a client sends too much, often with a Retry-After header in seconds. Do not retry immediately; wait as long as the API asks:

<?php
if ( 429 === wp_remote_retrieve_response_code( $response ) ) {
    $wait = (int) wp_remote_retrieve_header( $response, 'retry-after' );
    wp_schedule_single_event( time() + max( 60, $wait ), 'ha_push_order', array( $order_id ) );
}

Errors 500–599 are worth a retry later too; 400–499 (except 429) usually mean the request itself is wrong and will fail again.

A form-encoded body

When the body is an array, WordPress encodes it as application/x-www-form-urlencoded, which is what OAuth token endpoints usually expect:

<?php
$response = wp_remote_post( 'https://auth.example.com/oauth/token', array(
    'timeout' => 10,
    'body'    => array(
        'grant_type'    => 'client_credentials',
        'client_id'     => HA_CLIENT_ID,
        'client_secret' => HA_CLIENT_SECRET,
    ),
) );

if ( ! is_wp_error( $response ) && 200 === wp_remote_retrieve_response_code( $response ) ) {
    $token = json_decode( wp_remote_retrieve_body( $response ), true );
    set_transient( 'ha_crm_token', $token['access_token'], (int) $token['expires_in'] - 60 );
}

Keep the token in a transient until shortly before it expires, instead of requesting a new one for every API call.

Basic auth

<?php
$response = wp_remote_post( $url, array(
    'headers' => array( 'Authorization' => 'Basic ' . base64_encode( HA_API_USER . ':' . HA_API_PASS ) ),
    'body'    => wp_json_encode( $payload ),
) );

Where to call it

An HTTP request during a page view makes the visitor wait for the other server, and a slow or failing API slows down or breaks the page. Send data in the background instead: schedule a single cron event when the order is placed (wp_schedule_single_event( time(), 'ha_push_order', array( $order_id ) )) and do the request in its callback, with a retry when it fails. How the WooCommerce API is called from another system is shown in reading orders and updating stock through the WooCommerce REST API.

NOTE: Keep tokens and secrets in constants in wp-config.php or in environment variables, not in the plugin code and not in options that every administrator and every database backup can read. And never set 'sslverify' => false to “fix” a certificate error; fix the certificate or the CA bundle of the server instead.