PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Tuesday, September 6, 2022

[FIXED] How to update segments and groups of an existing subscriber in MailChimp API 3

 September 06, 2022     mailchimp, mailchimp-api-v3.0, php     No comments   

Issue

Iv'e written a method to subscribe users to MailChimp. Whats 'special' about it is that it automatically subscribe the users to groups within the list, and segments within the list, based on the users' cart items, wishlist items, and the item and / or category that he has subscribed from.

The integration with MailChimp is straight forward - I get the data > send curl > get response > handle response.

I'm looking for a way to constant update the users' groups and segments, based on their actions in my store.

Now, the only accepted statuses MailChimp can get are 'subscribed', 'pending', and 'clean'. All of them aren't updating, only inserting new subscribers. If the email is already subscribed, nothing is being updated, not even data that is different than what the subscriber has in its profile in my MailChimp lists.

Here's my code for reference:

    protected static function subscribeToMailchimp($email, $fullname)
{
    $params     = EkerbaseJoomla::getPluginParams('system', 'ekerbaseusers');
    $interests  = self::getUserInterestsObject();

    $apikey                 = $params->mailChimpApiKey;
    $listId                 = $params->mailChimpListId;
    $interestCategoryId     = $params->mailChimpInterestCategoryId;

    $auth                   = base64_encode( 'user:' . $apikey );
    $apiUrl                 = 'https://'.substr($params->mailChimpApiKey, -3).'.api.mailchimp.com/3.0/lists/'.$listId;
    $possibleGroups         = json_decode(file_get_contents($apiUrl . '/interest-categories/' . $interestCategoryId . '/interests?apikey=' . $apikey))->interests;
    $segments               = json_decode(file_get_contents($apiUrl . '/segments?apikey=' . $apikey))->segments;

    $data = [
        'apikey'            => $apikey,
        'email_address'     => $email,
        'status'            => 'subscribed',
        'merge_fields'      =>
            [
                'FNAME'     => $fullname
            ]
    ];

    if( ! empty($interests->categories) ) {

        $data['interests'] = [];

        foreach( $possibleGroups as $group ) {

            if( in_array($group->name, $interests->categories) ) {
                $data['interests'][$group->id] = true;
            }

        }

    }

    if( ! empty($interests->items) ) {

        $data['segments'] = [];

        foreach( $segments as $segment ) {

            if( in_array($segment->name, $interests->items) ) {
                $data['segments'][$segment->id] = true;
            }

        }

    }

    $ch = curl_init();

    curl_setopt($ch, CURLOPT_URL, $apiUrl . '/members/');
    curl_setopt($ch, CURLOPT_HTTPHEADER,
        [
            'Content-Type: application/json',
            'Authorization: Basic '.$auth
        ]
    );

    curl_setopt($ch, CURLOPT_USERAGENT, 'PHP-MCAPI/3.0');
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_TIMEOUT, 10);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));

    $result     = curl_exec($ch);
    $response   = json_decode($result);

    switch( $response->status ) {

        case 'subscribed':
            $responseMessage = JText::_('EKERBASE_SUCCESS_NEWSLETTER');
            $responseStatus  = 'success';
            $responseResult  = 'mailchimp subscribing succeeded';
            break;

        default:

            $responseStatus  = 'error';
            $responseMessage = $response->title;
            $responseResult  = 'mailchimp subscribing failed';

            if( $response->title === 'Member Exists' ) {
                $responseMessage = JText::_('EKERBASE_NEWSLETTER_ALREADY_SUBSCRIBER');
            }

            break;

    }

    return EkerbaseAjax::buildJsonResponse($responseMessage, $responseStatus, $responseResult);
}

Solution

If your integration is adding entirely new subscriber as expected, and the issue appears isolated to cases where the method is updating an existing sub's record, the issue may pertain to the HTTP method, and/or the api endpoint.

As v3 of MailChimp's API only allows subscribers to be initialized when using the POST method(which looks like it may be hard coded into cURL here), and is likely why entirely new subscribers are being added without issue.

This said, when wanting to add or update new subscribers using PUT would be recommended, and is specified in their docs.

  • Add or update a list member
  • more on http methods and their API

Additionally, along with this alternate method usage, to ensure existing subscribers are updated, you'll also need to append the MD5 hash of the lower case version of their email to to the endpoint. This only needs to be done for existing subs.

e.g. /members/{lowercase_email_MD5_hash}

Which should be provided in the response if you're first checking with MailChimp whether or not a subscriber exist, if you'd like to recycle that.



Answered By - Stu
Answer Checked By - David Goodson (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing