如何在php中使用API调用添加电子邮件地址到mailchimp列表


how to add email address to mailchimp list using api call in php

我是mailchimp的新手。刚才我已经创建了帐户并获得了API密钥。我已经通过他们的API将电子邮件地址添加到列表中,但没有帮助。

我有联系我们的形式,当用户点击提交按钮,我想在我的mailchimp数据库中添加用户的电子邮件id。

我也试过这个代码,但得到104错误…

  $apikey = '***********-us3';
                $listID = '*******';
                $email = "********";
                $url = sprintf('https://us2.api.mailchimp.com/2.0/lists/subscribe&apikey=%s&id=%s&email_address=%s&output=json', $apikey, $listID, $email, $_SERVER['REMOTE_ADDR']);
                $ch = curl_init($url);
                curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
                $data = curl_exec($ch);
                $arr = json_decode($data, true);
                curl_close($ch);
        if ($arr == 1) {
            echo 'Check now your e-mail and confirm your subsciption.';
        } else {
                            echo $arr['code'];
            switch ($arr['code']) {
                case 214:
                echo 'You are already subscribed.';
                break;
                // check the MailChimp API for more options
                default:
                echo 'Unkown error...';
                break;          
            }
        }
谁能告诉我如何实现它?

Thanks in advance

mailchimp在https://bitbucket.org/mailchimp/mailchimp-api-php上提供了一个PHP包装器,这使得生活变得非常容易。

这里发生的问题似乎是您正在执行GET而不是POST

$apikey = '**********-us3';
$listID = '******';
$email  = "**************";
$fields = array('apikey' => urlencode($apikey), 'id' => urlencode($listID), 'email_address' => urlencode($email), 'output' => 'json' );
foreach($fields as $key=>$value) { $fields_string .= $key.'='.$value.'&'; }
rtrim($fields_string, '&');
$url = 'https://us2.api.mailchimp.com/2.0/lists/subscribe';
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch,CURLOPT_URL, $url);
curl_setopt($ch,CURLOPT_POST, count($fields));
curl_setopt($ch,CURLOPT_POSTFIELDS, $fields_string);
$data = curl_exec($ch);
$arr = json_decode($data, true);
curl_close($ch);
if ($arr == 1) {
    echo 'Check now your e-mail and confirm your subsciption.';
} else {
                    echo $arr['code'];
    switch ($arr['code']) {
        case 214:
        echo 'You are already subscribed.';
        break;
        // check the MailChimp API for more options
        default:
        echo 'Unkown error...';
        break;          
    }
}

让我知道这是否有帮助。如果没有,我可以试着自己设置一些东西,这样我就可以测试一些代码了。

还有另一个流行的简单APIhttps://github.com/drewm/mailchimp-api

use 'DrewM'MailChimp'MailChimp;
$MailChimp = new MailChimp('abc123abc123abc123abc123abc123-us1');
$list_id = 'b1234346';
$result = $MailChimp->post("lists/$list_id/members", [
                'email_address' => 'davy@example.com',
                'status'        => 'subscribed',
            ]);
print_r($result);