Passing GDPR preferences via the MailChimp API

Using the MailChimp form builder, embedded forms or subscriber popups is great to get your newsletter signup process up and running quickly but often you want a bit more control.

You might want to create custom embedded newsletter signup forms on your website and use the MailChimp API to push those subscribers into MailChimp, but you will also need to push in their selected GDPR preferences (email, direct mail, customized online advertising) to record that the subscriber has opted into marketing preferences.

MailChimp Image

To add a subscriber with their GDPR marketing preferences via the MailChimp API, you have to split the process out into 4 parts.

For the purpose of this tutorial I am going to make use of PHP and the MailChimp API Wrapper for PHP by Drew McLellan

1) Prerequisites

In order to add a subscriber to your mailing list you need to know your API key, the list you are subscribing them to, their email address and the marketing preferences they have opt-ed into.

$apiKey = '[MAILCHIMP_API_KEY]';
$listId = '[MAILCHIMP_LIST_KEY]';
$email = '[SUBSCRIBER_EMAIL_ADDRESS]';
$gdprEmailMarketingPermissions = '????';

The first 3 values are fairly easy to get

  • $apiKey - Can be obtained at https://admin.mailchimp.com/account/api/
  • $listId
    • Open your list of audience via https://admin.mailchimp.com/lists/
    • For the desired list, select the Settings option from the drop-down on the right
    • Scroll to the bottom of the page and you should see "Unique ID for audience ..."
  • $email - This will be submitted via the newsletter signup form on the site.

The 4th value $gdprEmailMarketingPermissions is a bit tricker. The user must indicate how they wish to opt-in to your newsletter (via the signup for you embed on your website) before you can opt them into any of the marketing preferences in MailChimp. You can then opt them into one or more of the available marketing preferences (email, direct mail, customized online advertising) as per their selection.

The MailChimp ID's for the marketing preferences are different for each list and the easiest way to do find out what these marketing preference ID's are is to add a test subscriber directly into MailChimp and then retrieve their details which will include the marketing preferences ID's and whether the subscriber is opt-ed in or out.

For example, if I add chris@supercoolwidgets.xyz into my MailChimp audience list via the Add a subscriber, I can then retrieve the contact details of this subscriber via:-

$mailChimp = new \DrewM\MailChimp\MailChimp($apiKey);

$email = 'chris@supercoolwidgets.xyz';
$subscriberHash = \DrewM\MailChimp\MailChimp::subscriberHash($email);
$contact = $mailChimp->get("lists/$listId/members/$subscriberHash");

// Output the details of the contact to a temporary file
file_put_contents('/tmp/contact-details.json', json_encode($contact, JSON_PRETTY_PRINT));

The contents of the contact-details.json file should contain details similar to the ones below. Note: I've stripped the example down to only the key information we are concerned about so your data structure will contain a lot more information.

{
    "id": "WugqD604iFp0p3ANYj6BoXy4K68OufGT",
    "email_address": "chris@supercoolwidgets.xyz",
    "status": "subscribed",
    "marketing_permissions": [
        {
            "marketing_permission_id": "6fP5QDVYde",
            "text": "Email",
            "enabled": false
        },
        {
            "marketing_permission_id": "WMpEho8C2O",
            "text": "Direct Mail",
            "enabled": false
        },
        {
            "marketing_permission_id": "FwmcY98lf6",
            "text": "Customized Online Advertising",
            "enabled": false
        }
    ],
    "source": "API - Generic",
    "list_id": "Zt47FZR35w",
  }

Now you can create a mapping between your marketing preferences options in your newsletter signup form and MailChimp's GDPR marketing preferences which you can use during your newsletter signup process i.e.

$marketingPreferencesMapping = [
    'email' => '6fP5QDVYde',
    'direct_mail' => 'WMpEho8C2O',
    'customized_online_advertising' => 'FwmcY98lf6',
];

2) Creating a new contact

With the prerequisites complete, we now have all the details we need (API key, list id, email address of the subscriber and the MailChimp marketing preferences) to add a subscriber to our MailChimp newsletter and set their GDPR marketing preferences.

First, we need to add the subscriber to our list.

$mailChimp = new \DrewM\MailChimp\MailChimp($apiKey);

// Add user to the newsletter
$contact = $mailChimp->post("lists/$listId/members", [
    'email_address' => $email,
    'status'        => 'subscribed',
]);

