customerio

package module
v2.0.0+incompatible Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Dec 3, 2020 License: MIT Imports: 12 Imported by: 6

README

Customerio

go-customerio CircleCI

A golang client for the Customer.io event API. Tested with Go1.12

Godoc here: https://godoc.org/github.com/customerio/go-customerio

Installation

Add this line to your application's imports:

import (
    // ...
    "github.com/customerio/go-customerio"
)

And then execute:

go get

Or install it yourself:

$ go get "github.com/customerio/go-customerio"

Usage

Before we get started: API client vs. JavaScript snippet

It's helpful to know that everything below can also be accomplished through the Customer.io JavaScript snippet.

In many cases, using the JavaScript snippet will be easier to integrate with your app, but there are several reasons why using the API client is useful:

  • You're not planning on triggering emails based on how customers interact with your website (e.g. users who haven't visited the site in X days)
  • You're using the javascript snippet, but have a few events you'd like to send from your backend system. They will work well together!
  • You'd rather not have another javascript snippet slowing down your frontend. Our snippet is asynchronous (doesn't affect initial page load) and very small, but we understand.

In the end, the decision on whether or not to use the API client or the JavaScript snippet should be based on what works best for you. You'll be able to integrate fully with Customer.io with either approach.

Setup

Create an instance of the client with your customer.io credentials which can be found on the customer.io integration screen.

track := customerio.NewTrackClient("YOUR SITE ID", "YOUR API SECRET KEY")
Identify logged in customers

Tracking data of logged in customers is a key part of Customer.io. In order to send triggered emails, we must know the email address of the customer. You can also specify any number of customer attributes which help tailor Customer.io to your business.

Attributes you specify are useful in several ways:

  • As customer variables in your triggered emails. For instance, if you specify the customer's name, you can personalize the triggered email by using it in the subject or body.

  • As a way to filter who should receive a triggered email. For instance, if you pass along the current subscription plan (free / basic / premium) for your customers, you can set up triggers which are only sent to customers who have subscribed to a particular plan (e.g. "premium").

You'll want to identify your customers when they sign up for your app and any time their key information changes. This keeps Customer.io up to date with your customer information.

// Arguments
// customerID (required) - a unique identifier string for this customers
// attributes (required) - a ```map[string]interface{}``` of information about the customer. You can pass any
//                         information that would be useful in your triggers. You
//                         should at least pass in an email, and created_at timestamp.
//                         your interface{} should be parseable as Json by 'encoding/json'.Marshal

track.Identify("5", map[string]interface{}{
  "email": "bob@example.com",
  "created_at": time.Now().Unix(),
  "first_name": "Bob",
  "plan": "basic",
})
Deleting customers

Deleting a customer will remove them, and all their information from Customer.io. Note: if you're still sending data to Customer.io via other means (such as the javascript snippet), the customer could be recreated.

// Arguments
// customerID (required) - a unique identifier for the customer.  This
//                          should be the same id you'd pass into the
//                          `identify` command above.

track.Delete("5")
Tracking a custom event

Now that you're identifying your customers with Customer.io, you can now send events like "purchased" or "watchedIntroVideo". These allow you to more specifically target your users with automated emails, and track conversions when you're sending automated emails to encourage your customers to perform an action.

// Arguments
// customerID (required)  - the id of the customer who you want to associate with the event.
// name (required)        - the name of the event you want to track.
// attributes (optional)  - any related information you'd like to attach to this
//                          event, as a ```map[string]interface{}```. These attributes can be used in your triggers to control who should
//                         receive the triggered email. You can set any number of data values.

track.Track("5", "purchase", map[string]interface{}{
    "type": "socks",
    "price": "13.99",
})
Tracking an anonymous event

Anonymous events are also supported. These are ideal for when you need to track an event for a customer which may not exist in your People list.

// Arguments
// name (required)            - the name of the event you want to track.
// attributes (optional)      - any related information you'd like to attach to this
//                              event, as a ```map[string]interface{}```. These attributes can be used in your triggers to control who should
//                              receive the triggered email. You can set any number of data values.

