使用Mailchimp的API v3将订阅者添加到列表中

我正在尝试将用户添加到我在Mailchimp中创build的列表中,但无法在任何地方find任何代码示例。 我已经尝试搞清楚如何使用API​​,但我非常“看一个例子,学习”类人。

我已经尝试使用API​​的版本2,但似乎没有任何工作,尽pipe从网上的例子工作,Mailchimp说,他们的网站上API的早期版本以下:

版本2.0和更早版本已被弃用。 这些版本只有最小的支持错误修复程序和安全修补程序。

更新1 :我基于TooMuchPete关于pipe理订阅者的链接进行了一些进一步的研究,并且修改了我在这里find的一些代码,但是它不起作用,因为函数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,但我收到错误“您的请求不包括API密钥”。 我猜我需要validation如上所述。 我试着把它添加到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'); 

基于列表成员实例文档 ,最简单的方法是使用PUT请求,根据文档“添加新的列表成员或更新列表中的成员,如果电子邮件已经存在”

此外apikey绝对不是JSON模式的一部分,将它包含在你的json请求中没有意义。

另外,正如在@ TooMuchPete的评论中指出的,你可以使用CURLOPT_USERPWD来进行基本的httpauthentication,如下所示。

我正在使用下面的函数来添加和更新列表成员。 根据您的列表参数,您可能需要包含一些稍微不同的merge_fields

 $data = [ 'email' => 'johndoe@example.com', 'status' => 'subscribed', 'firstname' => 'john', 'lastname' => 'doe' ]; syncMailchimp($data); function syncMailchimp($data) { $apiKey = 'your api key'; $listId = 'your list id'; $memberId = md5(strtolower($data['email'])); $dataCenter = substr($apiKey,strpos($apiKey,'-')+1); $url = 'https://' . $dataCenter . '.api.mailchimp.com/3.0/lists/' . $listId . '/members/' . $memberId; $json = json_encode([ 'email_address' => $data['email'], 'status' => $data['status'], // "subscribed","unsubscribed","cleaned","pending" 'merge_fields' => [ 'FNAME' => $data['firstname'], 'LNAME' => $data['lastname'] ] ]); $ch = curl_init($url); curl_setopt($ch, CURLOPT_USERPWD, 'user:' . $apiKey); curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json']); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_TIMEOUT, 10); curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'PUT'); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); curl_setopt($ch, CURLOPT_POSTFIELDS, $json); $result = curl_exec($ch); $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE); curl_close($ch); return $httpCode; } 

我得到了它的工作。 我错误地将身份validation添加到头:

 $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', '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'); 

这些都是很好的答案,但从完整的答案中分离出来,你将如何得到一个表单来发送数据和处理这个响应。 这将演示如何通过jquery .ajax()从HTML页面将成员添加到API的v3.0列表中。

在Mailchimp中:

  1. 获取您的API密钥和列表ID
  2. 确保你设置了你的列表和你想使用的自定义字段。 在这种情况下,我已经将API设置为列表中的一个自定义字段。
  3. 查看将文档添加到列表的API文档 。 我们正在使用需要使用HTTP POST请求的create方法。 如果你想修改/删除子目录,在这里还有其他的选项需要PUT

HTML:

 <form id="pfb-signup-submission" method="post"> <div class="sign-up-group"> <input type="text" name="pfb-signup" id="pfb-signup-box-fname" class="pfb-signup-box" placeholder="First Name"> <input type="text" name="pfb-signup" id="pfb-signup-box-lname" class="pfb-signup-box" placeholder="Last Name"> <input type="email" name="pfb-signup" id="pfb-signup-box-email" class="pfb-signup-box" placeholder="youremail@example.com"> <input type="text" name="pfb-signup" id="pfb-signup-box-zip" class="pfb-signup-box" placeholder="Zip Code"> </div> <input type="submit" class="submit-button" value="Sign-up" id="pfb-signup-button"></a> <div id="pfb-signup-result"></div> </form> 

关键的东西:

  1. 给你的<form>一个唯一的ID,不要忘记method="post"属性,这样表单就可以工作。
  2. 注意最后一行#signup-result是您将存放PHP脚本反馈的地方。

PHP:

 <?php /* * Add a 'member' to a 'list' via mailchimp API v3.x * @ http://developer.mailchimp.com/documentation/mailchimp/reference/lists/members/#create-post_lists_list_id_members * * ================ * BACKGROUND * Typical use case is that this code would get run by an .ajax() jQuery call or possibly a form action * The live data you need will get transferred via the global $_POST variable * That data must be put into an array with keys that match the mailchimp endpoints, check the above link for those * You also need to include your API key and list ID for this to work. * You'll just have to go get those and type them in here, see README.md * ================ */ // Set API Key and list ID to add a subscriber $api_key = 'your-api-key-here'; $list_id = 'your-list-id-here'; /* ================ * DESTINATION URL * Note: your API URL has a location subdomain at the front of the URL string * It can vary depending on where you are in the world * To determine yours, check the last 3 digits of your API key * ================ */ $url = 'https://us5.api.mailchimp.com/3.0/lists/' . $list_id . '/members/'; /* ================ * DATA SETUP * Encode data into a format that the add subscriber mailchimp end point is looking for * Must include 'email_address' and 'status' * Statuses: pending = they get an email; subscribed = they don't get an email * Custom fields go into the 'merge_fields' as another array * More here: http://developer.mailchimp.com/documentation/mailchimp/reference/lists/members/#create-post_lists_list_id_members * ================ */ $pfb_data = array( 'email_address' => $_POST['emailname'], 'status' => 'pending', 'merge_fields' => array( 'FNAME' => $_POST['firstname'], 'LNAME' => $_POST['lastname'], 'ZIPCODE' => $_POST['zipcode'] ), ); // Encode the data $encoded_pfb_data = json_encode($pfb_data); // Setup cURL sequence $ch = curl_init(); /* ================ * cURL OPTIONS * The tricky one here is the _USERPWD - this is how you transfer the API key over * _RETURNTRANSFER allows us to get the response into a variable which is nice * This example just POSTs, we don't edit/modify - just a simple add to a list * _POSTFIELDS does the heavy lifting * _SSL_VERIFYPEER should probably be set but I didn't do it here * ================ */ curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_USERPWD, 'user:' . $api_key); curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json')); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_TIMEOUT, 10); curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_POSTFIELDS, $encoded_pfb_data); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); $results = curl_exec($ch); // store response $response = curl_getinfo($ch, CURLINFO_HTTP_CODE); // get HTTP CODE $errors = curl_error($ch); // store errors curl_close($ch); // Returns info back to jQuery .ajax or just outputs onto the page $results = array( 'results' => $result_info, 'response' => $response, 'errors' => $errors ); // Sends data back to the page OR the ajax() in your JS echo json_encode($results); ?> 

关键的东西:

  1. CURLOPT_USERPWD处理API密钥,Mailchimp并没有真正显示你如何做到这一点。
  2. CURLOPT_RETURNTRANSFER以这种方式给我们提供了响应,我们可以使用.ajax() success处理程序将其发送回HTML页面。
  3. 对收到的数据使用json_encode

JS:

 // Signup form submission $('#pfb-signup-submission').submit(function(event) { event.preventDefault(); // Get data from form and store it var pfbSignupFNAME = $('#pfb-signup-box-fname').val(); var pfbSignupLNAME = $('#pfb-signup-box-lname').val(); var pfbSignupEMAIL = $('#pfb-signup-box-email').val(); var pfbSignupZIP = $('#pfb-signup-box-zip').val(); // Create JSON variable of retreived data var pfbSignupData = { 'firstname': pfbSignupFNAME, 'lastname': pfbSignupLNAME, 'email': pfbSignupEMAIL, 'zipcode': pfbSignupZIP }; // Send data to PHP script via .ajax() of jQuery $.ajax({ type: 'POST', dataType: 'json', url: 'mailchimp-signup.php', data: pfbSignupData, success: function (results) { $('#pfb-signup-box-fname').hide(); $('#pfb-signup-box-lname').hide(); $('#pfb-signup-box-email').hide(); $('#pfb-signup-box-zip').hide(); $('#pfb-signup-result').text('Thanks for adding yourself to the email list. We will be in touch.'); console.log(results); }, error: function (results) { $('#pfb-signup-result').html('<p>Sorry but we were unable to add you into the email list.</p>'); console.log(results); } }); }); 

关键的东西:

  1. JSON数据非常敏感的传输。 在这里,我把它放入一个数组,它看起来很容易。 如果您遇到问题,可能是因为您的JSON数据的结构。 看一下这个!
  2. 您的JSON数据的键将成为您在PHP _POST全局variables中引用的内容。 在这种情况下,它将是_POST['email']_POST['firstname']等等。但是你可以任意命名它们 – 只要记住你的JSON传输的data部分的关键是你如何访问他们在PHP中。
  3. 这显然需要jQuery;)

批量加载 – 好的,所以在我之前的回复被删除了,只是使用链接,我更新了代码,我设法得到工作。 欣赏任何人简化/改正/提炼/放入function等我还在学习这东西,但我有批处理成员列表添加工作:)

 $apikey = "whatever-us99"; $list_id = "12ab34dc56"; $email1 = "jack@email.com"; $fname1 = "Jack"; $lname1 = "Black"; $email2 = "jill@email.com"; $fname2 = "Jill"; $lname2 = "Hill"; $auth = base64_encode( 'user:'.$apikey ); $data1 = array( "apikey" => $apikey, "email_address" => $email1, "status" => "subscribed", "merge_fields" => array( 'FNAME' => $fname1, 'LNAME' => $lname1, ) ); $data2 = array( "apikey" => $apikey, "email_address" => $email2, "status" => "subscribed", "merge_fields" => array( 'FNAME' => $fname2, 'LNAME' => $lname2, ) ); $json_data1 = json_encode($data1); $json_data2 = json_encode($data2); $array = array( "operations" => array( array( "method" => "POST", "path" => "/lists/$list_id/members/", "body" => $json_data1 ), array( "method" => "POST", "path" => "/lists/$list_id/members/", "body" => $json_data2 ) ) ); $json_post = json_encode($array); $ch = curl_init(); $curlopt_url = "https://us99.api.mailchimp.com/3.0/batches"; curl_setopt($ch, CURLOPT_URL, $curlopt_url); curl_setopt($ch, CURLOPT_HTTPHEADER, array('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_post); print_r($json_post . "\n"); $result = curl_exec($ch); var_dump($result . "\n"); print_r ($result . "\n"); 

V2.0仍然有效。 v1.3实际上也是 – 但是如果你正在寻找API v3.0的例子,我会检查一下这个GitHub仓库 。 它现在只有Python,但这可能足以让你指出你的语言正确的方向。

在pipe理订阅者的文档中还有一个页面,这与实际的代码示例相距甚远,但可能仍然有帮助。

如果您想使用Mailchimp API在列表上运行批量订阅 。 那么你可以使用下面的函数。

  /** * Mailchimp API- List Batch Subscribe added function * * @param array $data Passed you data as an array format. * @param string $apikey your mailchimp api key. * * @return mixed */ function batchSubscribe(array $data, $apikey) { $auth = base64_encode('user:' . $apikey); $json_postData = json_encode($data); $ch = curl_init(); $dataCenter = substr($apikey, strpos($apikey, '-') + 1); $curlopt_url = 'https://' . $dataCenter . '.api.mailchimp.com/3.0/batches/'; curl_setopt($ch, CURLOPT_URL, $curlopt_url); curl_setopt($ch, CURLOPT_HTTPHEADER, array('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_postData); $result = curl_exec($ch); return $result; } 

批量操作的function使用和数据格式:

 <?php $apikey = 'Your MailChimp Api Key'; $list_id = 'Your list ID'; $servername = 'localhost'; $username = 'Youre DB username'; $password = 'Your DB password'; $dbname = 'Your DB Name'; // Create connection $conn = new mysqli($servername, $username, $password, $dbname); // Check connection if ($conn->connect_error) { die('Connection failed: ' . $conn->connect_error); } $sql = 'SELECT * FROM emails';// your SQL Query goes here $result = $conn->query($sql); $finalData = []; if ($result->num_rows > 0) { // output data of each row while ($row = $result->fetch_assoc()) { $individulData = array( 'apikey' => $apikey, 'email_address' => $row['email'], 'status' => 'subscribed', 'merge_fields' => array( 'FNAME' => 'eastwest', 'LNAME' => 'rehab', ) ); $json_individulData = json_encode($individulData); $finalData['operations'][] = array( "method" => "POST", "path" => "/lists/$list_id/members/", "body" => $json_individulData ); } } $api_response = batchSubscribe($finalData, $apikey); print_r($api_response); $conn->close(); 

另外,你可以在我的Github中find这个代码。 GithubGist链接

参考文档: 官方