Skip to content
mailchimp.module 43.6 KiB
Newer Older
use Drupal\Core\Form\FormStateInterface;
Andy Price's avatar
Andy Price committed
use Drupal\Core\Link;
Andy Price's avatar
Andy Price committed
use function GuzzleHttp\default_user_agent;
use GuzzleHttp\Exception\ClientException;
define('MAILCHIMP_QUEUE_CRON', 'mailchimp');

define('MAILCHIMP_STATUS_SENT', 'sent');
define('MAILCHIMP_STATUS_SAVE', 'save');
define('MAILCHIMP_STATUS_PAUSED', 'paused');
define('MAILCHIMP_STATUS_SCHEDULE', 'schedule');
define('MAILCHIMP_STATUS_SENDING', 'sending');

/**
 * Access callback for mailchimp submodule menu items.
 *
 * @return bool
 *   TRUE if the mailchimp api is available and accessible by the user.
 */
function mailchimp_apikey_ready_access($permission) {
  if (mailchimp_get_api_object() && \Drupal::currentUser()->hasPermission($permission)) {
 * Instantiates a Mailchimp library object.
 * @return \Mailchimp\Mailchimp
 *   Drupal Mailchimp library object.
function mailchimp_get_api_object($classname = 'MailchimpApiUser') {
  $object = \Drupal::service('mailchimp.client_factory')->getByClassNameOrNull($classname);
  if (!$object) {
    \Drupal::messenger()->addError('Failed to load Mailchimp PHP library. Please refer to the installation requirements.');
  $config = \Drupal::config('mailchimp.settings');
  if (!$config->get('test_mode') && !$object->hasApiAccess()) {
Andy Price's avatar
Andy Price committed
    $mc_oauth_url = Url::fromRoute('mailchimp.admin.oauth');
    \Drupal::messenger()->addError(t('Unable to connect to Mailchimp API. Visit @oauth_settings_page to authenticate or uncheck "Use OAuth Authentication" and add an api_key below (deprecated).', ['@oauth_settings_page' => Link::fromTextAndUrl(t('OAuth Settings page'), $mc_oauth_url)->toString()]));
    return NULL;
  }
/**
 * Gets the user agent string for this installation of Mailchimp.
 *
 * @return string
 *   The user agent string.
 */
function _mailchimp_get_user_agent() {
  $version = '8.x-1.x';

  if (\Drupal::moduleHandler()->moduleExists('system')) {
    /** @var \Drupal\Core\Extension\ModuleExtensionList $extension_list */
    $extension_list = \Drupal::service('extension.list.module');
    $info = $extension_list->getExtensionInfo('mailchimp');
    if (!empty($info['version'])) {
      $version = $info['version'];
    }
  }

  $user_agent = "DrupalMailchimp/$version " . default_user_agent();
 * Returns a single list.
 *   The unique ID of the list provided by Mailchimp.
 *   Array of list data.
 * Returns all Mailchimp lists for a given key. Lists are stored in the cache.
 *
 * @param array $list_ids
 *   An array of list IDs to filter the results by.
 * @param bool $reset
 *   Force a cache reset.
 *
 * @return array
 *   An array of list data arrays.
function mailchimp_get_lists(array $list_ids = [], $reset = FALSE) {
  $lists = [];
  $cache = \Drupal::cache('mailchimp');
  $cached_data = $reset ? NULL : $cache->get('lists');

  // Return cached lists.
  if ($cached_data) {
    $lists = $cached_data->data;
      /** @var \Mailchimp\MailchimpLists $mcapi */
      $mcapi = mailchimp_get_api_object('MailchimpLists');
      if ($mcapi != NULL) {
        $result = $mcapi->getLists(['count' => 500]);
        if ($result->total_items > 0) {
          foreach ($result->lists as $list) {
            $int_category_data = $mcapi->getInterestCategories($list->id, ['count' => 500]);
            if ($int_category_data->total_items > 0) {

              foreach ($int_category_data->categories as $interest_category) {
                $interest_data = $mcapi->getInterests($list->id, $interest_category->id, ['count' => 500]);

                if ($interest_data->total_items > 0) {
                  $interest_category->interests = $interest_data->interests;
                }

                $list->intgroups[] = $interest_category;
              }
            $lists[$list->id] = $list;
            // Append mergefields:
            $mergefields = $mcapi->getMergeFields($list->id, ['count' => 500]);
            if ($mergefields->total_items > 0) {
              $lists[$list->id]->mergevars = $mergefields->merge_fields;
            }
      \Drupal::logger('mailchimp')->error('An error occurred requesting list information from Mailchimp. "{message}"', [
        'message' => $e->getMessage(),
      ]);

  // Filter by given IDs.
    foreach ($list_ids as $id) {
      if (array_key_exists($id, $lists)) {
        $filtered_lists[$id] = $lists[$id];
      }
    }
    return $filtered_lists;
  }
  else {
    return $lists;
  }
}

/**
 * Helper function used by uasort() to sort lists alphabetically by name.
 *
 * @param object $a
 *   An object representing the first list.
 * @param object $b
 *   An object representing the second list.
 *
 * @return int
 *   One of the values -1, 0, 1
 */
function _mailchimp_list_cmp($a, $b) {
  if ($a->name == $b->name) {
  return ($a->name < $b->name) ? -1 : 1;
 * Wrapper around MailchimpLists->getMergeFields().
 * @param array $list_ids
 *   Array of Mailchimp list IDs.
 * @param bool $reset
 *   Set to TRUE if mergevars should not be loaded from cache.
 * @return array
 *   Struct describing mergevars for the specified lists.
 */
function mailchimp_get_mergevars(array $list_ids, $reset = FALSE) {
  $mergevars = [];
  $cache = \Drupal::cache('mailchimp');
    foreach ($list_ids as $key => $list_id) {
      $cached_data = $cache->get($list_id . '-mergevars');
      // Get cached data and unset from our remaining lists to query.
      if ($cached_data) {
        $mergevars[$list_id] = $cached_data->data;
        unset($list_ids[$key]);
  // Get the uncached merge vars from Mailchimp.
    /** @var \Mailchimp\MailchimpLists $mc_lists */
    $mc_lists = mailchimp_get_api_object('MailchimpLists');
    $list_id = NULL;
        throw new Exception('Cannot get merge vars without Mailchimp API. Check API key has been entered.');
      }

      foreach ($list_ids as $list_id) {
        // Add default EMAIL merge var for all lists.
            'type' => 'email',
            'required' => TRUE,
            'default_value' => '',
            'public' => TRUE,
            'display_order' => 1,
        $result = $mc_lists->getMergeFields($list_id, ['count' => 500]);

        if ($result->total_items > 0) {
          $mergevars[$list_id] = array_merge($mergevars[$list_id], $result->merge_fields);
        $cache->set($list_id . '-mergevars', $mergevars[$list_id]);
      \Drupal::logger('mailchimp')->error('An error occurred requesting mergevars for list {list}. "{message}"', [
 * Get the Mailchimp member info for a given email address and list.
 * Results are cached in the cache_mailchimp bin which is cleared by the
 * Mailchimp web hooks system when needed.
 * @param string $list_id
 *   The Mailchimp list ID to get member info for.
 * @param string $email
 *   The Mailchimp user email address to load member info for.
 * @param bool $reset
 *   Set to TRUE if member info should not be loaded from cache.
 * @return object
 *   Member info object, empty if there is no valid info.
 */
function mailchimp_get_memberinfo($list_id, $email, $reset = FALSE) {
  $cache = \Drupal::cache('mailchimp');
  if (!$reset) {
    $cached_data = $cache->get($list_id . '-' . $email);
    if ($cached_data) {
      return $cached_data->data;
    }
  // Query lists from the MCAPI and store in cache:
  /** @var \Mailchimp\MailchimpLists $mc_lists */
  $mc_lists = mailchimp_get_api_object('MailchimpLists');
Lev Tsypin's avatar
Lev Tsypin committed
  try {
    if (!$mc_lists) {
      throw new Exception('Cannot get member info without Mailchimp API. Check API key has been entered.');
    }
    $result = $mc_lists->getMemberInfo($list_id, $email);
    if (!empty($result->id)) {
      $memberinfo = $result;
      $cache->set($list_id . '-' . $email, $memberinfo);
    // A 404 exception code means mailchimp does not have subscription
    // information for given email address. This is not an error and we can
    // cache this information.
    if ($e->getCode() == 404) {
      $cache->set($list_id . '-' . $email, $memberinfo);
    }
    else {
      \Drupal::logger('mailchimp')->error('An error occurred requesting memberinfo for {email} in list {list}. "{message}"', [
        'email' => $email,
        'list' => $list_id,
        'message' => $e->getMessage(),
Lev Tsypin's avatar
Lev Tsypin committed
  }
/**
 * Get the marketing permissions for a subscribed member.
 *
 * Simple wrapper around mailchimp_get_memberinfo().
 *
 * @param string $list_id
 *   Unique string identifier for the list on your MailChimp account.
 * @param string $email
 *   Email address to check for on the identified MailChimp List.
 * @param bool $reset
 *   Set to TRUE to ignore the cache. (Used heavily in testing functions.)
 *
 * @return array
 *   An array of marketing permissions, or an empty array if not subscribed
 */
function mailchimp_get_marketing_permissions($list_id, $email, $reset = FALSE) {
  $memberinfo = mailchimp_get_memberinfo($list_id, $email, $reset);
  if (isset($memberinfo->status)
      && $memberinfo->status == MailchimpLists::MEMBER_STATUS_SUBSCRIBED
      && isset($memberinfo->marketing_permissions)) {
    return $memberinfo->marketing_permissions;
  }

  return [];
}

 * Check if the given email is subscribed to the given list.
 * Simple wrapper around mailchimp_get_memberinfo().
 *
 * @param string $list_id
 *   Unique string identifier for the list on your Mailchimp account.
 * @param string $email
 *   Email address to check for on the identified Mailchimp List.
 * @param bool $reset
Gabriel Carleton-Barnes's avatar
Gabriel Carleton-Barnes committed
 *   Set to TRUE to ignore the cache. (Used heavily in testing functions.)
 *   TRUE if subscribed, FALSE otherwise.
function mailchimp_is_subscribed($list_id, $email, $reset = FALSE) {
  $memberinfo = mailchimp_get_memberinfo($list_id, $email, $reset);
  if (isset($memberinfo->status) && $memberinfo->status == MailchimpLists::MEMBER_STATUS_SUBSCRIBED) {
    $subscribed = TRUE;
  }

  return $subscribed;
 * Subscribe a user to a Mailchimp list in real time or by adding to the queue.
function mailchimp_subscribe($list_id, $email, $merge_vars = NULL, $interests = [], $double_optin = FALSE, $format = 'html', $language = NULL, $gdpr_consent = FALSE, $tags = NULL) {
  $config = \Drupal::config('mailchimp.settings');

  if (empty($language)) {
    $language = \Drupal::languageManager()->getCurrentLanguage()->getId();
  }

      'list_id' => $list_id,
      'email' => $email,
      'merge_vars' => $merge_vars,
      'interests' => $interests,
      'format' => $format,
    return mailchimp_addto_queue('mailchimp_subscribe_process', $args);
  }
  return mailchimp_subscribe_process($list_id, $email, $merge_vars, $interests, $double_optin, $format, $language, $gdpr_consent, $tags);
}

/**
 * Wrapper around Mailchimp_Lists::subscribe().
 *
 * @see Mailchimp_Lists::subscribe()
 */
function mailchimp_subscribe_process($list_id, $email, $merge_vars = NULL, $interests = [], $double_optin = FALSE, $format = 'html', $language = NULL, $gdpr_consent = FALSE, $tags = NULL) {
  $config = \Drupal::config('mailchimp.settings');
    /** @var \Mailchimp\MailchimpLists $mc_lists */
    $mc_lists = mailchimp_get_api_object('MailchimpLists');
    if (!$mc_lists) {
      throw new Exception('Cannot subscribe to list without Mailchimp API. Check API key has been entered.');
      // If double opt-in is required, set member status to 'pending'.
      'status' => ($double_optin) ? MailchimpLists::MEMBER_STATUS_PENDING : MailchimpLists::MEMBER_STATUS_SUBSCRIBED,
      'email_type' => $format,
    if (!empty($language)) {
      $parameters['language'] = $language;
    }

    // Set interests.
    if (!empty($interests)) {
      foreach ($interests as $interest_group) {
        // This could happen in case the selected interest group
        // is set to display radio inputs. So we either do an
        // explicit check here, or simply transform the single string
        // value to an array in order to pass the condition check below.
        if (!is_array($interest_group)) {
          $interest_group = [$interest_group => $interest_group];
        }

        foreach ($interest_group as $interest_id => $interest_status) {
          $selected_interests[$interest_id] = ($interest_status !== 0);
        }
      }

      if (!empty($selected_interests)) {
        $parameters['interests'] = (object) $selected_interests;
      }
    }

    // Set merge fields.
    if (!empty($merge_vars)) {
      $parameters['merge_fields'] = (object) $merge_vars;
    }

    // Has GDPR consent been given?
    if ($gdpr_consent) {
      // If the member is already subscribed get the marketing permission id(s)
      // for the list and enable them.
      $marketing_permissions = mailchimp_get_marketing_permissions($list_id, $email);
      $was_subscribed        = FALSE;
      if ($marketing_permissions) {
        foreach ($marketing_permissions as $marketing_permission) {
          $parameters['marketing_permissions'][] = [
            'marketing_permission_id' => $marketing_permission->marketing_permission_id,
            'enabled'                 => TRUE,
          ];
        }
        $was_subscribed = TRUE;
      }
    }
    else {
      // We need to make sure this is set.
      $was_subscribed = FALSE;
    }
    // Add member to list.
    $result = $mc_lists->addOrUpdateMember($list_id, $email, $parameters);
    if (isset($result->id)) {
      \Drupal::moduleHandler()->invokeAll('mailchimp_subscribe_success', [
        $list_id,
        $email,
        $merge_vars,
      ]);
      // Clear user cache, just in case there's some cruft leftover:
      \Drupal::logger('mailchimp')->notice('{email} was subscribed to list {list}.', [
        'list' => $list_id,

      // For newly subscribed members set GDPR consent if it's been given.
      if (!$was_subscribed && $gdpr_consent && !empty($result->marketing_permissions)) {
        // If the member is already subscribed get the marketing permission
        // id(s) for the list and enable them.
        foreach ($result->marketing_permissions as $marketing_permission) {
          $parameters['marketing_permissions'][] = [
            'marketing_permission_id' => $marketing_permission->marketing_permission_id,
            'enabled'                 => TRUE,
          ];
        }
        $result = $mc_lists->addOrUpdateMember($list_id, $email, $parameters);
        if (!isset($result->id)) {
          \Drupal::logger('mailchimp')
            ->warning('A problem occurred setting marketing permissions for {email} on list {list}.', [
              'email' => $email,
              'list'  => $list_id,
        $msg = $config->get('optin_check_email_msg');
        if ($msg) {
          \Drupal::messenger()->addStatus($msg, FALSE);
        }
Andy Price's avatar
Andy Price committed
        $tags = explode(',', (string) $tags);
        $tags = array_map('trim', $tags);

        try {
          $mc_lists->addTagsMember($list_id, $tags, $email);
        }

        catch (ClientException $e) {
          \Drupal::logger('mailchimp')->error('An error occurred while adding tags for this email({email}) to Mailchimp: {message}', [
            'message' => $e->getMessage(),
            'email' => $email,
          ]);
        }
      }
        \Drupal::logger('mailchimp')->warning('A problem occurred subscribing {email} to list {list}.', [
          'email' => $email,
          'list' => $list_id,
    if ($e->getCode() == '400' && strpos($e->getMessage(), 'Member In Compliance State') !== FALSE && !$double_optin) {
      \Drupal::logger('mailchimp')->error('Detected "Member In Compliance State" subscribing {email} to list {list}. Trying again using double-opt in.', [
      return mailchimp_subscribe_process($list_id, $email, $merge_vars, $interests, TRUE, $format, $language, $gdpr_consent, $tags);
    \Drupal::logger('mailchimp')->error('An error occurred subscribing {email} to list {list}. "{message}"', [
      'email' => $email,
      'list' => $list_id,
      'message' => $e->getMessage(),
 * Adds a Mailchimp subscription task to the queue.
 * @param string $function
 *   The name of the function the queue runner should call.
 * @param array $args
 * @return mixed
 *   Unique ID if item is successfully added to the queue, FALSE otherwise.
function mailchimp_addto_queue($function, array $args) {
  $queue = \Drupal::queue(MAILCHIMP_QUEUE_CRON);
/**
 * Update a members list subscription in real time or by adding to the queue.
 *
 * @see Mailchimp_Lists::updateMember()
 */
function mailchimp_update_member($list_id, $email, $merge_vars, $interests = [], $format = 'html', $double_optin = FALSE, $gdpr_consent = FALSE, $tags = NULL) {
  $config = \Drupal::config('mailchimp.settings');

  if ($config->get('cron')) {
      'list_id' => $list_id,
      'email' => $email,
      'merge_vars' => $merge_vars,
      'interests' => $interests,
    return mailchimp_addto_queue('mailchimp_update_member_process', $args);
  return mailchimp_update_member_process($list_id, $email, $merge_vars, $interests, $format, $double_optin, $gdpr_consent, $tags);
function mailchimp_update_member_process($list_id, $email, $merge_vars, $interests, $format, $double_optin = FALSE, $gdpr_consent = FALSE, $tags = NULL) {
  $config = \Drupal::config('mailchimp.settings');
    /** @var \Mailchimp\MailchimpLists $mc_lists */
    $mcapi = mailchimp_get_api_object('MailchimpLists');

      'status' => ($double_optin) ? MailchimpLists::MEMBER_STATUS_PENDING : MailchimpLists::MEMBER_STATUS_SUBSCRIBED,
      'email_type' => $format,

    // Set interests.
    if (!empty($interests)) {
      foreach ($interests as $interest_group) {
        foreach ($interest_group as $interest_id => $interest_status) {
          $selected_interests[$interest_id] = ($interest_status !== 0);
        }
      }

      if (!empty($selected_interests)) {
        $parameters['interests'] = (object) $selected_interests;
      }
    }

    // Set merge fields.
    if (!empty($merge_vars)) {
      $parameters['merge_fields'] = (object) $merge_vars;
    }
    // Has GDPR consent been given?
    if ($gdpr_consent) {
      // If the member is already subscribed get the marketing permission id(s)
      // for the list and enable them.
      $marketing_permissions = mailchimp_get_marketing_permissions($list_id, $email);
      if ($marketing_permissions) {
        foreach ($marketing_permissions as $marketing_permission) {
          $parameters['marketing_permissions'][] = [
            'marketing_permission_id' => $marketing_permission->marketing_permission_id,
            'enabled'                 => TRUE,
          ];
        }
      }
    }
    // Update member.
    $result = $mcapi->updateMember($list_id, $email, $parameters);

    if (isset($result->id)) {
      \Drupal::logger('mailchimp')->notice('{email} was updated in list {list_id}.', [
        'email' => $email,
        'list' => $list_id,
      // Clear user cache:
      mailchimp_cache_clear_member($list_id, $email);
      \Drupal::logger('mailchimp')->warning('A problem occurred updating {email} on list {list}.', [
        'email' => $email,
        'list' => $list_id,
    if ($e->getCode() == '400' && strpos($e->getMessage(), 'Member In Compliance State') !== FALSE && !$double_optin) {
      \Drupal::logger('mailchimp')->error('Detected "Member In Compliance State" subscribing {email} to list {list}.  Trying again using double-opt in.', [
      return mailchimp_update_member_process($list_id, $email, $merge_vars, $interests, $format, TRUE, $gdpr_consent, $tags);
    \Drupal::logger('mailchimp')->error('An error occurred updating {email} on list {list}. "{message}"', [
      'email' => $email,
      'list' => $list_id,
      'message' => $e->getMessage(),
    $msg = $config->get('optin_check_email_msg');
    if ($msg) {
      \Drupal::messenger()->addStatus($msg, FALSE);
    }
  // Add or update member tags
  if ($tags) {
    $tags = explode(',', (string) $tags);
    $tags = array_map('trim', $tags);

    try {
      $mcapi->addTagsMember($list_id, $tags, $email);
    }

    catch (ClientException $e) {
      \Drupal::logger('mailchimp')->error('An error occurred while adding tags for this email({email}) to Mailchimp: {message}', [
        'message' => $e->getMessage(),
        'email' => $email,
      ]);
    }
  }

/**
 * Retrieve all members of a given list with a given status.
 *
 * Note that this function can cause locking an is somewhat slow. It is not
 * recommended unless you know what you are doing! See the MCAPI documentation.
 */
function mailchimp_get_members($list_id, $status = MailchimpLists::MEMBER_STATUS_SUBSCRIBED, $options = []) {

  $lock = \Drupal::lock();

  if ($lock->acquire('mailchimp_get_members', 60)) {
      /** @var \Mailchimp\MailchimpLists $mcapi */
      $mcapi = mailchimp_get_api_object('MailchimpLists');

      $options['status'] = $status;
      $results = $mcapi->getMembers($list_id, $options);
      \Drupal::logger('mailchimp')->error('An error occurred pulling member info for a list. "{message}"', [
        'message' => $e->getMessage(),
      ]);

    $lock->release('mailchimp_get_members');
 * Batch updates a number of Mailchimp list members.
 * @see Mailchimp_Lists::batchSubscribe()
function mailchimp_batch_update_members($list_id, $batch) {
    /** @var \Mailchimp\MailchimpLists $mc_lists */
    $mc_lists = mailchimp_get_api_object('MailchimpLists');
    if (!$mc_lists) {
      throw new Exception('Cannot batch subscribe to list without Mailchimp API. Check API key has been entered.');
    }

    if (!empty($batch)) {
      // Create a new batch update operation for each member.
      foreach ($batch as $batch_data) {
        // @todo Remove 'advanced' earlier? Needed at all?
        unset($batch_data['merge_vars']['advanced']);

          'email_type' => $batch_data['email_type'],
          'merge_fields' => (object) $batch_data['merge_vars'],

        $mc_lists->addOrUpdateMember($list_id, $batch_data['email'], $parameters, TRUE);
      }

      // Process batch operations.
      return $mc_lists->processBatchOperations();
    }
    \Drupal::logger('mailchimp')->error('An error occurred performing batch subscribe/update. "{message}"', [
      'message' => $e->getMessage(),
    ]);
 * Unsubscribes a member from a Mailchimp list.
 * @see Mailchimp_Lists::unsubscribe()
function mailchimp_unsubscribe($list_id, $email) {
  $config = \Drupal::config('mailchimp.settings');


  if (mailchimp_is_subscribed($list_id, $email)) {
      $result = mailchimp_addto_queue(
        'mailchimp_unsubscribe_process',
          'list_id' => $list_id,
          'email' => $email,
      $result = mailchimp_unsubscribe_process($list_id, $email);
 * Unsubscribes a member from a Mailchimp list.
 *
 * @see Mailchimp_Lists::unsubscribe()
 */
function mailchimp_unsubscribe_process($list_id, $email) {
    /** @var \Mailchimp\MailchimpLists $mc_lists */
    $mc_lists = mailchimp_get_api_object('MailchimpLists');
    if (!$mc_lists) {
      throw new Exception('Cannot unsubscribe from list without Mailchimp API. Check API key has been entered.');
    $mc_lists->updateMember($list_id, $email, ['status' => MailchimpLists::MEMBER_STATUS_UNSUBSCRIBED]);
    \Drupal::moduleHandler()->invokeAll('mailchimp_unsubscribe_success', [
      $list_id,
      $email,
    ]);
    // Clear user cache:
    mailchimp_cache_clear_member($list_id, $email);
    \Drupal::logger('mailchimp')->error('An error occurred unsubscribing {email} from list {list}. "{message}"', [
      'email' => $email,
      'list' => $list_id,
      'message' => $e->getMessage(),
 * Wrapper function to return data for a given campaign.
 * Data is stored in the Mailchimp cache.
 * @param string $campaign_id
 *   The ID of the campaign to get data for.
 * @param bool $reset
 *   Set to TRUE if campaign data should not be loaded from cache.
 *
 * @return mixed
 *   Array of campaign data or FALSE if not found.
 */
function mailchimp_get_campaign_data($campaign_id, $reset = FALSE) {
  $cache = \Drupal::cache('mailchimp');
  $campaign_data = FALSE;

  if (!$reset) {
    $cached_data = $cache->get('campaign_' . $campaign_id);
    if ($cached_data) {
      return $cached_data->data;
    }
Lev Tsypin's avatar
Lev Tsypin committed

  try {
    /** @var \Mailchimp\MailchimpCampaigns $mcapi */
    $mcapi = mailchimp_get_api_object('MailchimpCampaigns');
    $response = $mcapi->getCampaign($campaign_id);
    if (!empty($response->id)) {
      $campaign_data = $response;
      $cache->set('campaign_' . $campaign_id, $campaign_data);
    \Drupal::logger('mailchimp')->error('An error occurred retrieving campaign data for {campaign}. "{message}"', [
      'campaign' => $campaign_id,
      'message' => $e->getMessage(),
Lev Tsypin's avatar
Lev Tsypin committed
  }
/**
 * Returns all lists a given email address is currently subscribed to.
 *
 * @param string $email
 *   Email address to search.
 *
 * @return array
 *   Campaign structs containing id, web_id, name.
 */
function mailchimp_get_lists_for_email($email) {
  try {
    /** @var \Mailchimp\MailchimpLists $mcapi */
    $mcapi = mailchimp_get_api_object('MailchimpLists');
    $lists = $mcapi->getListsForEmail($email);
    \Drupal::logger('mailchimp')->error('An error occurred retreiving lists data for {email}. "{message}"', [
      'email' => $email,
      'message' => $e->getMessage(),
 * Returns all webhooks for a given Mailchimp list ID.
 * @see Mailchimp_Lists::webhooks()
Dan Ruscoe's avatar
Dan Ruscoe committed
function mailchimp_webhook_get($list_id) {
  try {
    /** @var \Mailchimp\MailchimpLists $mc_lists */
Dan Ruscoe's avatar
Dan Ruscoe committed
    $mc_lists = mailchimp_get_api_object('MailchimpLists');
    $result = $mc_lists->getWebhooks($list_id);

    return ($result->total_items > 0) ? $result->webhooks : FALSE;
  }
    \Drupal::logger('mailchimp')->error('An error occurred reading webhooks for list {list}. "{message}"', [
Dan Ruscoe's avatar
Dan Ruscoe committed
      'list' => $list_id,
      'message' => $e->getMessage(),
Dan Ruscoe's avatar
Dan Ruscoe committed

    return FALSE;
  }
}
 * Adds a webhook to a Mailchimp list.
 * @param string $list_id
 *   The Mailchimp list ID to add a webhook for.
 * @param string $url
 *   The URL of the webhook endpoint.
 * @param array $events
 *   Associative array of events action to bool, indicating enabled status.
 * @param array $sources
 *   Associative array of source name to bool, indicating source status.
 *
 * @return string
 *   The ID of the new webhook.
function mailchimp_webhook_add($list_id, $url, array $events = [], array $sources = []) {
    /** @var \Mailchimp\MailchimpLists $mc_lists */
    $mc_lists = mailchimp_get_api_object('MailchimpLists');