Mailchimp API send campaign

Viewed 625

I have written a custom Drupal 8 module that will send article notifications to our Mailchimp subscribers.

Problem

Currently, the module loops over each of the article 'tags' and sends out a separate campaign for each. Consequently, if someone is subscribed two of an article's tags, they will receive two emails.

Solution

Instead, I'd like each person to receive a maximum of one email notification. I think that the best way to achieve this is to create a dynamic segment. Similar to the query posted here. However, I have been getting various errors, and can't find much help here and here.

Code

<?php

function mailchimp_notification_process(EntityInterface $node)
{
    global $base_url;

    $settings = Settings::get('mailchimp_audience');
    $content = (object) array(
        'subject_line' => 'XXX',
        'title' => 'Notification',
        'from_name' => 'XXX',
        'reply_to' => 'noreply@gmail.com'
    );
    $template_content = [
        'html' => [
            'value' => '<table align="center" border="0" cellpadding="0" cellspacing="0" height="100%" width="100%" id="bodyTable">email content removed for brevity</table>',
            'format' => 'mailchimp_campaign'
        ]
    ];

    $mc_campaign = mailchimp_get_api_object('MailchimpCampaigns');
    $lists = mailchimp_campaign_get_list_segments($settings, NULL);

    if (
        $node->isPublished() &&
        ($node->bundle() == 'article' || $node->bundle() == 'resource') &&
        $node->field_send_notification->getString() == 1 &&
        isset($node->field_send_notification_to->entity)
    ) {
        $all_tags = [];

        // loop over each of the loops to send notifications to
        foreach ($node->field_send_notification_to as $category) {
            $tags = array_filter($lists, function ($list) use ($category) {
                return $list->name == $category->entity->getName();
            });

            if ($tags && is_array($tags)) {
                $tags = reset($tags);
                array_push($all_tags, $tags->id);
                \Drupal::logger('mailchimp_notification')->notice('all_tags: ' . json_encode($all_tags));
            }
        }

        $recipients = (object) [
            'list_id' => $settings,
            'segment_opts' => [
                'match' => 'all',
                'conditions' => [
                    [
                        'condition_type' => 'Tags',
                        'field' => 'tags-123',
                        'op' => 'interestcontainsall',
                        'value' => $all_tags,
                    ]
                ]
            ]
        ];

        \Drupal::logger('mailchimp_notification')->notice('recipients: ' . json_encode($recipients));

        $campaign_id = mailchimp_campaign_save_campaign($template_content, $recipients, $content, "", "");

        if ($campaign_id) {
            $mc_campaign->send($campaign_id);
        }
    }
}
0 Answers
Related