We were able to achieve this by adding the MailChimp PHP library as a dependency of our custom module. We were then able to make a simple call using the API to subscribe a user to the mailing list. We implemented this via the following code.
First, in our module’s root directory we created a composer.json
file that specified the MailChimp PHP library as a dependency:
{
"require": {
"mailchimp/mailchimp": "*"
}
}
We then installed the Mailchimp API using the Composer Manager drush commands:
$ drush composer-json-rebuild
$ drush composer-manager install
As explained in my last post, the first command builds (or rebuilds) the consolidated project wide composer.json
file and the second command installs the dependencies.
Next, we created a function in our custom module to subscribe a user to a MailChimp mailing list.
<?php
/**
* Add an email to a MailChimp list.
*
* @param string $api_key
* The MailChimp API key.
* @param string $list_id
* The MailChimp list id that the user should be subscribed to.
* @param string $email
* The email address for the user being subscribed to the mailing list.
*/
function my_module_subscribe_user($api_key, $list_id, $email) {
$mailchimp = new Mailchimp($api_key);
try {
$result = $mailchimp->lists->subscribe($list_id, array('email' => $email));
}
catch(Exception $e) {
watchdog('my_module', 'User with email %email not subscribed to list %list_id', array('%email' => $email, '%list_id' => $list_id), WATCHDOG_WARNING);
}
}
With that function defined, we could then subscribe any user to any mailing list by simply calling
<?php
my_module_subscribe_user($api_key, $list_id, $email);