Reputation: 933
I'm trying to subscribe a user to my MailChimp list from Ruby 1.9.3. I've got the following code:
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
Before creating a new Email
, it runs chimp_subscribe
. Unfortunately, it breaks in the request block, with Errno::ECONNRESET
, meaning that MailChimp is resetting my connection.
Am I missing some MailChimp API parameter in here? I'm struggling to find it.
Upvotes: 2
Views: 296
Reputation: 648
The server you are requesting is HTTPS, so you should use SSL.
You should first require it:
require 'openssl'
Then make your request like this:
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)
Upvotes: 2