希望通过api将tags添加到我的邮件列表成员中。但是我看不到documentation中的标签传递位置。有人可以指出如何通过api更新与成员关联的标签的示例吗?
答案 0 :(得分:4)
显然,Mailchimp的“标签”是“细分”。
我编写了几个函数,使我可以通过电子邮件地址按名称(而不是按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 https://stackoverflow.com/a/52315577/470749)
*
* @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,他的回答使我走上了正轨!
答案 1 :(得分:2)
这是添加标签的官方方法: 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);
答案 2 :(得分:0)
使用网格按名称将标签列表添加到按电子邮件用户列表的完整示例
请注意,您可能需要设置一些错误检查,以查看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)
}
}
答案 3 :(得分:0)
如果要创建成员并同时添加标签,则可以通过以下方式指定标签属性:
$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在此主题中的答案帮助了我,我认为我想帮助一个花了几天时间的人(像我一样)弄清楚如何指定“标签”:add tags to mailchimp subscriber created via api php
答案 4 :(得分:0)
我花了一段时间才弄明白这个问题。他们的文档不清楚,似乎有两种添加标签的方法,一种是通过使用 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'] );
}