【问题标题】:Adding subscribers to a list in Mail Chimp 3.0 in ASP.NET在 ASP.NET 中将订阅者添加到 Mail Chimp 3.0 中的列表
【发布时间】:2015-11-06 14:35:38
【问题描述】:

我正在尝试使用我的 ASP.NET C# 网站实现 Mail Chimp 的新 API,因此当用户在输入框中输入他们的电子邮件地址时,它将自动添加到我的 mailchimp 列表中。我已经尝试了各种其他方法,但是这些方法都没有奏效。

我尝试了一个 Web 客户端,它抛出 405 Cannot use that Method 响应和一个 HttpClient,它在加星标的 GetStringAsync 方法调用上抛出错误,因为它不是任务。

到目前为止,我的代码详细如下:

public bool BatchSubscribe(IEnumerable<MailChimpSubscriberModel> newSubscribers)
{   
    if (string.IsNullOrEmpty(_defaultListId)) throw new ArgumentNullException(Res.Resource.MailChimpIntegrationNoListId);

    if (string.IsNullOrEmpty(_apiKey)) throw new ArgumentNullException(Res.Resource.MailChimpIntegrationNoApiKey);

    foreach (MailChimpSubscriberModel subscriber in newSubscribers)
    {
        string url = "https://" + _dataPoint + ".api.mailchimp.com/3.0/lists/" + _defaultListId + "/";

        Subscriber member = new Subscriber();
        member.email = subscriber.Email;
        member.subscribed = "subscribed";

        string jsonString = new JavaScriptSerializer().Serialize(member);

        //using (WebClient client = new WebClient())
        //{
        //    client.Headers[HttpRequestHeader.ContentType] = "application/x-www-form-urlencoded";
        //    client.Headers[HttpRequestHeader.Authorization] = new AuthenticationHeaderValue("Basic", _apiKey).ToString();
        //    string HtmlResult = client.(url, jsonString);

        //    return true;
        //}

        using (var http = new HttpClient())
        {
            http.DefaultRequestHeaders.Authorization =
                 new AuthenticationHeaderValue("Basic", _apiKey);
            string content = await http.**GetStringAsync**(@"https://us11.api.mailchimp.com/3.0/lists");
            Console.WriteLine(content);
        }
    }
    return false;
}

