400badrequest
400badrequest

Reputation: 33

Mailchimp api 3.0 error: "Schema describes object, array found instead" is the code or on mailchimp's end?

I need to bulk update subscribers in my mailchimp lists using mailchimp's api and subscriber lists in my database.

I am trying implement the solution to the question here: Mailchimp API 3.0 Batch Subscribe but I'm getting the error

{"type":"http://developer.mailchimp.com/documentation/mailchimp/guides/error-glossary/","title":"Invalid Resource","status":400,"detail":"The resource submitted could not be validated. For field-specific details, see the 'errors' array.","instance":"8198a6e9-9a7c-4e00-8365-3a7062f047f3","errors":[{"field":"","message":"Schema describes object, array found instead"}]}

I've seen people with similar issues, and sometimes it's a problem on mailchimp's end and sometimes it's a problem with how the data is being passed. Any insight into whether I need to fix the code or contact mailchimp would be appreciated!

script in question:

<?php
$apikey  = 'myapi'; // Your Mailchimp ApiKey
$list_id = 'mylist'; // your List ID Where you want to add subscriber

$servername = 'myserver';
$username   = 'myun';
$password   = 'mypw';
$dbname     = 'mydb';
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
    die('Connection failed: ' . $conn->connect_error);
}

$sql       = 'SELECT * FROM emails Limit 2';
$result    = $conn->query($sql);
$finalData = array();
if ($result->num_rows > 0) {
    // output data of each row
    while ($row = $result->fetch_assoc()) {
        $individulData = array(
            'apikey'        => $apikey,
            'email_address' => $row['email'],
            'status'        => $row['status'],//subscribe,pending,unsubscribe
            'merge_fields'  => array(
                'FNAME' => $row['FNAME'],
                'LNAME' => $row['LNAME'],
                'BARCODE' => $row['BARCODE'],
                'SERVICE' => $row['SERVICE'],
                'PURCHASE' => $row['PURCHASE'],
            )
        );

        $json_individulData        = json_encode($individulData);
        $finalData['operations'][] =
            array(
                "method" => "PUT",
                "path"   => "/lists/$list_id/members/",
                "body"   => $json_individulData
            );
    }
}

$api_response = batchSubscribe($finalData, $apikey);
print_r($api_response);
$conn->close();

/**
 * Mailchimp API- List Batch Subscribe added function
 *
 * @param array  $data   Passed you data as an array format.
 * @param string $apikey your mailchimp api key.
 *
 * @return mixed
 */
function batchSubscribe(array $data, $apikey)
{
    $auth          = base64_encode('user:' . $apikey);
    $json_postData = json_encode($data);
    $ch            = curl_init();
    $dataCenter    = substr($apikey, strpos($apikey, '-') + 1);
    $curlopt_url   = 'https://' . $dataCenter . '.api.mailchimp.com/3.0/batches/';
    curl_setopt($ch, CURLOPT_URL, $curlopt_url);

    curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json',
        'Authorization: Basic ' . $auth));
    curl_setopt($ch, CURLOPT_USERAGENT, 'PHP-MCAPI/3.0');
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_TIMEOUT, 10);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $json_postData);


    $result = curl_exec($ch);
    return $result;
}

?>

Upvotes: 3

Views: 3348

Answers (3)

Neo77
Neo77

Reputation: 56

I had a similar issue, the message was "Schema describes string, boolean found instead". It seems that json_encode() has a problem with special characters.

I solved it using this code, maybe it will work for you: utf8_encode($row['FNAME']) or you could try using (string). I hope this can help somebody. I used POST instead of PUT Example:

   $stringData =  array(
    'apikey'        => $api_key,
    'email_address' => $row['email'],
    'status'        => 'subscribed',
    'merge_fields'  =>  array(
        'FNAME'     =>  utf8_encode($row['FNAME']),
        'LNAME'     =>  utf8_encode($row['LNAME'])
    )
   );

Upvotes: 1

Ming Teoh
Ming Teoh

Reputation: 1

casting object is unnecessary.

refactored from Kevin's code:

$operations = [];
foreach ($customers as $customer)
{
    if ($customer->hasEmail())
    {
        $operations[] = [
            'method'        => 'post',
            'path'          => '/lists/' . $settings['list_id'] . '/members',
            'body' => json_encode([
                'email_address' => $customer->email,
                'status'        => 'subscribed',
                'merge_fields' => [],
            ])
        ];
    }
}

try
{
    $response = $mailchimp->batches->start(['operations'=>$operations]);
    print_r($response);
}
catch (\Exception $e)
{
    // var_dump($e->getMessage());
    print_r($e->getResponse()->getBody()->getContents());
}

missing bit is the operation list must be owned by 'operations' key in request payload

Upvotes: 0

Kevin van Boeckholtz
Kevin van Boeckholtz

Reputation: 41

I had a similar error. Hope it's still relevant for future users.

The main problem is the mailchimp documentation.


$operations = [];
foreach ($customers as $customer)
{
    if ($customer->hasEmail())
    {
        $operations['operations'][] = (object) [
            'method'        => 'post',
            'path'          => '/lists/' . $settings['list_id'] . '/members',
            'body' => json_encode([
                'email_address' => $customer->email,
                'status'        => 'subscribed',
                'merge_fields' => (object) [],
            ])
        ];
    }
}

try
{
    $response = $mailchimp->batches->start($operations);
    print_r($response);
}
catch (\Exception $e)
{
    // var_dump($e->getMessage());
    print_r($e->getResponse()->getBody()->getContents());
}

Upvotes: 4

Related Questions