使用Constant Contact c# .net sdk v2创建/添加

本文关键字:v2 创建 添加 sdk net Constant Contact 使用 | 更新日期: 2023-09-27 18:04:24

我使用的是Constant Contact .net sdk的官方版本2。

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

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

这些特性显然存在于这里找到的API的v2中,但是在SDK中似乎没有。

使用Constant Contact c# .net sdk v2创建/添加

创建联系人。

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。

(http://developer.constantcontact.com/docs/contacts-api/contacts-resource.html?method=DELETE)

注意:我还没有测试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;
}

这是我添加联系人的解决方案。我所做的是将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;