更新 mailchimp 电子邮件订阅不起作用

update mailchimp email subscription is not working

下面是我在 Mailchimp 中创建或更新订阅的代码。

function mailchimp_ajax_subscription()
{
    $data = isset( $_POST['formData'] ) ? $_POST['formData'] : array();
    ob_start();
    if(count($data) > 0)
    {

        $api_key = 'XXXXXXXXXXXXXX';
        $status = 'unsubscribed'; // subscribed, unsubscribed, cleaned, pending

            $args = array(
                'method' => 'PUT',
                'headers' => array(
                    'Authorization' => 'Basic ' . base64_encode( 'user:'. $api_key )
                ),
                'body' => json_encode(array(
                    'email_address' => $data["email"],
                    'status'        => $status,
                    'tags'  => array($data["name"])
                ))
            );

            $response = wp_remote_post( 'https://' . substr($api_key,strpos($api_key,'-')+1) . '.api.mailchimp.com/3.0/lists/XXXXX/members/' . md5(strtolower($email)), $args );

            $body = json_decode( $response['body'] );

            if ( $response['response']['code'] == 200 && $body->status == $status ) {
                echo 'The user has been successfully ' . $status . '.';
            } else {
                echo '<b>' . $response['response']['code'] . $body->title . ':</b> ' . $body->detail;
            }

    }
    wp_die();  
}

使用上面的代码,我可以创建对 Mailchimp 的订阅,但是如果我输入相同的电子邮件来编辑 tags/status,它会给我错误。

错误:

400Member Exists: abc@xyz.com is already a list member. Use PUT to insert or update list members.

我已经在代码中使用了 PUT,还缺少什么?

您可以使用 TAGS API 来更新 TAGS。以下是更新 TAG 的示例代码:

$postdata = array(
    'apikey' => $api_key,
    'email_address' => $userData["email"],
    'tags' => array(
        array(
            'name' => $userData["name"],
            'status' => 'active'
        ),
    )
);

$mch_api = curl_init(); // initialize cURL connection 
curl_setopt($mch_api, CURLOPT_URL, 'https://' . substr($api_key,strpos($api_key,'-')+1) . '.api.mailchimp.com/3.0/lists/' . $list_id . '/members/' . md5(strtolower($userData['email']))."/tags"); 
curl_setopt($mch_api, CURLOPT_HTTPHEADER, array('Content-Type: application/json', 'Authorization: Basic '.base64_encode( 'user:'.$api_key ))); 
curl_setopt($mch_api, CURLOPT_RETURNTRANSFER, true); // return the API response 
curl_setopt($mch_api, CURLOPT_TIMEOUT, 10); 
curl_setopt($mch_api, CURLOPT_POST, true); 
curl_setopt($mch_api, CURLOPT_POSTFIELDS, json_encode($postdata) ); // send data in json 
$result = curl_exec($mch_api);