php 使用 Mailchimp 的 API v3 将订阅者添加到列表中
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/30481979/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Adding subscribers to a list using Mailchimp's API v3
提问by VenomRush
I'm trying to add users to a list I've created in Mailchimp but I can't find any code examples anywhere. I've tried figuring out how to use the API but I'm very much a "Look at an example and learn" kind of person.
我正在尝试将用户添加到我在 Mailchimp 中创建的列表中,但在任何地方都找不到任何代码示例。我已经尝试弄清楚如何使用 API,但我非常喜欢“看一个例子并学习”类型的人。
I've tried using version 2 of the API but nothing seems to be working despite working from examples on the net and Mailchimp says the following about earlier versions of their API on their website:
我已经尝试使用 API 的第 2 版,但尽管通过网络上的示例工作,但似乎没有任何效果,Mailchimp 在其网站上对早期版本的 API 说了以下内容:
Versions 2.0 and earlier are deprecated. Only minimal support—bug fixes, security patches—will be available for those versions.
2.0 及更早版本已弃用。这些版本仅提供最低限度的支持(错误修复、安全补丁)。
UPDATE 1: I did some further research based on TooMuchPete's answerwith regards to the link on Managing Subscribers and altered some code I found here, but it won't work because the function http_build_query()doesn't deal with nested arrays. I'm not sure how to deal with the 'merge_fields' portion of adding a subscriber. My current code is below:
更新 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');
UPDATE 2: I've now resorted to using curl and I've managed to get something almost working. The data sends through to Mailchimp but I'm receiving the error "Your request did not include an API key."I'm guessing I need to authenticate as mentioned here. I've tried adding it to the http header which hasn't worked. See my code below:
更新 2:我现在求助于使用 curl 并且我已经设法让一些东西几乎正常工作。数据发送到 Mailchimp,但我收到错误“您的请求不包含 API 密钥。” 我猜我需要像这里提到的那样进行身份验证。我已经尝试将它添加到没有工作的 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');
回答by billynoah
Based on the List Members Instance docs, the easiest way is to use a PUT
request which according to the docs either "adds a new list member or updates the member if the email already exists on the list".
根据List Members Instance 文档,最简单的方法是使用PUT
根据文档“添加新的列表成员或更新成员(如果电子邮件已存在于列表中)”的请求。
Furthermore apikey
is definitely not part of the json schemaand there's no point in including it in your json request.
此外apikey
绝对不是json 模式的一部分,将它包含在您的 json 请求中毫无意义。
Also, as noted in @TooMuchPete's comment, you can use CURLOPT_USERPWD
for basic http auth as illustrated in below.
此外,如@TooMuchPete 的评论中所述,您可以使用CURLOPT_USERPWD
基本的 http 身份验证,如下所示。
I'm using the following function to add and update list members. You may need to include a slightly different set of merge_fields
depending on your list parameters.
我正在使用以下函数来添加和更新列表成员。merge_fields
根据您的列表参数,您可能需要包含一组略有不同的。
$data = [
'email' => '[email protected]',
'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;
}
回答by VenomRush
I got it working. I was adding the authentication to the header incorrectly:
我让它工作了。我错误地将身份验证添加到标题中:
$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');
回答by serraosays
These are good answers but detached from a full answer as to how you would get a form to send data and handle that response. This will demonstrate how to add a member to a list with v3.0 of the API from an HTML page via jquery .ajax()
.
这些是很好的答案,但与关于如何获取表单以发送数据和处理该响应的完整答案无关。这将演示如何通过 jquery 从 HTML 页面使用 API 的 v3.0 将成员添加到列表中.ajax()
。
In Mailchimp:
在 Mailchimp 中:
- Acquire your API Keyand List ID
- Make sure you setup your list and what custom fields you want to use with it. In this case, I've set up
zipcode
as a custom field in the list BEFORE I did the API call. - Check out the API docson adding members to lists. We are using the
create
method which requires the use of HTTPPOST
requests. There are other options in here that requirePUT
if you want to be able to modify/delete subs.
- 获取您的API 密钥和列表 ID
- 确保您设置了您的列表以及您想要使用的自定义字段。在这种情况下,我在
zipcode
执行 API 调用之前在列表中设置了一个自定义字段。 - 查看有关将成员添加到列表的API 文档。我们正在使用
create
需要使用 HTTPPOST
请求的方法。PUT
如果您希望能够修改/删除潜艇,这里还有其他选项。
HTML:
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="[email protected]">
<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>
Key things:
关键事项:
- Give your
<form>
a unique ID and don't forget themethod="post"
attribute so the form works. - Note the last line
#signup-result
is where you will deposit the feedback from the PHP script.
- 给你
<form>
一个唯一的 ID,不要忘记这个method="post"
属性,这样表单才能工作。 - 请注意,最后一行
#signup-result
是您将存放来自 PHP 脚本的反馈的位置。
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);
?>
Key things:
关键事项:
CURLOPT_USERPWD
handles the API key and Mailchimp doesn't really show you how to do this.CURLOPT_RETURNTRANSFER
gives us the response in such a way that we can send it back into the HTML page with the.ajax()
success
handler.- Use
json_encode
on the data you received.
CURLOPT_USERPWD
处理 API 密钥,而 Mailchimp 并没有真正向您展示如何执行此操作。CURLOPT_RETURNTRANSFER
以这样一种方式给我们响应,我们可以将它发送回带有.ajax()
success
处理程序的 HTML 页面。- 用于
json_encode
您收到的数据。
JS:
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);
}
});
});
Key things:
关键事项:
JSON
data is VERY touchy on transfer. Here, I am putting it into an array and it looks easy. If you are having problems, it is likely because of how your JSON data is structured. Check this out!- The keys for your JSON data will become what you reference in the PHP
_POST
global variable. In this case it will be_POST['email']
,_POST['firstname']
, etc. But you could name them whatever you want - just remember what you name the keys of thedata
part of your JSON transfer is how you access them in PHP. - This obviously requires jQuery ;)
JSON
数据在传输时非常敏感。在这里,我将它放入一个数组中,看起来很简单。如果您遇到问题,可能是因为您的 JSON 数据的结构方式。看一下这个!- JSON 数据的键将成为您在 PHP
_POST
全局变量中引用的键。在这种情况下,它将是_POST['email']
、_POST['firstname']
等。但是您可以随意命名它们 - 只需记住您命名data
JSON 传输部分的键是您在 PHP 中访问它们的方式。 - 这显然需要 jQuery ;)
回答by Danpez
BATCH LOAD- OK, so after having my previous reply deleted for just using links I have updated with the code I managed to get working. Appreciate anyone to simplify / correct / refine / put in function etc as I'm still learning this stuff, but I got batch member list add working :)
批量加载- 好的,所以在删除我之前的回复后只使用链接我已经更新了我设法开始工作的代码。感谢任何人简化/更正/改进/放入功能等,因为我仍在学习这些东西,但我有批处理成员列表添加工作:)
$apikey = "whatever-us99";
$list_id = "12ab34dc56";
$email1 = "[email protected]";
$fname1 = "Hyman";
$lname1 = "Black";
$email2 = "[email protected]";
$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");
回答by Faisal
If you Want to run Batch Subscribe on a List using Mailchimp API. Then you can use the below function.
如果您想使用 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 Use And Data format for Batch Operations:
批量操作的函数使用和数据格式:
<?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();
Also, You can found this code in my Github gist. GithubGist Link
此外,您可以在我的 Github 要点中找到此代码。GithubGist 链接
Reference Documentation: Official
参考文档:官方
回答by Ric
If it helps anyone, here is what I got working in Python using the Python Requestslibrary instead of CURL.
如果它对任何人有帮助,这就是我使用 Python Requests库而不是CURL在 Python 中工作的内容。
As explained by @staypuftman above, you will need your API Key and List ID from MailChimp and make sure your API Key suffix and URL prefix (i.e. us5) match.
正如上面@staypuftman 所解释的,您将需要来自 MailChimp 的 API 密钥和列表 ID,并确保您的 API 密钥后缀和 URL 前缀(即 us5)匹配。
Python:
Python:
#########################################################################################
# To add a single contact to MailChimp (using MailChimp v3.0 API), requires:
# + MailChimp API Key
# + MailChimp List Id for specific list
# + MailChimp API URL for adding a single new contact
#
# Note: the API URL has a 3/4 character 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/4 characters of your API key. The API URL location subdomain must match API Key
# suffix e.g. us5, us13, us19 etc. but in this example, us5.
# (suggest you put the following 3 values in 'settings' or 'secrets' file)
#########################################################################################
MAILCHIMP_API_KEY = 'your-api-key-here-us5'
MAILCHIMP_LIST_ID = 'your-list-id-here'
MAILCHIMP_ADD_CONTACT_TO_LIST_URL = 'https://us5.api.mailchimp.com/3.0/lists/' + MAILCHIMP_LIST_ID + '/members/'
# Create new contact data and convert into JSON as this is what MailChimp expects in the API
# I've hardcoded some test data but use what you get from your form as appropriate
new_contact_data_dict = {
"email_address": "[email protected]", # 'email_address' is a mandatory field
"status": "subscribed", # 'status' is a mandatory field
"merge_fields": { # 'merge_fields' are optional:
"FNAME": "John",
"LNAME": "Smith"
}
}
new_contact_data_json = json.dumps(new_contact_data_dict)
# Create the new contact using MailChimp API using Python 'Requests' library
req = requests.post(
MAILCHIMP_ADD_CONTACT_TO_LIST_URL,
data=new_contact_data_json,
auth=('user', MAILCHIMP_API_KEY),
headers={"content-type": "application/json"}
)
# debug info if required - .text and .json also list the 'merge_fields' names for use in contact JSON above
# print req.status_code
# print req.text
# print req.json()
if req.status_code == 200:
# success - do anything you need to do
else:
# fail - do anything you need to do - but here is a useful debug message
mailchimp_fail = 'MailChimp call failed calling this URL: {0}\n' \
'Returned this HTTP status code: {1}\n' \
'Returned this response text: {2}' \
.format(req.url, str(req.status_code), req.text)