goodEgg goodEgg - 4 months ago 75
PHP Question

MailChimp API 3.0 Batch update - Always pending, total_operations:0

Trying to update a batch of emails. I think I've tried every way to do this, but my use of DrewM's MailChimp wrapper only returns the following

$result
content:

Array ( [id] => 1234abcd [status] => pending [total_operations] => 0 [finished_operations] => 0


And so on. No errors, but no operations!

Essentially, my code looks like this, where
$emails
stores all the emails in an array.

include("MailChimp.php");
include("Batch.php");

$list_id = "1234abcd";

use \DrewM\MailChimp\MailChimp;
use \DrewM\MailChimp\Batch;
$apiKey = 'aslkjf84983hg84938h89gd-us13';

if(!isset($emails)){ // If not sending bulk requests
$MailChimp = new MailChimp($apiKey);
$subscriber_hash = $MailChimp->subscriberHash($email);
$result = $MailChimp->patch("lists/$list_id/members/$subscriber_hash",
array(
'status' => 'subscribed',
)
);

/* SENDING BATCH OF EMAILS */
} else if($emails){
$MailChimp = new MailChimp($apiKey);
$Batch = $MailChimp->new_batch();
$i = 1;
foreach($emails as &$value){
$Batch->post("op".$i, "lists/$list_id/members", [
'email_address' => $value,
'status' => 'subscribed',
]);
$i++;
}
$result = $Batch->execute(); // Send the request (not working I guess)
$MailChimp->new_batch($batch_id); // Now get results
$result = $Batch->check_status();
print_r($result);
}


If anyone can see what I'm not seeing, I'll be very grateful!

Answer

Problem solved. After talking with a rep at MailChimp, he helped to find two major problems.

Instead of using a POST method, he said to use PUT, when working with already existing emails. POST is best used for adding emails, while PUT can add and update emails.

So, change

$Batch->post

to

$Batch->put

Secondly, after successfully sending requests and getting errors in the $result, he found they were 405 errors and told me to add the md5 hash to my emails.

So, change

$Batch->post("op".$i, "lists/$list_id/members", [ ...

to

$subscriber_hash = $MailChimp->subscriberHash($value);
$Batch->put("op$i", "lists/$list_id/members/$subscriber_hash", [ ...

And they sent me a MailChimp stocking cap for being a good sport :-)

Veni. Vidi. Vici.

Comments