Mailchimp API Batch Request

Working with Mailchimp API, I’m trying to add contacts without success by sending in PHP Async Request batch call to their endpoint. I’ve gone trough their documentation may times but still without success, trying to replicate their example. https://mailchimp.com/developer/marketing/guides/run-async-requests-batch-endpoint/ I am using the php sdk.

Would be great if someone could point me in the right direction why the second example is not working.

#################START OF CODE #############################

<?php

require_once('vendor/autoload.php');

require_once('config.php');

include 'dbh.php';

include 'testDbh.php';

$mailchimp = new MailchimpMarketing\ApiClient();

$mailchimp->setConfig([

    'apiKey' => $key,

    'server' => $server

]);

    // build json array from mysql db

    $users = [];

    $conn = mysqli_connect("localhost","root","","mailchimpapi");

    //check connection

    if(!$conn){

        echo "Failed to connect to MySQL: " . mysqli_connect_error();

        exit();

      }else{

          echo 'Connection Successful! <br><br>';

      }

      $sql = "SELECT * FROM mailchimpbatch";

        //mysqli write query and get result

        $results = mysqli_query($conn, $sql);

        

        $users = mysqli_fetch_all($results, MYSQLI_ASSOC);


$operations = [];

foreach($users as $user) {
    $operation = [  

        'method' => 'POST',

        'path' => "/lists/$listId/members",

        'operation_id' => $user['id'],

        'body' => json_encode([

            'email_address' => $user['email'],

            'status' => $user['status'], 

            'merge_fields' =>

                'FNAME' => $user['fname'],

                'LNAME' => $user['lname']
            ]

        ])

    ];

    array_push($operations, $operation);

}

try {

    $response = $mailchimp->batches->start($operations);

    echo $response;

} catch (\MailchimpMarketing\ApiException $e) {

    echo $e->getMessage();

}

Here is the print_r of $users I pull from the database (made up people);

############################END OF CODE ##########################

Array ( 
[0] => Array 
	( 
		[id] => 1 
		[status] => subscribed 
		[email] => [email protected] 
		[fname] => David 
		[lname] => Tester 
	) 
[1] => Array 
	( 
		[id] => 2 
		[status] => subscribed 
		[email] => [email protected] 
		[fname] => Kevin 
		[lname] => Ishere 
	) 
[2] => Array 
	( 
		[id] => 3 
		[status] => subscribed 
		[email] => [email protected] 
		[fname] => Gerald 
		[lname] => Happy 
	) 
[3] => Array 
	(
		[id] => 4 
		[status] => subscribed 
		[email] => [email protected] 
		[fname] => Tim 
		[lname] => Toolman 
	) 
[4] => Array 
	( 
		[id] => 5 
		[status] => subscribed 
		[email] => [email protected] 
		[fname] => Jack [lname] => Grealish 
	)

)

The error I receive is a 400 BAD REQUEST, INVALID RESOURCE (full error returned is at the bottom of this post).

*****Upon reaching out to Mailchimp they responded with the following:

While we are unable to assist with editing or making PHP calls, we can see the Request is being sent over as an array, and does not have any reference to the required “operations”. For example, we would expect to see something like:

{
 "operations": [
{
    "method": "POST",
    "path": "\/lists\/$listID\/members",
    "operation_id": "1",
    "body": "{\"email_address\":\"[email protected]\",\"status\":\"subscribed\",\"merge_fields\":{\"FNAME\":\"David\",\"LNAME\":\"Tester\"}}"
  }
 ]
}

The request must be an object, rather than an array.

So now I am working on that change, but i’m unsure how to implement that - any ideas?

###################################################################

*Full error returned =
Fatal error: Uncaught GuzzleHttp\Exception\ClientException: Client error: POST https://us6.api.mailchimp.com/3.0/batches resulted in a 400 Bad Request response: {“type”:“https://mailchimp.com/developer/marketing/docs/errors/",“title”:"Invalid Resource”,“status”:400,“detail”:"The r (truncated…) in C:\xampp\htdocs\dashboard\MailchimpAPI\vendor\guzzlehttp\guzzle\src\Exception\RequestException.php:113 Stack trace: #0 C:\xampp\htdocs\dashboard\MailchimpAPI\vendor\guzzlehttp\guzzle\src\Middleware.php(69): GuzzleHttp\Exception\RequestException::create(Object(GuzzleHttp\Psr7\Request), Object(GuzzleHttp\Psr7\Response), NULL, Array, NULL) #1 C:\xampp\htdocs\dashboard\MailchimpAPI\vendor\guzzlehttp\promises\src\Promise.php(204): GuzzleHttp\Middleware::GuzzleHttp{closure}(Object(GuzzleHttp\Psr7\Response)) #2 C:\xampp\htdocs\dashboard\MailchimpAPI\vendor\guzzlehttp\promises\src\Promise.php(153): GuzzleHttp\Promise\Promise::callHandler(1, Object(GuzzleHttp\Psr7\Response), NULL) #3 C:\xampp\htdocs\dashboard\MailchimpAPI\vendor\guzzlehttp\promises\src\TaskQueue.php(48): GuzzleHttp\Promise\Promise::GuzzleHttp\Promise{closure}() #4 C:\xampp\htdocs\dashboard\MailchimpAPI\vendor\guzzlehttp\promises\src\Promise.php(248): GuzzleHttp\Promise\TaskQueue->run(true) #5 C:\xampp\htdocs\dashboard\MailchimpAPI\vendor\guzzlehttp\promises\src\Promise.php(224): GuzzleHttp\Promise\Promise->invokeWaitFn() #6 C:\xampp\htdocs\dashboard\MailchimpAPI\vendor\guzzlehttp\promises\src\Promise.php(269): GuzzleHttp\Promise\Promise->waitIfPending() #7 C:\xampp\htdocs\dashboard\MailchimpAPI\vendor\guzzlehttp\promises\src\Promise.php(226): GuzzleHttp\Promise\Promise->invokeWaitList() #8 C:\xampp\htdocs\dashboard\MailchimpAPI\vendor\guzzlehttp\promises\src\Promise.php(62): GuzzleHttp\Promise\Promise->waitIfPending() #9 C:\xampp\htdocs\dashboard\MailchimpAPI\vendor\guzzlehttp\guzzle\src\Client.php(123): GuzzleHttp\Promise\Promise->wait() #10 C:\xampp\htdocs\dashboard\MailchimpAPI\vendor\mailchimp\marketing\lib\Api\BatchesApi.php(538): GuzzleHttp\Client->send(Object(GuzzleHttp\Psr7\Request), Array) #11 C:\xampp\htdocs\dashboard\MailchimpAPI\vendor\mailchimp\marketing\lib\Api\BatchesApi.php(527):

Sponsor our Newsletter | Privacy Policy | Terms of Service