Skip to content

Instantly share code, notes, and snippets.

@jrallison
Created May 1, 2012 19:59
Show Gist options
  • Save jrallison/2570936 to your computer and use it in GitHub Desktop.
Save jrallison/2570936 to your computer and use it in GitHub Desktop.
Simple Customer.io API client in Ruby using HTTParty.
# Simple Customer.io API client in Ruby (1.9 syntax) using HTTParty.
# Uses https://github.com/jnunemaker/httparty for all the heavy lifting.
#
# Usage:
#
# client = Customerio.new("YOUR SITE ID", "YOUR API SECRET KEY")
#
# # Identifying a user with user attributes
# user.email = "[email protected]"
# client.identify(user, { first_name: "Bob", plan: "basic" })
#
# # Tracking a custom event
# client.track(user, name: "purchase", data: { type: "socks", price: "13.99" })
#
class Customerio
include HTTParty
base_uri 'https://app.customer.io'
def initialize(site_id, secret_key)
@auth = { username: site_id, password: secret_key }
end
def identify(customer, attributes= {})
create_or_update(customer, attributes)
end
def track(customer, hash)
create_or_update(customer)
create_event(customer, hash)
end
private
def create_or_update(customer, attributes = {})
body = {
id: customer.id,
email: customer.email,
created_at: customer.created_at.to_i
}.merge(attributes)
self.class.put(customer_path(customer), options.merge(body: body))
end
def create_event(customer, hash)
self.class.post("#{customer_path(customer)}/events", options.merge(body: hash))
end
def customer_path(customer)
"/api/v1/customers/#{customer.id}"
end
def options
{ basic_auth: @auth }
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment