如何通过 api 添加 "Tags" 到 mailchimp 订阅者
How to add "Tags" to mailchimp subscriber via the api
希望添加 tags to my mailing list members via the api. But I don't see where to pass in tags in the documentation。有人可以指出如何通过 api 更新与成员关联的标签的示例吗?
标签取代了静态片段。因此,用于创建标签以及向成员添加和删除标签的端点与之前用于管理分段的端点相同。以下是用于通过 API 管理标签的端点文档,其中包括请求和响应正文参数以及示例请求和响应:
http://developer.mailchimp.com/documentation/mailchimp/reference/lists/segments/
为了给您的成员添加标签,您需要在 'static_segment' 数组参数中包含他们的电子邮件地址。
希望对您有所帮助。
显然 Mailchimp "tags" 是 "segments"。
我编写了几个函数,允许我通过电子邮件地址按名称(而不是按 ID)向成员(即订户)添加标签。
/**
*
* @param string $emailAddress
* @param array $tags
* @return void
*/
public function addTagsToContact($emailAddress, $tags) {
$list_id = $this->getDefaultListId();
foreach ($tags as $tag) {
$this->addMemberToSegment($emailAddress, $list_id, $tag);
}
}
/**
* Add a tag to a subscriber (tags replaced segments
*
* @param string $emailAddress
* @param string $list_id
* @param string $segment_name
* @return array
*/
public function addMemberToSegment($emailAddress, $list_id, $segment_name) {
$api = Newsletter::getApi();
$segmentsByName = $this->getSegments($list_id);
$segment_id = $segmentsByName[$segment_name]['id'];
$response = $api->post("lists/$list_id/segments/$segment_id", [
'members_to_add' => [$emailAddress]
]); //https://developer.mailchimp.com/documentation/mailchimp/reference/lists/segments/#create-post_lists_list_id_segments_segment_id
return $response;
}
/**
*
* @param string $list_id
* @return array
*/
public function getSegments($list_id) {//https://developer.mailchimp.com/documentation/mailchimp/reference/lists/segments/#%20
$segmentsByName = [];
$api = Newsletter::getApi();
$count = 50; //default is 10
$offset = 0;
do {
$url = "lists/$list_id/segments/?" . http_build_query(['count' => $count, 'offset' => $offset]);
Log::debug($url);
$response = $api->get($url);
$total_items = $response['total_items'];
foreach ($response['segments'] as $segment) {
$segmentsByName[$segment['name']] = $segment;
}
$offset += $count;
} while (count($segmentsByName) < $total_items);
//Log::debug(json_encode($segmentsByName));
return $segmentsByName;
}
/**
*
* @return string
*/
public function getDefaultListId() {
return config('newsletter.lists.subscribers.id');
}
这依赖于 https://github.com/spatie/laravel-newsletter 库。
P.S。非常感谢@Jelan,他的回答让我走上正轨!
这是官方添加标签的方式:
https://developer.mailchimp.com/documentation/mailchimp/reference/lists/members/tags/
它有效,除了在我的测试中,响应消息是空的,即使添加了标签。
以下是 Google Apps 脚本中的示例代码:
payload = '{\
"tags": [\
{\
"name":"' + tagName + '",\
"status":"' + tagStatus + '"\
}\
]\
}'
;
params = {
"method": "POST",
"headers":MC_headers,
"payload": payload,
"muteHttpExceptions": true
};
url = MC_url + 'lists/' + MC_IDs.listId + '/members/' + sub_hash + '/tags';
response = UrlFetchApp.fetch(url, params);
使用 GRAILS 将标签列表按名称添加到按电子邮件发送的用户列表的完整示例
请注意,您可能需要设置一些错误检查以查看 MailChimp 受众成员是否存在。
BusinessLogicController.groovy
/*
* Add list of tags by name to list of members
*/
def addTagsByNameToUser(){
List<string> tagNamesToAdd = ['foo', 'bar']
def addResult = mailChimpService.addTagsToContactsByName(["foo@example.com", "bar@example.com"], tagNamesToAdd)
}
MailChimpService.groovy
import grails.util.Holders
import groovyx.net.http.Method
class MailChimpService {
def grailsApplication
ApiConsumerService apiConsumerService
final String AUTH = Holders.config.grails.mailChimp.auth
final String BASEURL = "https://us19.api.mailchimp.com/3.0/"
final String LISTID = "abc123"
//Add list of tags by name to list of subscribers by email
def addTagsToContactsByName(List emailAddresses, List tags = []) {
tags.each { tagName ->
addMembersToSegment(emailAddresses, tagName);
}
}
//Add a tag to a subscriber by name
def addMembersToSegment(List emailAddresses, String segmentName) {
def segmentsByName = getAllSegmentsInList()
String segmentId = segmentsByName["$segmentName"] as String
return addMailChimpTagToUsers(emailAddresses, segmentId)
}
//Get information about all available segments for a specific list.
def getAllSegmentsInList(Map query = [:]) {
String path = "lists/"+LISTID+"/segments/"
Map segments = [:]
def segmentResults = apiConsumerService.getRequest(BASEURL, path, AUTH, query, Method.GET)
segmentResults.segments.each { segment ->
segments.put(segment.name, segment.id)
}
return segments
}
//Add list of tags to a list members.
def addMailChimpTagToUsers(List emailAddresses = [], String segmentId) {
String path = "lists/LISTID/segments/" + segmentId
apiConsumerService.postRequest(BASEURL, path, AUTH, ['members_to_add': emailAddresses], Method.POST)
}
}
ApiConsumerService.groovy
import grails.transaction.Transactional
import groovyx.net.http.ContentType
import groovyx.net.http.HTTPBuilder
import groovyx.net.http.Method
@Transactional
class ApiConsumerService {
//POST REQUEST
def postRequest(String baseUrl, String path, String auth, Map query = [:], Method method = Method.POST) {
try {
HTTPBuilder http = new HTTPBuilder(baseUrl)
http.headers['Authorization'] = 'Basic ' + "${auth}".getBytes('iso-8859-1').encodeBase64()
http.request(method, ContentType.JSON) { req ->
uri.path = path
if (method == Method.POST) {
body = query
} else {
uri.query = query
}
headers.'Accept' = 'application/json'
headers.'User-Agent' = "MyPetCerts/US19"
response.success = { resp, json ->
return json
}
response.failure = { resp, json ->
println "POST response status: ${resp.statusLine}"
}
}
} catch (groovyx.net.http.HttpResponseException ex) {
ex.printStackTrace()
return null
} catch (java.net.ConnectException ex) {
ex.printStackTrace()
return null
}
}
//GET Request
def getRequest(String baseUrl, String path, String auth, Map query = [:], Method method = Method.GET) {
return postRequest(baseUrl, path, auth, query, method)
}
}
如果您想创建一个成员并添加一个标签,您可以通过以下方式指定标签属性:
$data = array(
'apikey' => $api_key,
'email_address' => $email,
'status' => $status,
'tags' => array('your-tag-name'),
'merge_fields' => array(
'FNAME' => $fname,
'LNAME' => $lname
)
);
尽管 MC API 有些地方会告诉你填写名称和状态,它帮助我将标签定义为数组,但只粘贴标签的名称。
Seefan 在此线程中的回答帮助了我,我想我想帮助一个花了几天时间的人(像我一样)弄清楚 "tags" 是如何指定的:add tags to mailchimp subscriber created via api php
这是 WordPress 的代码,但应该有所帮助。我确实从另一个答案中得到了大部分内容,但在其他任何地方都找不到它。
请注意,这仅在订阅者已存在于列表中时才有效,然后您可以标记或取消标记它们。
$api_key = XXXXXXXXXXXXXXXXXXX-us20';
$email = 'tom@gmail.com';
$list_id = 'XXXXXXXX'; //This is the list /Audience id
$tag_name_text = 'XXXXX'; //This can be whatever you want it to be. Mail chimp will add it to the tags if not already on the system
//TAGS
$args = array(
'method' => 'POST',
'headers' => array(
'Authorization' => 'Basic ' . base64_encode( 'user:'. $api_key )
),
'body' => json_encode(array(
'tags' => array(
['name' => $tag_name_text,
'status' => 'active']
)
))
);
$response = wp_remote_post( 'https://' . substr($api_key,strpos($api_key,'-')+1) . '.api.mailchimp.com/3.0/lists/' . $list_id . '/members/'.md5(strtolower($email)).'/tags', $args );
if ($response['response']['code'] == 200 && $body->status == $status || $response['resp`enter code here`onse']['code'] == 204) {
//echo 'The you have been successfully ' . $status . '. Please check your emails';
} else {
echo '<b>' . $response['response']['code'] . $body->title . ':</b> ' . $body->detail;
}
我也花了一段时间才弄明白这一点。他们的文档不清楚,似乎有两种添加标签的方法,一种是使用 POST 通过标签端点,另一种是通过 PATCH 通过更新用户。这是 PHP 中 POST 的示例:
function tagUser($email){
global $api_key;
global $listId;
$hashedEmail = md5(strtolower($email));
$args = array(
'method' => 'POST',
'headers' => array(
'Authorization' => 'Basic ' . base64_encode( 'user:'. $api_key )
),
'body' => json_encode(array(
'tags' => array(['name'=>'healthy','status'=>'active'])
))
);
$response = wp_remote_post( 'https://usxx.api.mailchimp.com/3.0/lists/'.$listId.'/members/'.$hashedEmail.'/tags', $args );
$body = json_decode( $response['body'] );
}
希望添加 tags to my mailing list members via the api. But I don't see where to pass in tags in the documentation。有人可以指出如何通过 api 更新与成员关联的标签的示例吗?
标签取代了静态片段。因此,用于创建标签以及向成员添加和删除标签的端点与之前用于管理分段的端点相同。以下是用于通过 API 管理标签的端点文档,其中包括请求和响应正文参数以及示例请求和响应:
http://developer.mailchimp.com/documentation/mailchimp/reference/lists/segments/
为了给您的成员添加标签,您需要在 'static_segment' 数组参数中包含他们的电子邮件地址。
希望对您有所帮助。
显然 Mailchimp "tags" 是 "segments"。
我编写了几个函数,允许我通过电子邮件地址按名称(而不是按 ID)向成员(即订户)添加标签。
/**
*
* @param string $emailAddress
* @param array $tags
* @return void
*/
public function addTagsToContact($emailAddress, $tags) {
$list_id = $this->getDefaultListId();
foreach ($tags as $tag) {
$this->addMemberToSegment($emailAddress, $list_id, $tag);
}
}
/**
* Add a tag to a subscriber (tags replaced segments
*
* @param string $emailAddress
* @param string $list_id
* @param string $segment_name
* @return array
*/
public function addMemberToSegment($emailAddress, $list_id, $segment_name) {
$api = Newsletter::getApi();
$segmentsByName = $this->getSegments($list_id);
$segment_id = $segmentsByName[$segment_name]['id'];
$response = $api->post("lists/$list_id/segments/$segment_id", [
'members_to_add' => [$emailAddress]
]); //https://developer.mailchimp.com/documentation/mailchimp/reference/lists/segments/#create-post_lists_list_id_segments_segment_id
return $response;
}
/**
*
* @param string $list_id
* @return array
*/
public function getSegments($list_id) {//https://developer.mailchimp.com/documentation/mailchimp/reference/lists/segments/#%20
$segmentsByName = [];
$api = Newsletter::getApi();
$count = 50; //default is 10
$offset = 0;
do {
$url = "lists/$list_id/segments/?" . http_build_query(['count' => $count, 'offset' => $offset]);
Log::debug($url);
$response = $api->get($url);
$total_items = $response['total_items'];
foreach ($response['segments'] as $segment) {
$segmentsByName[$segment['name']] = $segment;
}
$offset += $count;
} while (count($segmentsByName) < $total_items);
//Log::debug(json_encode($segmentsByName));
return $segmentsByName;
}
/**
*
* @return string
*/
public function getDefaultListId() {
return config('newsletter.lists.subscribers.id');
}
这依赖于 https://github.com/spatie/laravel-newsletter 库。
P.S。非常感谢@Jelan,他的回答让我走上正轨!
这是官方添加标签的方式: https://developer.mailchimp.com/documentation/mailchimp/reference/lists/members/tags/ 它有效,除了在我的测试中,响应消息是空的,即使添加了标签。
以下是 Google Apps 脚本中的示例代码:
payload = '{\
"tags": [\
{\
"name":"' + tagName + '",\
"status":"' + tagStatus + '"\
}\
]\
}'
;
params = {
"method": "POST",
"headers":MC_headers,
"payload": payload,
"muteHttpExceptions": true
};
url = MC_url + 'lists/' + MC_IDs.listId + '/members/' + sub_hash + '/tags';
response = UrlFetchApp.fetch(url, params);
使用 GRAILS 将标签列表按名称添加到按电子邮件发送的用户列表的完整示例
请注意,您可能需要设置一些错误检查以查看 MailChimp 受众成员是否存在。
BusinessLogicController.groovy
/*
* Add list of tags by name to list of members
*/
def addTagsByNameToUser(){
List<string> tagNamesToAdd = ['foo', 'bar']
def addResult = mailChimpService.addTagsToContactsByName(["foo@example.com", "bar@example.com"], tagNamesToAdd)
}
MailChimpService.groovy
import grails.util.Holders
import groovyx.net.http.Method
class MailChimpService {
def grailsApplication
ApiConsumerService apiConsumerService
final String AUTH = Holders.config.grails.mailChimp.auth
final String BASEURL = "https://us19.api.mailchimp.com/3.0/"
final String LISTID = "abc123"
//Add list of tags by name to list of subscribers by email
def addTagsToContactsByName(List emailAddresses, List tags = []) {
tags.each { tagName ->
addMembersToSegment(emailAddresses, tagName);
}
}
//Add a tag to a subscriber by name
def addMembersToSegment(List emailAddresses, String segmentName) {
def segmentsByName = getAllSegmentsInList()
String segmentId = segmentsByName["$segmentName"] as String
return addMailChimpTagToUsers(emailAddresses, segmentId)
}
//Get information about all available segments for a specific list.
def getAllSegmentsInList(Map query = [:]) {
String path = "lists/"+LISTID+"/segments/"
Map segments = [:]
def segmentResults = apiConsumerService.getRequest(BASEURL, path, AUTH, query, Method.GET)
segmentResults.segments.each { segment ->
segments.put(segment.name, segment.id)
}
return segments
}
//Add list of tags to a list members.
def addMailChimpTagToUsers(List emailAddresses = [], String segmentId) {
String path = "lists/LISTID/segments/" + segmentId
apiConsumerService.postRequest(BASEURL, path, AUTH, ['members_to_add': emailAddresses], Method.POST)
}
}
ApiConsumerService.groovy
import grails.transaction.Transactional
import groovyx.net.http.ContentType
import groovyx.net.http.HTTPBuilder
import groovyx.net.http.Method
@Transactional
class ApiConsumerService {
//POST REQUEST
def postRequest(String baseUrl, String path, String auth, Map query = [:], Method method = Method.POST) {
try {
HTTPBuilder http = new HTTPBuilder(baseUrl)
http.headers['Authorization'] = 'Basic ' + "${auth}".getBytes('iso-8859-1').encodeBase64()
http.request(method, ContentType.JSON) { req ->
uri.path = path
if (method == Method.POST) {
body = query
} else {
uri.query = query
}
headers.'Accept' = 'application/json'
headers.'User-Agent' = "MyPetCerts/US19"
response.success = { resp, json ->
return json
}
response.failure = { resp, json ->
println "POST response status: ${resp.statusLine}"
}
}
} catch (groovyx.net.http.HttpResponseException ex) {
ex.printStackTrace()
return null
} catch (java.net.ConnectException ex) {
ex.printStackTrace()
return null
}
}
//GET Request
def getRequest(String baseUrl, String path, String auth, Map query = [:], Method method = Method.GET) {
return postRequest(baseUrl, path, auth, query, method)
}
}
如果您想创建一个成员并添加一个标签,您可以通过以下方式指定标签属性:
$data = array(
'apikey' => $api_key,
'email_address' => $email,
'status' => $status,
'tags' => array('your-tag-name'),
'merge_fields' => array(
'FNAME' => $fname,
'LNAME' => $lname
)
);
尽管 MC API 有些地方会告诉你填写名称和状态,它帮助我将标签定义为数组,但只粘贴标签的名称。
Seefan 在此线程中的回答帮助了我,我想我想帮助一个花了几天时间的人(像我一样)弄清楚 "tags" 是如何指定的:add tags to mailchimp subscriber created via api php
这是 WordPress 的代码,但应该有所帮助。我确实从另一个答案中得到了大部分内容,但在其他任何地方都找不到它。 请注意,这仅在订阅者已存在于列表中时才有效,然后您可以标记或取消标记它们。
$api_key = XXXXXXXXXXXXXXXXXXX-us20';
$email = 'tom@gmail.com';
$list_id = 'XXXXXXXX'; //This is the list /Audience id
$tag_name_text = 'XXXXX'; //This can be whatever you want it to be. Mail chimp will add it to the tags if not already on the system
//TAGS
$args = array(
'method' => 'POST',
'headers' => array(
'Authorization' => 'Basic ' . base64_encode( 'user:'. $api_key )
),
'body' => json_encode(array(
'tags' => array(
['name' => $tag_name_text,
'status' => 'active']
)
))
);
$response = wp_remote_post( 'https://' . substr($api_key,strpos($api_key,'-')+1) . '.api.mailchimp.com/3.0/lists/' . $list_id . '/members/'.md5(strtolower($email)).'/tags', $args );
if ($response['response']['code'] == 200 && $body->status == $status || $response['resp`enter code here`onse']['code'] == 204) {
//echo 'The you have been successfully ' . $status . '. Please check your emails';
} else {
echo '<b>' . $response['response']['code'] . $body->title . ':</b> ' . $body->detail;
}
我也花了一段时间才弄明白这一点。他们的文档不清楚,似乎有两种添加标签的方法,一种是使用 POST 通过标签端点,另一种是通过 PATCH 通过更新用户。这是 PHP 中 POST 的示例:
function tagUser($email){
global $api_key;
global $listId;
$hashedEmail = md5(strtolower($email));
$args = array(
'method' => 'POST',
'headers' => array(
'Authorization' => 'Basic ' . base64_encode( 'user:'. $api_key )
),
'body' => json_encode(array(
'tags' => array(['name'=>'healthy','status'=>'active'])
))
);
$response = wp_remote_post( 'https://usxx.api.mailchimp.com/3.0/lists/'.$listId.'/members/'.$hashedEmail.'/tags', $args );
$body = json_decode( $response['body'] );
}