【问题标题】:Mailchimp API v3 create list REST Client RubyMailchimp API v3 创建列表 REST 客户端 Ruby
【发布时间】:2017-04-24 13:17:03
【问题描述】:

我正在尝试使用 Mailchimps API (v3) 和 REST Client gem create 一个 Mailchimp 列表。我已经正常工作以检索列表名称和 ID。但是,我收到了401 Unauthorized - API Key Missing 响应以创建列表。我认为我的帖子请求格式不正确,但我无法确定我哪里出错了。我的代码如下所示:

params_hash = {
  name: "#{territory}",
  contact: {
    company: "Company",
    address1: "Address",
    city: "City",
    state: "State",
    zip: "0000",
    country: "US"
  },
  permission_reminder: "You are receiving this email because....",
  campaign_defaults: {
    from_name: "From Name",
    from_email: "contact@contact.com",
    subject: "Subject",
    language: "en"
  },
  notify_on_subscribe: "contact1@contact.com",
  notify_on_unsubscribe: "contact1@contact.com",
  email_type_option: true,
  apikey: mailchimp_key
}

RestClient.post("#{mailchimp_url}/lists", { params: params_hash }) { |response, request, result, &block|

}

【问题讨论】:

    标签: ruby-on-rails ruby rest mailchimp mailchimp-api-v3.0


    【解决方案1】:

    您不应在有效负载中传递您的 API 密钥,而应使用 HTTP Basic Authentication。 RestClient 确实支持这一点,但这有点尴尬。如果您想使用 RestClient 快捷方式,您可以修改您的 URL 以包含用户名/密码,如下所示:https://username:api_key@us1.api.mailchimp.com -- 用户名对 MailChimp 无关紧要,但它是基本身份验证所必需的,因此您可以传递任何内容。

    或者,您可以直接使用 RestClient 的 Request class,将您的请求改为:

    RestClient::Request.execute(method: :post, url: "#{mailchimp_url}/lists", payload: params_hash, user: 'anything', password: mailchimp_key)
    

    但是,说实话? RestClient 不是很好。我更喜欢HTTParty,它允许您创建非常轻量级的包装器,并为您设置很多默认值,或者像 RestClient 一样使用它,但 API 更友好:

    HTTParty.post("#{mailchimp_url}/lists", body: params_hash, basic_auth: {username: 'whatever', password: mailchimp_key})
    

    【讨论】:

    • 感谢您的回复。我同意 RestClient 很尴尬。然而,我觉得将用户名设置为任何东西都很奇怪——这可能会让其他从事该项目的开发人员感到困惑。我设法使用以下方法使其工作:RestClient.post("#{mailchimp_url}/lists", params_hash, {:Authorization => "apikey #{mailchimp_key}"})。你觉得这有什么问题吗?
    • 你说得对,HTTParty 比 RestClient 好得多。感谢您的帮助。
    • 我明白你在说什么,是的。 MC 目前支持这种格式,但它是非常自定义的。这不太可能有所作为,我只是倾向于认为基本身份验证比自定义标题更容易阅读,所以我这样做了,但这是个人喜好。另外,我通常将用户名设置为帐户的实际用户名,但这只是我的习惯而不是要求。
    • 另外:根据您的基本身份验证客户端,您可能根本不需要传递用户名,它可能只发送一个空白用户名,这对于 MC 应该同样有效。
    • 我正在切换到 HTTParty - 你是对的 basic_auth 更容易阅读。现在所有对 API 的请求都遵循相同的模式 - 好多了!我找到了您的以下内容:github.com/mailchimp/APIv3-examples/pull/12/files 您将 api 密钥设置为用户名。我也这样做了,只是添加了 cmets,这对于其他任何使用该实现的人来说应该是清楚的。再次感谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-10-12
    • 1970-01-01
    • 1970-01-01
    • 2018-01-24
    • 2020-12-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多