track.TrackAnonymous("invite", map[string]interface{}{
    "first_name": "Alex",
    "source": "OldApp",
})
Adding a device to a customer

In order to send push notifications, we need customer device information.

// Arguments
// customerID (required) - a unique identifier string for this customer
// deviceID (required)   - a unique identifier string for this device
// platform (required)   - the platform of the device, currently only accepts 'ios' and 'andriod'
// data (optional)        - a ```map[string]interface{}``` of information about the device. You can pass any
//                         key/value pairs that would be useful in your triggers. We
//                         currently only save 'last_used'.
//                         your interface{} should be parseable as Json by 'encoding/json'.Marshal

track.AddDevice("5", "messaging token", "android", map[string]interface{}{
"last_used": time.Now().Unix(),
})
Deleting devices

Deleting a device will remove it from the customers device list in Customer.io.

// Arguments
// customerID (required) - the id of the customer the device you want to delete belongs to
// deviceToken (required) - a unique identifier for the device.  This
//                          should be the same id you'd pass into the
//                          `addDevice` command above

track.DeleteDevice("5", "messaging-token")
Send Transactional Messages

To use the Customer.io Transactional API, create an instance of the API client using an app key.

Create a SendEmailRequest instance, and then use SendEmail to send your message. Learn more about transactional messages and optional SendEmailRequest properties.

You can also send attachments with your message. Use Attach to encode attachments.

import "github.com/customerio/go-customerio"

client := customerio.NewAPIClient("<extapikey>");

// TransactionalMessageId — the ID of the transactional message you want to send.
// To                     — the email address of your recipients.
// Identifiers            — contains the id of your recipient. If the id does not exist, Customer.io creates it.
// MessageData            — contains properties that you want reference in your message using liquid.
// Attach                 — a helper that encodes attachments to your message.

request := customerio.SendEmailRequest{
  To: "person@example.com",
  TransactionalMessageID: "3",
  MessageData: map[string]interface{}{
    "name": "Person",
    "items": map[string]interface{}{
      "name": "shoes",
      "price": "59.99",
    },
    "products": []interface{}{},
  },
  Identifiers: map[string]string{
    "id": "example1",
  },
}

// (optional) attach a file to your message.
f, err := os.Open("receipt.pdf")
if err != nil {
  fmt.Println(err)
}
request.Attach("receipt.pdf", f)

body, err := client.SendEmail(context.Background(), &request)
if err != nil {
  fmt.Println(err)
}

fmt.Println(body)

Contributing

  1. Fork it
  2. Clone your fork (git clone git@github.com:MY_USERNAME/go-customerio.git && cd go-customerio)
  3. Create your feature branch (git checkout -b my-new-feature)
  4. Commit your changes (git commit -am 'Added some feature')
  5. Push to the branch (git push origin my-new-feature)
  6. Create new Pull Request

Documentation

Index

Constants

This section is empty.

Variables

View Source
var ErrAttachmentExists = errors.New("attachment with this name already exists")

Functions

This section is empty.

Types

type APIClient

type APIClient struct {
	Key    string
	URL    string
	Client *http.Client
}

func NewAPIClient

func NewAPIClient(key string) *APIClient

NewAPIClient prepares a client for use with the Customer.io API, see: https://customer.io/docs/api/#apicoreintroduction using an App API Key from https://fly.customer.io/settings/api_credentials?keyType=app

func (*APIClient) SendEmail

func (c *APIClient) SendEmail(ctx context.Context, req *SendEmailRequest) (*SendEmailResponse, error)

SendEmail sends a single transactional email using the Customer.io transactional API

type CustomerIO

type CustomerIO struct {
	URL    string
	Client *http.Client
	// contains filtered or unexported fields
}

CustomerIO wraps the customer.io track API, see: https://customer.io/docs/api/#apitrackintroduction

func NewCustomerIO

func NewCustomerIO(siteID, apiKey string) *CustomerIO

NewCustomerIO prepares a client for use with the Customer.io track API, see: https://customer.io/docs/api/#apitrackintroduction deprecated in favour of NewTrackClient

func NewTrackClient

