Hello Folks,
In this introductory article I will walk you through the steps on how to Add your contacts to MailChimp
I am not going to elaborate / explain about MailChimp here. I am assuming you have basic knowledge about MailChimp (What it does, Why you need it etc.) and you would like to explore / integrate MailChimp to your project.
In the second part of this article, we will see how to:
- Add a tag to a MailChimp contact
- Delete a tag to a MailChimp contact
In the third part of this article, I am going to show how you can send your E-commerce purchases to MailChimp.
Prerequisites:
- A MailChimp account
- Basic knowledge of Ruby programming language
- MailChimp API Key (Obtain it from here: https://mailchimp.com/help/about-api-keys/#Generate_an_API_key)
- MailChimp Audience ID (Obtain it from here: https://mailchimp.com/help/find-audience-id/)
Let’s code it!
1. Add some base before adding a contact or assign a tag
require 'uri'
require 'net/http'
require 'resolv-replace'
module MailchimpUserApi
class MailchimpIntegration
def initialize *args
base_data_center = 'us2'
@base_uri = 'https://' + base_data_center + '.api.mailchimp.com/3.0/'
@base_setup = {
api_key: YOUR_MAILCHIMP_API_KEY,
list_id: YOUR_MAILCHIMP_AUDIENCE_ID
}
end
def make_a_get_request_with uri
req = Net::HTTP::Get.new(uri.to_s)
req.basic_auth 'anystring', @base_setup[:api_key]
response = nil
Net::HTTP.start(uri.host, uri.port, :use_ssl => uri.scheme == 'https', read_timeout: 60, max_retries: 3) do |http|
response = http.request req
end
response = JSON.parse(response.body)
return response
end
def make_a_post_request_with uri, request_body
req = Net::HTTP::Post.new(uri.to_s)
req.body = request_body.to_json
req.basic_auth 'anystring', @base_setup[:api_key]
response = nil
Net::HTTP.start(uri.host, uri.port, :use_ssl => uri.scheme == 'https', read_timeout: 60, max_retries: 3) do |http|
response = http.request req
end
return response
end
def endpoint_for?(action, params = nil)
available_endpoints = {
contact_presence: @base_uri + "lists/" + @base_setup[:list_id] + "/members/" + (params.nil? ? '' : params),
add_contact: @base_uri + "lists/" + @base_setup[:list_id] + "/members/",
update_contact: @base_uri + "lists/" + @base_setup[:list_id] + "/members/" + params.to_s,
all_or_create_segments: @base_uri + "lists/" + @base_setup[:list_id] + "/segments",
list_segments: @base_uri + "lists/" + @base_setup[:list_id] + "/segments?count=200",
add_remove_tag_contact: @base_uri + "lists/" + @base_setup[:list_id] + "/segments/" + (params.nil? ? '' : params),
}
begin
uri = URI.parse available_endpoints[action]
rescue URI::InvalidURIError
uri = URI.parse(URI.escape(available_endpoints[action]))
end
return uri
end
end
end
Here’s what we have done so far:
- Created a base class and initialized it with all configurations
- Created GET and POST HTTP methods
- Created a method with all endpoints mailchimp has and that we will hit to send data to MailChimp
2. Let’s add some code to add a user to MailChimp
require 'uri'
require 'net/http'
require 'resolv-replace'
module MailchimpUserApi
class Contact < MailchimpIntegration
def initialize(user)
@user = user
@email_lookup_hash = Digest::MD5.hexdigest @user["email"].downcase
super
end
def add
exist, resp = contact_already_present?
return true if exist
return create_contact
end
def create_contact(opts={})
uri = endpoint_for?(:add_contact)
request_body = request_hash
response = make_a_post_request_with uri, request_body
return response.code.eql?("200")
end
def request_hash
request_body = {
"email_address" => @user["email"].downcase,
"status" => "subscribed"
}
if @user["name"].present?
request_body = request_body.merge({
"merge_fields" => {
"FNAME" => @user["name"].split(" ")[0],
"LNAME" => @user["name"].split(" ").drop(1).join(" "),
"COMPANY" => @user["company_name"].to_s
}
})
end
request_body
end
def contact_already_present?
uri = endpoint_for?(:contact_presence, @email_lookup_hash)
response = make_a_get_request_with uri
return false, nil if response["status"].eql?(404)
return true, response
end
end
end
Here’s what we are doing:
- Initialize the `Contact` class with user’s email address
- Before adding the contact to MailChimp, we are first checking if the contact exists. If not then only add the contact.
- To test this, here’s what you can do from irb or console:
user = {email: "john_smith@example.com", name: "John Smith", company_name: "Website Builder"}
contact = MailchimpUserApi::Contact.new(user)
contact.add
#or
contact.contact_already_present?
Hope that helps! Implementation is straightforward.
Happy Coding!