2016-02-14 78 views
2

我試圖從Ruby 1.9.3訂閱用戶到我的MailChimp列表。我有以下代碼:在Ruby中訂閱MailChimp API 3.0的電子郵件

require 'net/http' 
require 'digest/md5' 

class Email < ActiveRecord::Base 
    attr_accessible :email 
    validates :email, :confirmation => true 

    before_create :chimp_subscribe 


    def chimp_subscribe 
     api_key = "my api key" 
     list_id = "my list id" 
     dc = "my data center" 
     member_id = Digest::MD5.hexdigest(self.email) 

     uri = URI.parse("https://" + dc + ".api.mailchimp.com/3.0/lists/" + list_id + "/members/" + member_id) 
     req = Net::HTTP::Put.new(uri.path) 
     req.body = { "email" => self.email, "status" => 'subscribed' }.to_json 
     req.content_type = "application/json" 

     res = Net::HTTP.start(uri.hostname, uri.port) do |http| 
      http.request(req) 
     end 
    end 
end 

之前創建一個新的Email,它運行chimp_subscribe。不幸的是,它在請求塊中斷開,Errno::ECONNRESET,這意味着MailChimp正在重置我的連接。

我錯過了一些MailChimp API參數嗎?我正在努力尋找它。

回答

2

您請求的服務器是HTTPS,因此您應該使用SSL。

你應該首先要求它:

require 'openssl' 

然後,讓你的要求是這樣的:

http = Net::HTTP.new(uri.host, uri.port) 
http.use_ssl = true 
http.verify_mode = OpenSSL::SSL::VERIFY_NONE # You should use VERIFY_PEER in production 
res = http.request(req) 
+0

後續:我收到401未授權。我添加了一個帶有「username:apikey」的授權標頭作爲它的值,但401仍然存在。有小費嗎? –