Last Updated: September 09, 2019
·
6.799K
· drrobotnik

Remote POST from WP to HipChat

WordPress itself has a great administrative interface that makes it suitable as a CMS. Not all the information captured within it is for posts and pages. In this example I've written a function that can be used to interact with the service HipChat to create a new room.

In curl, it would look like this:

curl https://api.hipchat.com/v2/room\?auth_token=XXXXXXXX --data '{"name":"New Room"}' --header "Content-Type:application/json"

In order to make this modular, I've wrapped it in a function and we'll use WP specific functions for our POST request.

function hipchat_create_room( $name = null ) {

Next we need to add the required request specific information url, data, and headers. HipChat requires the data to be JSON, so we use json_encode( $arg_data ); around our array of data.

$post_url = 'https://api.hipchat.com/v2/room?auth_token=XXXXXXXX';

$arg_data = array( 'name' => $name );
$data = json_encode( $arg_data );

$args = array( 'headers' => array( 'Content-Type' => 'application/json' ), 'body' => $data );

The next portion is WP specific, and is recommended only if you're using the platform. It is relatively concise.

$response = wp_remote_post( esc_url_raw( $post_url ), $args );

$response_code = wp_remote_retrieve_response_code( $response );
$response_body = wp_remote_retrieve_body( $response );

Check the response code for errors:

// Bail out early if there are any errors
if ( !in_array( $response_code, array(200,201) ) || is_wp_error( $response_body ) )
    return false;

Since the response is in JSON, I prefer to convert it to PHP, then returning the result.

  $result = json_decode( $response_body );

  return $result;

}

You could easily take this example and add additional functions to provide more interaction with HipChat. For example, now that you've created a room, you could post a notification with some information captured from a form.

Handy

Handy!