Mailchimp API v3를 사용하여 목록에 가입자 추가
Mailchimp에서 만든 목록에 사용자를 추가하려고 하는데 코드 예를 찾을 수 없습니다.API를 어떻게 사용하는지 알아보려고 노력했지만, 저는 "예시를 보고 배우는" 타입의 사람입니다.
API 버전2를 사용해 봤는데, 인터넷상의 예에서 작업하고 있는데도 아무것도 동작하지 않는 것 같습니다.Mailchimp는 이전 버전의 API에 대해 다음과 같이 웹 사이트에서 말하고 있습니다.
버전 2.0 이전은 권장되지 않습니다.이러한 버전에서는 최소한의 지원(버그 수정, 보안 패치)만 사용할 수 있습니다.
업데이트 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: 현재 컬을 사용하고 있으며, 거의 동작하고 있는 것을 입수할 수 있습니다.데이터는 Mailchimp로 전송되지만 "Your request does 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');
List Members Instance 문서를 기반으로 가장 쉬운 방법은 문서에 따르면 "새 목록 구성원을 추가하거나 목록에 이미 전자 메일이 있는 경우 구성원을 업데이트"하는 요청을 사용하는 것입니다.
★★★★★★★★★★★★★★★★.apikey
json 스키마의 일부가 아니므로 json 요청에 포함시켜도 의미가 없습니다.
@알 수, 「」, 「@TooMuchPete」, 「TooMuchPete」를 사용할 수 .CURLOPT_USERPWD
「http auth」 「http auth」 「http auth」 「http auth」 。
리스트 멤버 추가 및 갱신을 위해 다음 기능을 사용하고 있습니다. 할 요.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;
}
내가 해냈다.헤더에 인증을 잘못 추가하고 있었습니다.
$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"를 통해 .0을 줍니다..ajax()
Mailchimp의 경우:
- API 키 및 목록 ID 획득
- 목록과 목록과 함께 사용할 사용자 정의 필드를 설정해야 합니다. 이,, 는미를
zipcode
API 호출을 수행하기 전에 목록의 커스텀 필드로 사용합니다. - 목록에 멤버 추가에 대한 API 문서를 참조하십시오.를 사용하고 있습니다.
create
HTTP를 해야 하는POST
이 밖에도 또 다른 선택지가 있습니다.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>
주요 사항:
- 의 이름을 대세요.
<form>
로,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);
?>
주요 사항:
CURLOPT_USERPWD
Mailchimp API Mailchimp입니다.CURLOPT_RETURNTRANSFER
페이지로 수 합니다.html html html 、 HTML 、페 html html html html html html html html html 。.ajax()
success
핸들러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);
}
});
});
주요 사항:
JSON
전송 시 데이터가 매우 민감합니다.이치노문제가 있는 경우는, JSON 데이터의 구조화가 원인이라고 생각할 수 있습니다.★★★★★★★★★★★★★★★★!- 는 PHP .
_POST
는 「」, 「」가 됩니다._POST['email']
,_POST['firstname']
수 키. 단지 당신이 이름을 짓는 것을 기억하기만 하면 됩니다.data
JSON은 PHP를 사용합니다. - 여기에는 분명히 jQuery가 필요합니다.)
BATCH LOAD - OK, 링크 사용만으로 이전 회신을 삭제한 후 코드를 업데이트하여 작업을 할 수 있었습니다.저는 아직 이 내용을 배우고 있습니다만, 배치 멤버 리스트 추가 작업을 받고 있기 때문에, 심플화/수정/수정/기능화 등에 대해 감사해 주십시오.
$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");
만약 도움이 된다면, CURL이 아닌 Python Requests 라이브러리를 사용하여 Python에서 작업한 것입니다.
위의 @staypuftman에서 설명한 바와 같이 MailChimp에서 API 키와 목록 ID가 필요하며 API 키 접미사와 URL 접두사(us5)가 일치하는지 확인합니다.
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": "test@testing.com", # '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)
Mailchimp API를 사용하여 목록에서 Batch Subscribe를 실행하고 싶다면 다음 함수를 사용할 수 있습니다.
/**
* 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;
}
배치 작업을 위한 함수 사용 및 데이터 형식:
<?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 Gist에서 찾을 수 있습니다.GithubGist 링크
레퍼런스 문서: 공식
언급URL : https://stackoverflow.com/questions/30481979/adding-subscribers-to-a-list-using-mailchimps-api-v3
'programing' 카테고리의 다른 글
일부 유명 프로그램이 항상 인쇄를 사용하는 이유 (0) | 2023.03.29 |
---|---|
브라우저 콘솔에서 앵귤러 함수를 호출하다 (0) | 2023.03.19 |
단일 요소 디코딩에 실패하면 Swift JSONDecode 디코딩 어레이가 실패함 (0) | 2023.03.19 |
스프링 부트 보안 - java.lang.부정 인수예외: 부여된 null을 전달할 수 없습니다.권한 수집 (0) | 2023.03.19 |
ng-click 부모부터 자녀까지 클릭 (0) | 2023.03.19 |