Batches in MailChimp API

First time I faced with Mailchimp API batch operations when I implemented a mass resynchronization function in my mailchimp plugin for WordPress.

In this tutorial we will use the following WordPress functions:

Actually that’s all! ๐Ÿ™‚

Create a Simple MailChimp Batch Subscribe Operation with WordPress

If you’re not sure, where to get your MailChimp API key, read it. If you do not know what is your list ID, go here first.


$my_api = 'YOUR API KEY';
$list_id = 'YOUR LIST ID';

// let's suppose that we have a large array of emails we would like to subscribe with API
$many_emails = array(
	'misha@rudrastyh.com',

	...

	'misha50@rudrastyh.com'
);

// Body parameters should be an object,
// if you pass it as an array, you will get the error "Schema describes object"
$request_body_parameters = new stdClass();

// all the batch operations will be stored in this array
$request_body_parameters->operations = array();


// in this loop I added only subscribe operations, but it could be anything
foreach ( $many_emails as $this_email ) {

	// each batch operation $o should be passed as an object too!
	$o = new stdClass();
	$o->method = 'PUT';
	$o->path = 'lists/' . $list_id . '/members/' . md5( strtolower( $this_email ) );
	$o->body = json_encode( array(
		'email_address' => $this_email,
		'status'        => 'subscribed'
		// "merge_fields", "interests" params could be here as well
	) );
	// add it to the array of all batch operations
	$request_body_parameters->operations[] = $o;

}

// at this moment we have the array of batch operations $request_body_parameters->operations
// you can print_r( $request_body_parameters->operations ) it
// now we continue with creating a batch operations request
$response = wp_remote_post( 'https://'.substr($my_api,strpos($my_api,'-')+1).'.api.mailchimp.com/3.0/batches', array(
	'method' => 'POST',
 	'headers' => array(
		'Authorization' => 'Basic ' . base64_encode( 'user:'. $my_api )
	),
	'body' => json_encode( $request_body_parameters )
) );

if( wp_remote_retrieve_response_message( $response ) == 'OK' ) {
	
	// we're done!
	
	$response_body_parameters = json_decode( wp_remote_retrieve_body( $response ) );
	// let's look what is in the response!
	// print_r( $response_body_parameters )

	echo 'The batch operation ' . $response_body_parameters->id . ' has been submitted';

}

If you would like to create a list and to subscribe emails to this list in a single batch operation โ€“ย please don’t do it! Because MailChimp doesn’t guarantee that the batch operations will be fired in the same order!

Check Batch Operation Status

Once batch operations are scheduled, you can check their status with a simple GET-request.


$my_api = 'YOUR API KEY';
$batch_id = 'BATCH ID';


$response = wp_remote_get( 'https://'.substr($my_api,strpos($my_api,'-')+1).'.api.mailchimp.com/3.0/batches/'.$batch_id, array(
	'headers' => array(
		'Authorization' => 'Basic ' . base64_encode( 'user:'. $my_api )
	)
) );
		

if( wp_remote_retrieve_response_message( $response ) == 'OK' ) {

	$body = json_decode( wp_remote_retrieve_body( $response ) );
	echo "Status: {$body->status}
Finished: {$body->finished_operations}
Errors: {$body->errored_operations}"; }

You can also send an API request to this endpoint /batches to get a list with all batch requests.

Delete a batch operation

And it is also possible to delete a specific batch request:


$usX = substr($my_api,strpos($my_api,'-')+1);

wp_remote_post( "https://$usX.api.mailchimp.com/3.0/batches/" . $batch_id, array(
	'method' => 'DELETE',
 	'headers' => array(
		'Authorization' => 'Basic ' . base64_encode( 'user:'. $my_api )
	)
) );

Batch Webhooks

What is a webhook?

Once a batch operation is completed, MailChimp can request a certain .php file on your server.

Step 1. Create a Webhook


$my_api = 'YOUR API KEY';

$response = wp_remote_post( 'https://' . substr($my_api,strpos($my_api,'-')+1) . '.api.mailchimp.com/3.0/batch-webhooks',array(
 	'headers' => array(
		'method' => 'POST',
		'Authorization' => 'Basic ' . base64_encode( 'user:'. $my_api )
	),
	'body' => json_encode(array(
    		'url' => 'https://rudrastyh.com/batchwebhook.php'
	))
) );

By the way you can also use:

Step 2. Create a file to process webhooks

The only thing is to make sure that the URL can be accessed by MailChimp. When I did it first time, I couldn’t understand why MailChimp API returns “The resource submitted could not be validated” error each time but the problem was that my webhook file was closed with .htpasswd auth ๐Ÿ˜

Here is a very simple example of a webhook file, which is good for debug purposes:


require_once( 'wp-load.php' ); // in case your webhook file is in WP directory

wp_mail( 'misha@rudrastyh.com', 'Batch Completed', print_r($_POST, true) );
Misha Rudrastyh

Misha Rudrastyh

I develop websites since 2008, so it is total of 13 years of experience, oh my gosh. Most of all I love love love to create websites with WordPress and Gutenberg, some ideas and thoughts I share throughout my blog.

Need some developer help? Contact me