May 16, 2019 in Drupal 8, Snippets

This code will make you manage subscriptions in mailchimp via a drupal 8 webform. First, create a webform with a "fist name", "last name", and "email" field.

Then, in your custom module add a folder src/Plugin/WebformHandler and create a file newsletterSubscription.php. Add the following code:

<?php
namespace Drupal\<mycustommodule>\Plugin\WebformHandler;

use Drupal\Core\Form\FormStateInterface;
use Drupal\webform\Plugin\WebformHandlerBase;
use Drupal\webform\webformSubmissionInterface;

/**
 * Form submission handler.
 *
 * @WebformHandler(
 *   id = "newslettersubscription",
 *   label = @Translation("Newsletter subscription"),
 *   category = @Translation("Form Handler"),
 *   description = @Translation("Administers subscriptions in Mailchimp"),
 *   cardinality = \Drupal\webform\Plugin\WebformHandlerInterface::CARDINALITY_SINGLE,
 *   results = \Drupal\webform\Plugin\WebformHandlerInterface::RESULTS_PROCESSED,
 * )
 */

class newsletterSubscription extends WebformHandlerBase {

  /**
   * {@inheritdoc}
   */
  public function defaultConfiguration() {
    return [];
  }

  const MAILCHIMP_API_KEY = 'x'; // see https://mailchimp.com/help/about-api-keys
  const LIST_ID = 'x'; // see https://3by400.com/get-support/3by400-knowledgebase?view=kb&kbartid=6


  /**
   * {@inheritdoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state, WebformSubmissionInterface $webform_submission) {

    $values = $webform_submission->getData();
    $email = strtolower($values['e_mail']);
    $first_name = $values['first_name'];
    $last_name = $values['last_name'];

    // The data to send to the API
    $postData = array(
      "email_address" => "$email",
      "status" => "subscribed",
      "merge_fields" => array(
        "FNAME" => "$first_name",
        "LNAME" => "$last_name"
      )
    );

    // Setup cURL
    // To get the correct dataserver, see the url of your mailchimp back-end, mine is https://us20.admin.mailchimp.com/account/api/
    $ch = curl_init('https://us20.api.mailchimp.com/3.0/lists/'.self::LIST_ID.'/members/');
    curl_setopt_array($ch, array(
      CURLOPT_POST => TRUE,
      CURLOPT_RETURNTRANSFER => TRUE,
      CURLOPT_HTTPHEADER => array(
        'Authorization: apikey '.self::MAILCHIMP_API_KEY,
        'Content-Type: application/json'
      ),
      CURLOPT_POSTFIELDS => json_encode($postData)
    ));

    // Send the request
    $response = curl_exec($ch);
    $readable_response = json_decode($response);
    if($readable_response->status == 403) {
      \Drupal::logger('Mailchimp_subscriber')->error($readable_response->title.': '.$readable_response->detail .'. Raw values:'.print_r($values));
      \Drupal::messenger()->addError('Something went wrong. Please contact your webmaster.');
    }
    if($readable_response->status == 'subscribed') {
      \Drupal::messenger()->addStatus('You are now successfully subscribed.');
    }
    if($readable_response->status == 400) {
      if($readable_response->title == 'Member Exists') {
        \Drupal::messenger()->addWarning('You are already subscribed to this mailing list.');
      }
    }

    return true;
  }
}

Enable the module and clear cache. Now, in your webform back-end, go to settings and then emails / handlers (/admin/structure/webform/manage/<webform_id>/handlers). Add your handler here. 

Drupal 8 webform mailchimp subscription
Add your custom handler to your webform. From now on, all submissions are added to Mailchimp.