【问题讨论】:

    标签: c# asp.net json mailchimp-api-v3.0


    【解决方案1】:

    这个问题我有点晚了,但是我花了半天时间才弄清楚,这里有我的答案,所以它可以帮助其他人。我正在使用 MailChimp 3.0:

    private void subscribeAddress() 
    {
      string apiKey = "APIKEY-usX"; //your API KEY created by you.
      string dataCenter = "usX";
      string listID = "listID"; //The ListID of the list you want to use.
    
      SubscribeClassCreatedByMe subscribeRequest = new SubscribeClassCreatedByMe 
      {
          email_address = "somebodys@email.com",
          status = "subscribed"
      };
      subscribeRequest.merge_fields = new MergeFieldClassCreatedByMe();
      subscribeRequest.merge_fields.FNAME = "YourName";
      subscribeRequest.merge_fields.LNAME = "YourSurname";
    
      using (HttpClient client = new HttpClient())
      {
          var uri = "https://" + dataCenter + ".api.mailchimp.com/";
          var endpoint = "3.0/lists/" + listID + "/members";
    
          client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Basic", apiKey);
          client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
          client.BaseAddress = new Uri(uri);
    
          //NOTE: To avoid the method being 'async' we access to '.Result'
          HttpResponseMessage response = client.PostAsJsonAsync(endpoint, subscribeRequest).Result;//PostAsJsonAsync method serializes an object to 
                                                                                                //JSON and then sends the JSON payload in a POST request
        //StatusCode == 200
        // -> Status == "subscribed" -> Is on the list now
        // -> Status == "unsubscribed" -> this address used to be on the list, but is not anymore
        // -> Status == "pending" -> This address requested to be added with double-opt-in but hasn't confirmed yet
        // -> Status == "cleaned" -> This address bounced and has been removed from the list
    
        //StatusCode == 404
        if ((response.IsSuccessStatusCode))
        {
           //Your code here
        }
      }
    }
    

    这里有SubscribeClassCreatedByMe和MergeFieldClassCreatedByMe类

    namespace Subscriber
    {
      public class SubscribeClassCreatedByMe 
      {
        public string email_address { get; set; }
        public string status { get; set; }
        public MergeFieldClassCreatedByMe merge_fields { get; set; }
      }
    }
    namespace Subscriber
    {
      public class MergeFieldClassCreatedByMe
      {
        public string FNAME { get; set; }
        public string LNAME { get; set; }
      }
    }
    

    嗯,希望对你有帮助!!

    【讨论】:

    • 通过 Postman 使用相同的参数时,我收到错误 403 The API key provided is linked to a different datacenter
    • 我收到错误回复StatusCode: 400, ReasonPhrase: 'Bad Request'
    • 在我的情况下,由于使用了伪造的凭据(例如电子邮件:example@example.com),我收到了错误的请求响应。当使用更真实的凭据时,它起作用了。
    【解决方案2】:

    401 不是“无法使用该方法”,而是“未经授权”。您遇到了身份验证错误。从外观上看,您并没有以正确的方式进行基本身份验证。 Check out this example 了解您所缺少的详细信息。

    PS:从 APIv3 返回的响应通常很有帮助,因此您应该始终确保查看整个响应,而不仅仅是状态代码。

    【讨论】:

    • 嗨@TooMuchPete 感谢您的回复。每当我尝试将 json 数据发送到 mailchimp 时,我目前都会收到 404 错误代码。这是正在发送的消息:{方法:GET,RequestUri:'us11.api.mailchimp.com/3.0/lists/myListKey{"email":"testemail@test.com","subscribed":"subscribed"}',版本:1.1,内容: , 标头:{ Authorization: Basic myAPIkey }}
    • 这看起来不像是你应该发送给 MailChimp 的东西。如果您尝试发出 GET 请求,则根本不应该发送任何正文。你在 MailChimp 的回复中得到了什么?
    【解决方案3】:

    如果您将 auth 更改为以下几行,它会起作用:

    String username = "abc"; //anything
    String password = apiKey; //your apikey
    String encoded = Convert.ToBase64String(Encoding.GetEncoding("ISO-8859-1").GetBytes(username + ":" + password));
    
    client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Basic", encoded);
    

    【讨论】:

      【解决方案4】:

      下面的代码 sn-p 应该可以在 .NET Core 2.1 上使用 Mailchimp API V3.0:

          string url = @"https://" + mailchimpInstance + ".api.mailchimp.com/3.0/lists/" + ListId + "/members";
      
           var info = new Info() { email_address = "example@gmail.com", status = "subscribed" };
              var infoJson = JsonConvert.SerializeObject(info);
      
           using (var client = new HttpClient())
              {
      
                  var uri = "https://" + mailchimpInstance + ".api.mailchimp.com/";
                  var endpoint = "3.0/lists/" + ListId + "/members";
      
                  try
                  {
      
                      client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Basic",ApiKey);
                      client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
      
                      client.BaseAddress = new Uri(uri);
                      var content = new StringContent(infoJson.ToString(), Encoding.UTF8, "application/json");
                       HttpResponseMessage response = await client.PostAsync(endpoint, content);
      
                      var responseString = await response.Content.ReadAsStringAsync();
                      Console.WriteLine("Response from server -> " + responseString);
      
                      return Ok();
      

      【讨论】:

      • 什么是内容,什么是Info(),你的收获在哪里?你是如何设置你的布尔值的?这里缺少太多有用的东西。
      【解决方案5】:

      添加到参考文献MailChimp.Net.dll 比你可以定义一个像

      这样的接口
      IMailChimpManager manager = new MailChimpManager(ConfigurationManager.AppSettings["MailChimpApiKey"].ToString());
      

      您可以在 MailChimp 列表中添加或更新您的客户端

                      Member m = await manager.Members.AddOrUpdateAsync(ConfigurationManager.AppSettings["MailChimpListId"].ToString(), new Member { EmailAddress = _email, EmailType = "html", Status = Status.Pending});
                  m = await manager.Members.AddOrUpdateAsync(ConfigurationManager.AppSettings["MailChimpListId"].ToString(), new Member { EmailAddress = _email, EmailType = "html", Status = Status.Subscribed });
      

      这很简单..我认为...

      【讨论】:

        猜你喜欢
        • 2012-01-07
        • 1970-01-01
        • 1970-01-01
        • 2017-02-11
        • 2020-08-20
        • 2017-05-31
        • 2018-08-21
        • 2020-08-09
        • 2016-06-23
        相关资源
        最近更新 更多