Last Updated: February 25, 2016
·
4.774K
· preclowski

Simple implementation of MailChimp API to subscribe user

<?php

/**
 * MailChimp API documentation:
 * http://apidocs.mailchimp.com/api/
 */

require_once 'MCAPI.class.php'; # Download: http://apidocs.mailchimp.com/api/downloads/

# Configuration
$config = array(
    'apiKey' => 'API-KEY',
    'listId' => 'LIST-ID',
    'email'  => $_POST['email'],
);

# Error codes available at: http://apidocs.mailchimp.com/api/1.3/exceptions.field.php
$errorCodes = array(
    230 => 'You already subscribed to this mailing list. Thanks!',
    232 => 'This isn\'t valid e-mail address.',
);

$api = new MCAPI($config['apiKey']);

//var_dump($api->lists()); # Uncomment this to get ID's of mailing lists and select proper list ID.

?>
<!doctype html>
<html>
<head>
    <meta charset="utf-8">
    <title>Mailing</title>
</head>
<body>
<h1>Mailing</h1>
<?php if (filter_var($config['email'], FILTER_VALIDATE_EMAIL)): ?>
    <?php if ($api->listSubscribe($config['listId'], $config['email'])): ?>
        <p style="background:lightgreen">Success</p>
    <?php else: ?>
        <p style="background:red">Error</p>
        <p>Error code: <?php echo $api->errorCode; ?></p>
        <p>Error message: <?php echo $errorCodes[$api->errorCode]; ?></p>
    <?php endif; ?>
<?php else: ?>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
    <input type="email" name="email">
    <input type="submit">
</form>
<?php endif; ?>
</body>
</html>