Last Updated: February 25, 2016
·
1.317K
· rebyn

Sync User Contacts with Campaign Monitor

At Charity Map we stumbled a while on picking Mailchimp or Campaign Monitor as our email newsletter platform. In the end, Campaign Monitor won a tight game for their awesome API and documentation. And here I'm gonna show you how to keep both your User table and Campaign Monitor subscriber list in sync in order to avoid doing manual tasks like adding new subscribers to the list every once in a while.

First, add Campaign Monitor's Ruby wrapper in your Gemfile

gem 'createsend'

Second, we're gonna use concerns in your User model (more: why is that?)

# models/user.rb
class User < ActiveRecord::Base
  include Monitored
  validates :email, presence: true, uniqueness: true
end

Third, add a new file called monitored.rb to apps/models/concerns

# models/concerns/monitored.rb
require 'createsend'
module Monitored
  extend ActiveSupport::Concern

  included do
    after_create :add_new_subscriber_to_list
  end

  def add_new_subscriber_to_list
    auth = {api_key: ENV['CAMPAIGN_MONITOR_API_KEY']}
    begin
      CreateSend::Subscriber.add auth, '76dc691d424ceab2f5d1ea2f68da79972', self.email, '', [], true
    rescue CreateSend::BadRequest => br
      p 'Error: #{br}'
    end
  end

  handle_asynchronously :add_new_subscriber_to_list
end

A few things are going on here.

  1. I add an after_create callback method named add_new_subscriber_to_list, which will take place when you've created a new user
  2. In add_new_subscriber_to_list, CreateSend::Subscriber takes in the API key, list ID, email and three more parameters. More on required params here
  3. Since you don't want your user to wait a while after signing up for an account (aftercreate you send a POST to the Campaign Monitor API endpoint), I'm offloading this task to a background worker here using delayedjob with handle_asynchronously

And that's all. Now your users' information will always be in sync with Campaign Monitor's list. Happy emailing!