A simple Mailchimp sign up form

Here is a simple implementation of an HTML form that uses PHP to authenticate with the Mailchimp API. This is intended to be expanded upon and serve as a starting point.

Mailchimp API Key and Audience ID

Log in to your Mailchimp account and open the user menu by clicking your avatar at the top-right. Then click “Account & billing”.

On the “Account & billing” page, click the “Extras” navigation dropdown and then select “API Keys”. Then follow the steps to create an API Key.

You’ll need to go to the “All contacts” page within the “Audience” navigation menu. On the “All contacts” page, click the “Settings” navigation dropdown and then select “Audience name and defaults”. On this page you will find your Audience ID.

HTML

<form class="mailchimp">
    <input type="email" id="email" name="email" class="mailchimp__email" placeholder="Enter your email" required>
    <button type="submit" class="mailchimp__submit">Sign Up</button>
</form>

<script src="scripts/mailchimp.js"></script>

JavaScript

document.addEventListener('DOMContentLoaded', () => {
    const form = document.querySelector('.mailchimp')
    const emailInput = document.querySelector('.mailchimp__email')

    form.addEventListener('submit', (event) => {
        event.preventDefault()

        const email = emailInput.value
        
        // validate email input
        const emailPattern = /^[^\s@]+@[^\s@]+\.[^\s@]+$/
        if (!emailPattern.test(email)) {
            alert('Please enter a valid email address.')
            return
        }

        // call the PHP server-side script
        const url = '../mailchimp.php'

        // send the email address to the server
        fetch(url, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded'
            },
            body: `email=${encodeURIComponent(email)}`
        })
        // parse the response
        .then(response => response.json())
        // handle the response
        .then(data => {
            if (data.status === 'subscribed') {
                alert('Thank you for signing up!')
                form.reset()
            } else {
                alert('An error occurred. Please try again later.')
            }
        })
        // handle errors
        .catch(error => {
            console.error('Error:', error)
        });
    });
});

PHP

<?php
// get the email from the POST request body
$email = $_POST['email'];

// Mailchimp API Key
$apiKey = 'ENTER_YOUR_API_KEY';

// Mailchimp Audience ID
$audienceId = 'ENTER_YOUR_AUDIENCE_ID';

// extract the "data center" text from the API Key
$dataCenter = explode('-', $apiKey)[1];

// Mailchimp API endpoint URL
$url = "https://{$dataCenter}.api.mailchimp.com/3.0/lists/{$audienceId}/members";

// data to be sent to Mailchimp
$data = array(
    'email_address' => $email,
    'status' => 'subscribed'
);

// initialize cURL session
$ch = curl_init($url);

// set cURL options
curl_setopt($ch, CURLOPT_USERPWD, 'user:' . $apiKey);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));

// execute cURL session
$response = curl_exec($ch);

// close cURL session
curl_close($ch);

// return the Mailchimp API response to the client
echo $response;
?>