customerio

package module
v1.4.0 Latest Latest
Warning

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

Go to latest
Published: Feb 27, 2023 License: MIT Imports: 12 Imported by: 0

README

CustomerIO (Unofficial Fork)

A golang client for the Customer.io event API. (Visit the Original repo/library)

Release Build Status Report codecov Go


Table of Contents


Installation

go-customerio requires a supported release of Go.

go get -u github.com/mrz1836/go-customerio

Documentation

View the generated documentation

GoDoc

Features
  • Client is completely configurable
  • Using default heimdall http client with exponential backoff & more
  • Use your own custom HTTP client
  • Current coverage for the customer.io API
    • Authentication
      • Find your account region
      • Test Track API keys
    • Customers
      • Add or update a customer
      • Delete a customer
      • Add or update a customer device
      • Delete a customer device
      • Suppress a customer profile
      • Unsuppress a customer profile
      • Custom unsubscribe handling
    • Events
      • Track a customer event
      • Track an anonymous event
      • Report push metrics
    • Transactional Emails
      • Send a transactional email
    • Trigger Broadcasts
      • Trigger a broadcast
      • Get the status of a broadcast
      • List errors from a broadcast
    • Beta API (Customers)
      • Get customers by email
      • Search for customers
      • Lookup a customer's attributes
      • List customers and attributes
      • Lookup a customer's segments
      • Lookup messages sent to a customer
      • Lookup a customer's activities
    • Beta API (Campaigns)
      • List campaigns
      • Get a campaign
      • Get campaign metrics
      • Get campaign link metrics
      • List campaign actions
      • Get campaign message metadata
      • Get a campaign action
      • Update a campaign action
      • Get campaign action metrics
      • Get link metrics for an action
    • Beta API (Newsletters)
      • List newsletters
      • Get a newsletter
      • Get newsletter metrics
      • Get newsletter link metrics
      • List newsletter variants
      • Get newsletter message metadata
      • Get a newsletter variant
      • Update a newsletter variant
      • Get metrics for a variant
      • Get newsletter variant link metrics
    • Beta API (Segments)
      • Create a manual segment
      • List segments
      • Get a segment
      • Delete a segment
      • Get a segment's dependencies
      • Get a segment customer count
      • List customers in a segment
    • Beta API (Messages)
      • List messages
      • Get a message
      • Get an archived message
    • Beta API (Exports)
      • List exports
      • Get an export
      • Download an export
      • Export customer data
      • Export information about deliveries
    • Beta API (Activities)
      • List activities
    • Beta API (Collections)
      • Create a collection
      • List your collections
      • Lookup a collection
      • Delete a collection
      • Update a collection
      • Lookup collection contents
      • Update the contents of a collection
    • Beta API (Sender Identities)
      • List sender identities
      • Get a sender
      • Get sender usage data
    • Beta API (Reporting Webhooks)
      • Create a reporting webhook
      • List reporting webhooks
      • Get a reporting webhook
      • Update a webhook configuration
      • Delete a reporting webhook
      • Reporting webhook format
    • Beta API (Broadcasts)
      • List broadcasts
      • Get a broadcast
      • Get metrics for a broadcast
      • Get broadcast link metrics
      • List broadcast actions
      • Get message metadata for a broadcast
      • Get a broadcast action
      • Update a broadcast action
      • Get broadcast action metrics
      • Get broadcast action link metrics
      • Get broadcast triggers
    • Beta API (Snippets)
      • List snippets
      • Update snippets
      • Delete a snippet
    • Beta API (Info)
      • List IP addresses
Before we get started: API client vs. JavaScript snippet

It's helpful to know that everything (Tracking API) 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 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.

Basic Setup

Create an instance of the client with your Customer.io credentials.

client, err := customerio.NewClient(
    customerio.WithTrackingKey(os.Getenv("TRACKING_SITE_ID"), os.Getenv("TRACKING_API_KEY")),
    customerio.WithRegion(customerio.RegionUS),
)