func NewTrackClient(siteID, apiKey string) *CustomerIO

NewTrackClient prepares a client for use with the Customer.io track API, see: https://customer.io/docs/api/#apitrackintroduction using a Tracking Site ID and API Key pair from https://fly.customer.io/settings/api_credentials

func (*CustomerIO) AddDevice added in v1.1.0

func (c *CustomerIO) AddDevice(customerID string, deviceID string, platform string, data map[string]interface{}) error

AddDevice adds a device for a customer

func (*CustomerIO) Delete

func (c *CustomerIO) Delete(customerID string) error

Delete deletes a customer

func (*CustomerIO) DeleteDevice added in v1.1.0

func (c *CustomerIO) DeleteDevice(customerID string, deviceID string) error

DeleteDevice deletes a device for a customer

func (*CustomerIO) Identify

func (c *CustomerIO) Identify(customerID string, attributes map[string]interface{}) error

Identify identifies a customer and sets their attributes

func (*CustomerIO) Track

func (c *CustomerIO) Track(customerID string, eventName string, data map[string]interface{}) error

Track sends a single event to Customer.io for the supplied user

func (*CustomerIO) TrackAnonymous added in v1.1.0

func (c *CustomerIO) TrackAnonymous(eventName string, data map[string]interface{}) error

TrackAnonymous sends a single event to Customer.io for the anonymous user

type CustomerIOError

type CustomerIOError struct {
	// contains filtered or unexported fields
}

CustomerIOError is returned by any method that fails at the API level

func (*CustomerIOError) Error

func (e *CustomerIOError) Error() string

type ParamError

type ParamError struct {
	Param string // Param is the name of the parameter.
}

ParamError is an error returned if a parameter to the track API is invalid.

func (ParamError) Error

func (e ParamError) Error() string

type SendEmailRequest

type SendEmailRequest struct {
	MessageData             map[string]interface{} `json:"message_data,omitempty"`
	TransactionalMessageID  string                 `json:"transactional_message_id,omitempty"`
	Identifiers             map[string]string      `json:"identifiers"`
	Headers                 map[string]string      `json:"headers,omitempty"`
	From                    string                 `json:"from,omitempty"`
	To                      string                 `json:"to,omitempty"`
	ReplyTo                 string                 `json:"reply_to,omitempty"`
	BCC                     string                 `json:"bcc,omitempty"`
	Subject                 string                 `json:"subject,omitempty"`
	Preheader               string                 `json:"preheader,omitempty"`
	Body                    string                 `json:"body,omitempty"`
	PlaintextBody           string                 `json:"plaintext_body,omitempty"`
	AMPBody                 string                 `json:"amp_body,omitempty"`
	FakeBCC                 *bool                  `json:"fake_bcc,omitempty"`
	Attachments             map[string]string      `json:"attachments,omitempty"`
	DisableMessageRetention *bool                  `json:"disable_message_retention,omitempty"`
	SendToUnsubscribed      *bool                  `json:"send_to_unsubscribed,omitempty"`
	EnableTracking          *bool                  `json:"tracked,omitempty"`
	QueueDraft              *bool                  `json:"queue_draft,omitempty"`
}

func (*SendEmailRequest) Attach

func (e *SendEmailRequest) Attach(name string, value io.Reader) error

type SendEmailResponse

type SendEmailResponse struct {
	TransactionalResponse
}

type TransactionalError

type TransactionalError struct {
	// Err is a more specific error message.
	Err string
	// StatusCode is the http status code for the error.
	StatusCode int
}

TransactionalError is returned if a transactional message fails to send.

func (*TransactionalError) Error

func (e *TransactionalError) Error() string

type TransactionalResponse

type TransactionalResponse struct {
	// DeliveryID is a unique id for the given message.
	DeliveryID string `json:"delivery_id"`
	// QueuedAt is when the message was queued.
	QueuedAt time.Time `json:"queued_at"`
}

TransactionalResponse is a response to the send of a transactional message.

func (*TransactionalResponse) UnmarshalJSON

func (t *TransactionalResponse) UnmarshalJSON(b []byte) error

Directories

Path Synopsis

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL