0

我正在使用此处找到的 Constant Contact .net-sdk 的官方版本 2 。

我一直无法找到以下方法:

  • 创建联系人列表
  • 将联系人添加到联系人列表
  • 从联系人列表中删除联系人
  • 将多个联系人添加到联系人列表
  • 创建电子邮件活动

这些功能显然存在于此处找到的 API v2 中,但 SDK 中似乎缺少这些功能。

访问此功能的任何帮助表示赞赏。

4

2 回答 2

1

创建联系人。

try
{
    using (var client = new HttpClient())
    {
        client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "<Replace with your oAuth Token>");

        ContactObject cont = new ContactObject
        {
            first_name = "Deepu",
            last_name = "Madhusoodanan"
        };

        var email_addresses = new List<EmailAddress>
        {
            new EmailAddress{email_address = "deepumi1@gmail.com"}
        };

        cont.email_addresses = email_addresses;
        cont.lists = new List<List>
        {
            new List {id = "<Replace with your List Id>"}
        };

        var json = Newtonsoft.Json.JsonConvert.SerializeObject(cont);
        string MessageType = "application/json";
        using (var request = new HttpRequestMessage(System.Net.Http.HttpMethod.Post, "https://api.constantcontact.com/v2/contacts?api_key=<Replace with your API key>"))
        {
            request.Headers.Add("Accept", MessageType);

            request.Content = new StringContent(json);
            request.Content.Headers.ContentType = System.Net.Http.Headers.MediaTypeHeaderValue.Parse(MessageType);

            using (var response = await client.SendAsync(request).ConfigureAwait(false))
            {
                string responseXml = await response.Content.ReadAsStringAsync().ConfigureAwait(false);
                var code = response.StatusCode;
            }
            request.Content.Dispose();
        }
    }
}
catch (Exception exp)
{ 
  //log exception here
}

/*Model class*/
public class Address
{
    public string address_type { get; set; }
    public string city { get; set; }
    public string country_code { get; set; }
    public string line1 { get; set; }
    public string line2 { get; set; }
    public string line3 { get; set; }
    public string postal_code { get; set; }
    public string state_code { get; set; }
    public string sub_postal_code { get; set; }
}

public class List
{
    public string id { get; set; }
}

public class EmailAddress
{
    public string email_address { get; set; }
}

public class ContactObject
{
    public List<Address> addresses { get; set; }
    public List<List> lists { get; set; }
    public string cell_phone { get; set; }
    public string company_name { get; set; }
    public bool confirmed { get; set; }
    public List<EmailAddress> email_addresses { get; set; }
    public string fax { get; set; }
    public string first_name { get; set; }
    public string home_phone { get; set; }
    public string job_title { get; set; }
    public string last_name { get; set; }
    public string middle_name { get; set; }
    public string prefix_name { get; set; }
    public string work_phone { get; set; }
}

注意:您必须替换 oAuth 令牌、API 密钥和列表 ID。

根据 api 文档删除方法。( http://developer.constantcontact.com/docs/contacts-api/contacts-resource.html?method=DELETE )

注意:我还没有测试删除方法。

private async Task<string> DeleteContact(string contactId)
{
    try
    {
        using (var client = new HttpClient())
        {
            client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "<Replace with your oAuth Token>");
            using (var request = new HttpRequestMessage(System.Net.Http.HttpMethod.Delete, "https://api.constantcontact.com/v2/contacts/" + contactId + "?api_key=<Replace with your API key>"))
            {
                using (var response = await client.SendAsync(request).ConfigureAwait(false))
                {
                    response.EnsureSuccessStatusCode();
                    return await response.Content.ReadAsStringAsync().ConfigureAwait(false);
                }
            }
        }
    }
    catch (Exception exp)
    { 
        //log exp here
    }
    return string.Empty;
}
于 2015-07-23T20:11:09.477 回答
0

这是我添加联系人的解决方案。我所做的是将 Deepu 提供的代码与 Constant Contact API v2 结合起来。我还不得不删除asyncawait引用,因为它们与 VS2010 不兼容。我还没试过DELETE。。。

using System;
using System.Collections.Generic;
using System.Configuration;
using System.Net.Http;
using CTCT.Components.Contacts;
using System.Net.Http.Headers;

