Skip to content
Prodjex

MailChimp API Subscriber Sign Up

2 min read

MailChimp API Subscriber Sign Up

MailChimp allows you to create sign up forms with their builder, but they can be a pain to style and for some don't allow enough customization.

The following code is an example of how you can take advantage of the MailChimp API to subscribe new users.  Doing this allows you to then create a custom sign up form and style it easily to match your own look and feel.

This example assumes you're only passing the First Name, Last Name, and email of a new subscriber.  It's easy enough to add additional fields, but this will get you started.

First you'll need to set up an API key in your MailChimp account, so login and navigate to Account -> Extras -> API Keys.

MailChimp API Subscriber Sign Up

MailChimp API Subscriber Sign Up

MailChimp API Subscriber Sign Up

Once you've clicked to create a new API key go ahead and copy the API key and place it in your code.

Now you will need to find the list ID.  This is not the ID of the list from the URL.  You need to go to your lists and in the drop down select settings.  Scroll all the way down and here you will find your list ID to replace in the code.

MailChimp API Subscriber Sign Up

MailChimp API Subscriber Sign Up

You're all set, now create your form matching the names from the following script and set your form action to "GET".

<?php
/**
 * Created by PhpStorm.
 * User: Prodjex
 * Date: 1/31/2018
 * Time: 9:04 AM
 */

//Grab Data Variables Passed From Form
$data = [
    'email' => $_GET['email'],
    'status' => 'subscribed',
    'firstname' => $_GET['firstname'],
    'lastname' => $_GET['lastname']
];

syncMailchimp($data);

function syncMailchimp($data)
{
    $apiKey = 'Your API KEY';
    $listID = 'Your List ID';

    $memberID = md5(strtolower($data['email']));
    $dataCenter = substr($apiKey, strpos($apiKey, '-') + 1);
    $url = 'https://' . $dataCenter . '.api.mailchimp.com/3.0/lists/' . $listID . '/members/' . $memberID;

    $json = json_encode([
        'email_address' => $data['email'],
        'status' => $data['status'], // "subscribed","unsubscribed","cleaned","pending"
        'merge_fields' => [
            'FNAME' => $data['firstname'],
            'LNAME' => $data['lastname']
        ]
    ]);

    $ch = curl_init($url);

    curl_setopt($ch, CURLOPT_USERPWD, 'user:' . $apiKey);
    curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json']);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_TIMEOUT, 10);
    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'PUT');
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $json);

    $result = curl_exec($ch);
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);

    return $httpCode;
}

Questions or Comments?  View the forum discussion.

  • api
  • curl
  • form
  • mailchimp
  • php
  • sign up
  • subscribe

Keep reading