if (!$contact) {
    throw \RuntimeException('Error adding contact to MailChimp');
}

3) Retrieve the user you have just created

Next, we need to retrieve the subscriber we have just created

$subscriberHash = \DrewM\MailChimp\MailChimp::subscriberHash($email);
$contact = $mailChimp->get("lists/$listId/members/$subscriberHash");

4) Update the user with the appropriate GDPR marketing preferences.

And finally, we enable the GDPR marketing preference in line with what the subscriber has opt-ed into

// These selected preferences should come from the signup form on your website.
$selectedMarketingPreferences = [ ..... ];

// Get the GDPR options
$enabledMarketingPermissions = [];
foreach ($contact['marketing_permissions'] as $marketingPermission) {
   // Get the key for the marketing permission id
   $key = array_search($marketingPermission['marketing_permission_id'], $marketingPreferencesMapping);

   // If the key isn't one in the selected marketing permissions the continue to next one
   if (!in_array($key, $selectedMarketingPermissions)) {
      continue;
   }

   // Set the marketing permission to enabled
    $marketingPermission['enabled'] = true;
    $enabledMarketingPermissions[] = $marketingPermission;
}

// Update the GDPR marketing permissions
$contact = $mailChimp->patch("lists/$listId/members/$subscriberHash", [
    "marketing_permissions" => $enabledMarketingPermissions,
]);

Full Code Example

So, let put the whole example together

/*
 * Step 1 - Prerequites
 * 
 * EDIT CONFIG VARIABLES AS NECESSARY
 */

// MailChimp API & List ID 
$apiKey = '[MAILCHIMP_API_KEY]';
$listId = '[MAILCHIMP_LIST_ID]';

// Marketing Preference Mapping for embedded form -> mailchimp permissions.
$marketingPreferencesMapping = [
   'email' => '[MARKETING_PREFERENCE_ID_FOR_EMAIL]',
    'direct_mail' => '[MARKETING_PREFERENCE_ID_FOR_DIRECT_MAIL]',
    'customized_online_advertising' => '[MARKETING_PREFERENCE_ID_FOR_CUSTOMIZED_ONLINE_ADVERTISING',
];

// Email Address obtained from the embedded newsletter signup form
$email = '[SUBSCRIBER_EMAIL_ADDRESS]';

// Marketing Permissions obtained from the embeded newsletter signup form
// We're going to assume email and customized_online_advertising were selected in the form
$selectedMarketingPermissions = [
   'email',
   'customized_online_advertising',
];

/*
 * NO EDITS REQUIRED BEYOND THIS POINT
 */

/*
 * Step 2 - Create the user
 */
$mailChimp = new \DrewM\MailChimp\MailChimp($apiKey);

// Add user to the newsletter
$contact = $mailChimp->post("lists/$listId/members", [
    'email_address' => $email,
    'status'        => 'subscribed',
]);

if (!$contact) {
    throw \RuntimeException('Error adding contact to MailChimp');
}

/*
 * Step 2 - Retrieve User
 */
$subscriberHash = \DrewM\MailChimp\MailChimp::subscriberHash($email);
$contact = $mailChimp->get("lists/$listId/members/$subscriberHash");
/*
 * Step 3 - Set GDPR preferences 
 */

// Get the appropriate GDPR options
$enabledMarketingPermissions = [];
foreach ($contact['marketing_permissions'] as $marketingPermission) {
   // Get the key for the marketing permission id
   $key = array_search($marketingPermission['marketing_permission_id'], $marketingPreferencesMapping);

   // If the key isn't one in the selected marketing permissions the continue to next one
   if (!in_array($key, $selectedMarketingPermissions)) {
      continue;
   }

   // Set the marketing permission to enabled
    $marketingPermission['enabled'] = true;
    $enabledMarketingPermissions[] = $marketingPermission;
}

// Update the GDPR marketing permissions
$contact = $mailChimp->patch("lists/$listId/members/$subscriberHash", [
    "marketing_permissions" => $enabledMarketingPermissions,
]);

Code Repository

I've created a small example repository with this code https://github.com/chrisshennan/mailchimp-api-gdpr-marketing which can be used as a reference.

References

The Author

Ready for more?

Subscribe to our newsletter and get hints and tips for keeping your site performing at its best direct to your inbox

Subscribe