/// <summary>
/// Constant Contact Helper Class for POST, PUT, and DELETE 
/// </summary>
public class ConstantContactHelper
{
    private string _accessToken = ConfigurationManager.AppSettings["ccAccessToken"];
    private Dictionary<string, System.Net.Http.HttpMethod> requestDict = new Dictionary<string, System.Net.Http.HttpMethod> { 
        {"GET", HttpMethod.Get}, 
        {"POST", HttpMethod.Post}, 
        {"PUT", HttpMethod.Put}, 
        {"DELETE", HttpMethod.Delete} 
    };
    private System.Net.Http.HttpMethod requestMethod = null;
    private Dictionary<string, ConstantContactURI> uriDict = new Dictionary<string, ConstantContactURI> { 
        {"AddContact", new ConstantContactURI("contacts")},
        {"AddContactList", new ConstantContactURI("lists")},
        {"AddEmailCampaign", new ConstantContactURI("campaigns")},
    };
    private ConstantContactURI URI_Handler = new ConstantContactURI();
    private ContactRequestBody RequestBody = new ContactRequestBody();
    private const string messageType = "application/json";
    public string jsonRequest = null;
    public string responseXml = null;
    public string status_code = null;

    public ConstantContactHelper()  {}

    public ConstantContactHelper(string methodKey, string uriKey, string firstName, string lastName, string emailAddress, string listId)
    {
        this.requestMethod = this.requestDict[methodKey];
        this.URI_Handler = this.uriDict[uriKey];
        this.RequestBody = new ContactRequestBody(firstName, lastName, emailAddress, listId);
    }

    // Return Response as a string
    public void TryRequest()
    {
        try
        {
            using (var client = new HttpClient())
            {
                client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", this._accessToken);

                var json = Newtonsoft.Json.JsonConvert.SerializeObject(this.RequestBody.contact);
                this.jsonRequest = json;
                using (var request = new HttpRequestMessage(HttpMethod.Post, this.URI_Handler.fullURI))
                {
                    request.Headers.Add("Accept", messageType);

                    request.Content = new StringContent(json);
                    request.Content.Headers.ContentType = System.Net.Http.Headers.MediaTypeHeaderValue.Parse(messageType);

                    using (var response = client.SendAsync(request))
                    {
                        this.responseXml = response.Result.Content.ReadAsStreamAsync().ConfigureAwait(false).ToString();
                        this.status_code = response.Status.ToString();
                    }
                    request.Content.Dispose();                    
                }
            }
        }
        catch(Exception exp)
        {
            // Handle Exception
            this.responseXml = "Unhandled exception: " + exp.ToString();
        }
    }
}

public class ConstantContactURI
{
    private const string baseURI = "https://api.constantcontact.com/v2/";
    private const string queryPrefix = "?api_key=";
    private string _apiKey = ConfigurationManager.AppSettings["ccApiKey"];
    public string fullURI = null;

    public ConstantContactURI() {}

    public ConstantContactURI(string specificPath)
    {
        this.fullURI = baseURI + specificPath + queryPrefix + _apiKey;    
    }
}

public class ContactRequestBody
{
    public Contact contact = new Contact();

    private List<EmailAddress> email_addresses = new List<EmailAddress>()
    {
        new EmailAddress{
            EmailAddr = "",
            Status = Status.Active,
            ConfirmStatus = ConfirmStatus.NoConfirmationRequired
        }
    };
    private List<ContactList> lists = new List<ContactList>()
    {
        new ContactList {Id = ""}
    };

    public ContactRequestBody() { }

    public ContactRequestBody(string firstName, string lastName, string emailAddress, string listId) 
    {
        this.contact.FirstName = firstName;
        this.contact.LastName = lastName;

        this.email_addresses[0].EmailAddr = emailAddress;
        this.contact.EmailAddresses = this.email_addresses;

        this.lists[0].Id = listId;
        this.contact.Lists = this.lists;
    }
}

来自页面的示例调用aspx.cs如下所示:

ConstantContactHelper requestHelper = new ConstantContactHelper("POST", "AddContact", firstName.Text, lastName.Text, emailBox.Text, listId);
requestHelper.TryRequest();
lbTest.Text = requestHelper.jsonRequest + ", status code:" + requestHelper.status_code + ", xml:" + requestHelper.responseXml;
于 2015-07-24T03:22:14.910 回答