简体   繁体   English

如何在MailChimp API 3中更新现有订户的段和组

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

Iv'e written a method to subscribe users to MailChimp. 我写了一个方法来订阅用户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. 与MailChimp的集成是直截了当的 - 我得到数据>发送curl>获取响应>处理响应。

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'. 现在,MailChimp可以获得的唯一接受状态是“订阅”,“待定”和“清理”。 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. 如果电子邮件已经订阅,则不会更新任何内容,甚至不会更新与订阅者在其MailChimp列表中的配置文件中所拥有的数据不同的数据。

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);
}

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. 如果您的集成按预期添加了全新的订阅者,并且该问题在该方法更新现有子记录的情况下显得孤立,则该问题可能与HTTP方法和/或api端点有关。

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. 由于MailChimp API的v3仅允许在使用POST方法时初始化订阅者(这看起来可能在此处硬编码到cURL中),并且可能是为什么全新订阅者被添加而没有问题。

This said, when wanting to add or update new subscribers using PUT would be recommended, and is specified in their docs. 这就是说,当想要使用PUT添加或更新新订户时,建议使用,并在其文档中指定。

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. 此外,除了这种替代方法的使用,为了确保更新现有订户,您还需要将其电子邮件小写版本的MD5哈希附加到端点。 This only needs to be done for existing subs. 这只需要对现有的潜艇进行。

eg /members/{lowercase_email_MD5_hash} 例如/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. 如果您首先使用MailChimp检查是否存在订户,如果​​您想要回收该订户,则应在响应中提供。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM