我想把用户添加到我在Mailchimp创建的列表中,但我无法在任何地方找到代码示例。我尝试弄清楚如何使用API,但我非常希望能够“查看示例并学习”。
我尝试使用API的2.0版本,但是尽管从网上和Mailchimp的示例中工作,但似乎什么也不起作用,而且Mailchimp在其网站上关于早期版本API的说明如下:
2.0版本及更早版本已过时。对于这些版本,只提供最低限度的支持 - bug修复,安全补丁。
更新1:根据TooMuchPete的答案有关管理订阅者链接的进一步研究,我修改了一些代码,我在这里找到了一些代码,但它不起作用,因为函数http_build_query()不能处理嵌套数组。我不确定如何处理添加订阅者的'merge_fields'部分。我的当前代码如下:
$postdata = http_build_query(
array(
'apikey' => $apikey,
'email_address' => $email,
'status' => 'subscribed',
'merge_fields' => array(
'FNAME' => $name
)
)
);
$opts = array('http' =>
array(
'method' => 'POST',
'header' => 'Content-type: application/x-www-form-urlencoded',
'content' => $postdata
)
);
$context = stream_context_create($opts);
$result = file_get_contents('https://us2.api.mailchimp.com/3.0/lists/<list_id>/members/', false, $context);
var_dump($result);
die('Mailchimp executed');
更新2:我现在已经转而使用curl,并成功地实现了几乎可以工作的内容。数据已通过发送至Mailchimp,但是我收到了错误"Your request did not include an API key."。我猜测我需要进行身份验证,就像在这里所提到的一样。我尝试将其添加到HTTP头中,但并没有起作用。请参见下面的代码:
$apikey = '<api_key>';
$auth = base64_encode( 'user:'.$apikey );
$data = array(
'apikey' => $apikey,
'email_address' => $email,
'status' => 'subscribed',
'merge_fields' => array(
'FNAME' => $name
)
);
$json_data = json_encode($data);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://us2.api.mailchimp.com/3.0/lists/<list_id>/members/');
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json/r/n
Authorization: Basic '.$auth));
curl_setopt($ch, CURLOPT_USERAGENT, 'PHP-MCAPI/2.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_data);
$result = curl_exec($ch);
var_dump($result);
die('Mailchimp executed');