Reading MailChimp data API 3.0

In one project I needed CRON script to read specific subscribers and copy them in another list.

Although MailChimp API v 3.0 is well documented I've written it down. It may help as an example for connecting and reading paginated list data in PHP.

Class for sending requests:

<?php

class ChimpApi
{

const URL_BASE = 'https://usX.api.mailchimp.com/3.0/';

const API_KEY = '';

/**
*
* @param string $method
* @param string $target
* @return array
*/
public function request($method, $target)
{
    $curlSession = curl_init();
    curl_setopt($curlSession, CURLOPT_URL, self::URL_BASE . $target);
    curl_setopt($curlSession, CURLOPT_HTTPHEADER, array(
        'Content-Type: application/json',
        'Authorization: apikey ' . self::API_KEY
    ));
    curl_setopt($curlSession, CURLOPT_USERAGENT, 'PHP-MCAPI/3.0');
    curl_setopt($curlSession, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($curlSession, CURLOPT_TIMEOUT, 20);
    curl_setopt($curlSession, CURLOPT_CUSTOMREQUEST, $method);
    // curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($curlSession, CURLOPT_SSL_VERIFYPEER, false);
    // curl_setopt($ch, CURLOPT_POSTFIELDS, $json_data);

    $response = curl_exec($curlSession);
    curl_close($curlSession);
    $responseArray = json_decode($response, true);

    return $responseArray;
}
}

An example of reading data and save them in temporary table.


<?php
require 'ChimpApi.php';
require 'database.local.php';

define('COUNT', 100);

$api = new ChimpApi();

$dsn = 'mysql:host=' . $dbParams['hostname'] . ';dbname=' . $dbParams['database'];
$pdo = new PDO($dsn, $dbParams['username'], $dbParams['password'], array(
    PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES 'UTF8'"
));

try {
    
    $response = $api->request('GET', 'reports?count=1');
    $campaign = $response['reports'][0]; // last campaign
    
    $total = $campaign['emails_sent'];
    $campaignId = $campaign['id'];

    $sql = "INSERT INTO mailchimp_groups (group_type, campaign_id, list_id, email_id, email_address, open_count) VALUES (1, :campaignid, :listid, :emailid, :emailaddress, :opencount)";
    $prepare = $pdo->prepare($sql);
   
    for ($offset = 0; $offset <= $total; $offset = $offset + COUNT) {
        $requestUrl = sprintf('reports/%s/sent-to?fields=sent_to.email_id,sent_to.email_address,sent_to.open_count,sent_to.list_id,total_items&offset=%d&count=%d', $campaignId, $offset, COUNT);
        $response = $api->request('GET', $requestUrl);
        
        foreach ($response['sent_to'] as $row) {
            if ($row['open_count'] > 1) {
                $prepare->bindValue(':campaignid', $campaignId);
                $prepare->bindValue(':listid', $row['list_id']);
                $prepare->bindValue(':emailid', $row['email_id']);
                $prepare->bindValue(':emailaddress', $row['email_address']);
                $prepare->bindValue(':opencount', $row['open_count']);
                $prepare->execute();
           }
        }
    }
    
} catch (Exception $e) {
    echo $e->getMessage();
}

TheĀ Playground is very helpfull for exploring account data and statistics.