Your account region—RegionUS or RegionEU—is optional. If you do not specify your region, we assume that your account is based in the US (RegionUS). If your account is based in the EU and you do not provide the correct region, we'll route requests from the US to RegionEU accordingly, however this may cause data to be logged in the US.

Add or Update 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 parsable as Json by 'encoding/json'.Marshal

err = client.UpdateCustomer("123", map[string]interface{}{
  "created_at": time.Now().Unix(),
  "email":      "bob@example.com",
  "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
//                          `UpdateCustomer` command above.

client.DeleteCustomer("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.
// timestamp (optional)   - used for sending events in the past
// 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.

client.NewEvent("5", "purchase", time.Now().UTC(), 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.
// timestamp (optional)       - used for sending events in the past
// 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.

client.NewAnonymousEvent("invite", time.Now().UTC(), 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
// device.ID (required)       - a unique identifier string for this device
// device.Platform (required) - the platform of the device, currently only accepts 'ios' and 'andriod'
// device.LastUsed (optional) - the timestamp the device was last used

client.UpdateDevice("5", &customerio.Device{
  ID:       "1234567890",
  LastUsed: time.Now().UTC().Unix(),
  Platform: customerio.PlatformIOs,
})
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
// deviceID (required)   - a unique identifier for the device.  This
//                          should be the same id you'd pass into the
//                          `UpdateDevice` command above

client.DeleteDevice("5", "1234567890")
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/mrz1836/go-customerio"

client, err := customerio.NewClient(
  customerio.WithAppKey(os.Getenv("APP_API_KEY")),
  customerio.WithRegion(customerio.RegionUS),
)
// 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 := client.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)
Library Deployment

goreleaser for easy binary or library deployment to GitHub and can be installed via: brew install goreleaser.

The .goreleaser.yml file is used to configure goreleaser.

Use make release-snap to create a snapshot version of the release, and finally make release to ship to production.

Makefile Commands

View all makefile commands

make help

List of all current commands:

all                  Runs multiple commands
clean                Remove previous builds and any test cache data
clean-mods           Remove all the Go mod cache
coverage             Shows the test coverage
godocs               Sync the latest tag with GoDocs
help                 Show this help message
install              Install the application
install-go           Install the application (Using Native Go)
lint                 Run the golangci-lint application (install if not found)
release              Full production release (creates release in Github)
release              Runs common.release then runs godocs
release-snap         Test the full release (build binaries)
release-test         Full production test release (everything except deploy)
replace-version      Replaces the version in HTML/JS (pre-deploy)
tag                  Generate a new tag and push (tag version=0.0.0)
tag-remove           Remove a tag if found (tag-remove version=0.0.0)
tag-update           Update an existing tag to current commit (tag-update version=0.0.0)
test                 Runs vet, lint and ALL tests
test-ci              Runs all tests via CI (exports coverage)
test-ci-no-race      Runs all tests via CI (no race) (exports coverage)
test-ci-short        Runs unit tests via CI (exports coverage)
test-short           Runs vet, lint and tests (excludes integration tests)
uninstall            Uninstall the application (and remove files)
update-linter        Update the golangci-lint package (macOS only)
vet                  Run the Go vet application

Examples & Tests

All unit tests and examples run via GitHub Actions and uses Go version(s) 1.17.x. View the configuration file.

Run all tests (including integration tests)

make test

Run tests (excluding integration tests)

make test-short

Benchmarks

Run the Go benchmarks:

make bench

Code Standards

Read more about this Go project's code standards.


Usage

Checkout all the examples!


Maintainers (of the Fork)

This is an "unofficial fork" of the official library and was created to enhance or improve missing functionality.

MrZ
MrZ

Contributing

View the contributing guidelines and follow the code of conduct.

How can I help?

All kinds of contributions are welcome 🙌! The most basic way to show your support is to star 🌟 the project, or to raise issues 💬. You can also support this project by becoming a sponsor on GitHub 👏!

License

License

Documentation

Overview

Package customerio is Golang library for implementing the CustomerIO API following their documentation: https://customer.io/docs/api/

If you have any suggestions or comments, please feel free to open an issue on this GitHub repository!

By CustomerIO (Original repo) By MrZ (Fork of Original repo)

Index

Examples

Constants

This section is empty.

Variables

View Source
var (
	RegionUS = region{
				// contains filtered or unexported fields
	}
	RegionEU = region{
				// contains filtered or unexported fields
	}
)

Current regions available

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

ErrAttachmentExists is the error message if the attachment already exists

Functions

This section is empty.

Types

type APIError added in v1.3.0

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

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

func (*APIError) Error added in v1.3.0

func (a *APIError) Error() string

Error is used to display the error message Escape the returned JSON string will make it easier to consume in other applications

type Client added in v1.3.0

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

Client is the CustomerIO client/configuration

func NewClient added in v1.3.0

func NewClient(opts ...ClientOps) (*Client, error)

NewClient creates a new client for all CustomerIO requests (tracking, app, beta)

If no options are given, it will use the DefaultClientOptions() If no client is supplied it will use a default Resty HTTP client

Example

ExampleNewClient example using NewClient()

See more examples in /examples/

client, err := NewClient(WithTrackingKey(testSiteID, testTrackingAPIKey))
if err != nil {
	fmt.Printf("error loading client: %s", err.Error())
	return
}
fmt.Printf("loaded client: %s", client.options.userAgent)
Output:

loaded client: go-customerio: v1.4.0

func (*Client) DeleteCustomer added in v1.3.0

func (c *Client) DeleteCustomer(customerIDOrEmail string) error

DeleteCustomer will remove a customer given their id or email If not found, a customer will be created. If found, the attributes will be updated See: https://customer.io/docs/api/#operation/delete Only use "email" if the workspace is setup to use email instead of ID

Example

ExampleClient_DeleteCustomer example using DeleteCustomer()

See more examples in /examples/

// Load the client
client, err := newTestClient()
if err != nil {
	fmt.Printf("error loading client: %s", err.Error())
	return
}

mockDeleteCustomer(http.StatusOK, testCustomerID)

// Delete customer
err = client.DeleteCustomer(testCustomerID)
if err != nil {
	fmt.Printf("error deleting customer: " + err.Error())
	return
}
fmt.Printf("customer deleted: %s", testCustomerID)
Output:

customer deleted: 123

func (*Client) DeleteDevice added in v1.3.0

func (c *Client) DeleteDevice(customerIDOrEmail, deviceID string) error

DeleteDevice will remove a customer's device See: https://customer.io/docs/api/#operation/delete_device Only use "email" if the workspace is setup to use email instead of ID

Example

ExampleClient_DeleteDevice example using DeleteDevice()

See more examples in /examples/

// Load the client
client, err := newTestClient()
if err != nil {
	fmt.Printf("error loading client: %s", err.Error())
	return
}

mockDeleteDevice(http.StatusOK, testCustomerID, testDeviceID)

// Delete device
err = client.DeleteDevice(testCustomerID, testDeviceID)
if err != nil {
	fmt.Printf("error deleting device: " + err.Error())
	return
}
fmt.Printf("device deleted: %s", testDeviceID)
Output:

device deleted: abcdefghijklmnopqrstuvwxyz

func (*Client) FindRegion added in v1.3.0

func (c *Client) FindRegion() (region *RegionInfo, err error)

FindRegion will return the url, data center and environment id See: https://customer.io/docs/api/#tag/trackAuth

func (*Client) GetUserAgent added in v1.3.0

func (c *Client) GetUserAgent() string

GetUserAgent will return the user agent string of the client

func (*Client) NewAnonymousEvent added in v1.3.0

func (c *Client) NewAnonymousEvent(eventName string, timestamp time.Time, data map[string]interface{}) error

NewAnonymousEvent will create a new event for the anonymous visitor See: https://customer.io/docs/api/#operation/trackAnonymous AKA: TrackAnonymous() Use "timestamp" to send events in the past. If not set, it will use Now().UTC()

Example

ExampleClient_NewAnonymousEvent example using NewAnonymousEvent()

See more examples in /examples/

// Load the client
client, err := newTestClient()
if err != nil {
	fmt.Printf("error loading client: %s", err.Error())
	return
}

mockNewAnonymousEvent(http.StatusOK)

// New event
err = client.NewAnonymousEvent(
	testEventName, time.Now().UTC(),
	map[string]interface{}{
		"field_name":      "some_value",
		"int_field":       123,
		"timestamp_field": time.Now().UTC().Unix(),
	})
if err != nil {
	fmt.Printf("error creating event: " + err.Error())
	return
}
fmt.Printf("event created: %s", testEventName)
Output:

event created: test_event

func (*Client) NewEvent added in v1.3.0

func (c *Client) NewEvent(customerIDOrEmail string, eventName string, timestamp time.Time,
	data map[string]interface{}) error

NewEvent will create a new event for the supplied customer See: https://customer.io/docs/api/#tag/Track-Events AKA: Track() Only use "email" if the workspace is setup to use email instead of ID Use "timestamp" to send events in the past. If not set, it will use Now().UTC()

Example

ExampleClient_NewEvent example using NewEvent()

See more examples in /examples/

// Load the client
client, err := newTestClient()
if err != nil {
	fmt.Printf("error loading client: %s", err.Error())
	return
}

mockNewEvent(http.StatusOK, testCustomerID)

// New event
err = client.NewEvent(
	testCustomerID, testEventName, time.Now().UTC(),
	map[string]interface{}{
		"field_name":      "some_value",
		"int_field":       123,
		"timestamp_field": time.Now().UTC().Unix(),
	})
if err != nil {
	fmt.Printf("error creating event: " + err.Error())
	return
}
fmt.Printf("event created: %s", testEventName)
Output:

event created: test_event

func (*Client) NewEventUsingInterface added in v1.3.1

func (c *Client) NewEventUsingInterface(customerIDOrEmail string, eventName string, timestamp time.Time,
	data interface{}) error

NewEventUsingInterface is a wrapper for NewEvent() which can take a custom struct vs map[string]interface{} See: https://customer.io/docs/api/#tag/Track-Events AKA: Track() Only use "email" if the workspace is setup to use email instead of ID Use "timestamp" to send events in the past. If not set, it will use Now().UTC()

func (*Client) SendEmail added in v1.3.0

func (c *Client) SendEmail(emailRequest *EmailRequest) (*EmailResponse, error)

SendEmail sends a single transactional email using the Customer.io transactional API See: https://customer.io/docs/api/#tag/Transactional

Example

ExampleClient_SendEmail example using SendEmail()

See more examples in /examples/

// Load the client
client, err := newTestClient()
if err != nil {
	fmt.Printf("error loading client: %s", err.Error())
	return
}

mockSendEmail(http.StatusOK)

// Start the email request (with template)
emailRequestWithTemplate := &EmailRequest{
	TransactionalMessageID: "123",
	Identifiers:            map[string]string{"id": "123"},
	MessageData: map[string]interface{}{
		"name": "Person",
		"items": map[string]interface{}{
			"name":  "shoes",
			"price": "59.99",
		},
		"products": []interface{}{},
	},
	To: "bob@example.com",
}

// Send email
_, err = client.SendEmail(emailRequestWithTemplate)
if err != nil {
	fmt.Printf("error sending email: " + err.Error())
	return
}
fmt.Printf("email sent to: %s", emailRequestWithTemplate.To)
Output:

email sent to: bob@example.com

func (*Client) TestAuth added in v1.3.0

func (c *Client) TestAuth() error

TestAuth will test your current Tracking API credentials See: https://customer.io/docs/api/#tag/trackAuth

func (*Client) UpdateCollection added in v1.3.3

func (c *Client) UpdateCollection(collectionID, collectionName string, items []map[string]interface{}) error

UpdateCollection will create or update a collection with raw data See: https://customer.io/docs/api/#operation/addCollection See: https://customer.io/docs/api/#operation/updateCollection

The name of the collection. This is how you'll reference your collection in message. Updating the data or url for your collection fully replaces the contents of the collection. Data example: {"data":[{"property1":null,"property2":null}]}}

Example

ExampleClient_UpdateCollection example using UpdateCollection()

See more examples in /examples/

// Load the client
client, err := newTestClient()
if err != nil {
	fmt.Printf("error loading client: %s", err.Error())
	return
}

mockNewCollection(http.StatusOK)

// New collection
err = client.UpdateCollection(
	"",
	testCollectionName,
	[]map[string]interface{}{
		{
			"item_name":       "test_item_1",
			"id_field":        1,
			"timestamp_field": time.Now().UTC().Unix(),
		},
		{
			"item_name":       "test_item_2",
			"id_field":        2,
			"timestamp_field": time.Now().UTC().Unix(),
		},
	})
if err != nil {
	fmt.Printf("error creating collection: " + err.Error())
	return
}
fmt.Printf("collection created: %s", testCollectionName)
Output:

collection created: test_collection

func (*Client) UpdateCollectionViaURL added in v1.3.3

func (c *Client) UpdateCollectionViaURL(collectionID, collectionName string, jsonURL string) error

UpdateCollectionViaURL will create or update a collection using a URL to a JSON file See: https://customer.io/docs/api/#operation/addCollection See: https://customer.io/docs/api/#operation/updateCollection

The name of the collection. This is how you'll reference your collection in message.

The URL where your data is stored. If your URL does not include a Content-Type, Customer.io assumes your data is JSON. This URL can also be a google sheet that you've shared with cio_share@customer.io. Updating the data or url for your collection fully replaces the contents of the collection.

Example

ExampleClient_UpdateCollectionViaURL example using UpdateCollectionViaURL()

See more examples in /examples/

// Load the client
client, err := newTestClient()
if err != nil {
	fmt.Printf("error loading client: %s", err.Error())
	return
}

mockNewCollectionViaURL(http.StatusOK)

// New collection
err = client.UpdateCollectionViaURL(
	"",
	testCollectionName,
	testCollectionURL,
)
if err != nil {
	fmt.Printf("error creating collection: " + err.Error())
	return
}
fmt.Printf("collection created: %s", testCollectionName)
Output:

collection created: test_collection

func (*Client) UpdateCustomer added in v1.3.0

func (c *Client) UpdateCustomer(customerIDOrEmail string, attributes map[string]interface{}) error

UpdateCustomer will add/update a customer and sets their attributes If not found, a customer will be created. If found, the attributes will be updated See: https://customer.io/docs/api/#operation/identify AKA: Identify() Only use "email" if the workspace is setup to use email instead of ID

Example

ExampleClient_UpdateCustomer example using UpdateCustomer()

See more examples in /examples/

// Load the client
client, err := newTestClient()
if err != nil {
	fmt.Printf("error loading client: %s", err.Error())
	return
}

mockUpdateCustomer(http.StatusOK, testCustomerID)

// Update customer
err = client.UpdateCustomer(testCustomerID, map[string]interface{}{
	"created_at": time.Now().Unix(),
	"email":      testCustomerEmail,
	"first_name": "Bob",
	"plan":       "basic",
})
if err != nil {
	fmt.Printf("error updating customer: " + err.Error())
	return
}
fmt.Printf("customer updated: %s", testCustomerID)
Output:

customer updated: 123

func (*Client) UpdateDevice added in v1.3.0

func (c *Client) UpdateDevice(customerIDOrEmail string, device *Device) error

UpdateDevice will add/update a customer's device If not found, a device will be created. If found, the attributes will be updated See: https://customer.io/docs/api/#operation/add_device Only use "email" if the workspace is setup to use email instead of ID

Example

ExampleClient_UpdateDevice example using UpdateDevice()

See more examples in /examples/

// Load the client
client, err := newTestClient()
if err != nil {
	fmt.Printf("error loading client: %s", err.Error())
	return
}

mockUpdateDevice(http.StatusOK, testCustomerID)

// Delete customer
err = client.UpdateDevice(testCustomerID, &Device{
	ID:       testDeviceID,
	LastUsed: time.Now().UTC().Unix(),
	Platform: PlatformIOs,
})
if err != nil {
	fmt.Printf("error updating device: " + err.Error())
	return
}
fmt.Printf("device updated: %s", testDeviceID)
Output:

device updated: abcdefghijklmnopqrstuvwxyz

func (*Client) WithCustomHTTPClient added in v1.3.0

func (c *Client) WithCustomHTTPClient(client *resty.Client) *Client

WithCustomHTTPClient will overwrite the default client with a custom client.

type ClientOps added in v1.3.0

type ClientOps func(c *clientOptions)

ClientOps allow functional options to be supplied that overwrite default client options.

func WithAppKey added in v1.3.0

func WithAppKey(appAPIKey string) ClientOps

WithAppKey will provide the App or Beta API key See: https://fly.customer.io/settings/api_credentials?keyType=app

func WithHTTPTimeout added in v1.3.0

func WithHTTPTimeout(timeout time.Duration) ClientOps

WithHTTPTimeout can be supplied to adjust the default http client timeouts. The http client is used when creating requests Default timeout is 20 seconds.

func WithRegion added in v1.3.0

func WithRegion(r region) ClientOps

WithRegion will change the region API endpoints

func WithRequestTracing added in v1.3.0

func WithRequestTracing() ClientOps

WithRequestTracing will enable tracing. Tracing is disabled by default.

func WithRetryCount added in v1.3.0

func WithRetryCount(retries int) ClientOps

WithRetryCount will overwrite the default retry count for http requests. Default retries is 2.

func WithTrackingKey added in v1.3.0

func WithTrackingKey(siteID, trackingAPIKey string) ClientOps

WithTrackingKey will provide the SiteID and Tracking API key See: https://fly.customer.io/settings/api_credentials

func WithUserAgent added in v1.3.0

func WithUserAgent(userAgent string) ClientOps

WithUserAgent will overwrite the default useragent. Default is package name + version.

type Device added in v1.3.0

type Device struct {
	ID       string         `json:"id"`
	LastUsed int64          `json:"last_used"`
	Platform DevicePlatform `json:"platform"`
}

Device is the customer device model

type DevicePlatform added in v1.3.0

type DevicePlatform string

DevicePlatform is the platform for the customer device

const (
	PlatformIOs     DevicePlatform = "ios"
	PlatformAndroid DevicePlatform = "android"
)

Allowed types of platforms

type EmailRequest added in v1.3.0

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

EmailRequest is the request structure for sending an email

func (*EmailRequest) Attach added in v1.3.0

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

Attach will add a new file to the email

type EmailResponse added in v1.3.0

type EmailResponse struct {
	TransactionalResponse
}

EmailResponse is the response from sending the email

type ParamError added in v1.3.0

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 added in v1.3.0

func (p ParamError) Error() string

Error is used to display the error message

type RegionInfo added in v1.3.0

type RegionInfo struct {
	DataCenter    string `json:"data_center"`
	EnvironmentID uint64 `json:"environment_id"`
	URL           string `json:"url"`
}

RegionInfo is the response from FindRegion

type StandardResponse added in v1.3.0

type StandardResponse struct {
	Body       []byte          `json:"-"` // Body of the response request
	StatusCode int             `json:"-"` // Status code returned on the request
	Tracing    resty.TraceInfo `json:"-"` // Trace information if enabled on the request
}

StandardResponse is the standard fields returned on all responses

type TransactionalError added in v1.3.0

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

TransactionalError is returned if a transactional message fails to send.

func (*TransactionalError) Error added in v1.3.0

func (e *TransactionalError) Error() string

Error with display the string error message

type TransactionalResponse added in v1.3.0

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

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

func (*TransactionalResponse) UnmarshalJSON added in v1.3.0

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

UnmarshalJSON will unmarshall the response

Jump to

Keyboard shortcuts

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