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

时间:2019-07-09 09:36:24

标签: wordpress mailchimp mailchimp-api-v3.0

下面是我在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中创建订阅,但是如果我输入相同的电子邮件来编辑标签/状态,则会出现错误。

错误:

  

400个成员已存在:abc@xyz.com已经是列表成员。使用PUT来   插入或更新列表成员。

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

1 个答案:

答案 0 :(得分:1)

您可以使用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);