suprsend

package module
v0.5.1 Latest Latest
Warning

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

Go to latest
Published: Apr 18, 2024 License: MIT Imports: 25 Imported by: 0

README

suprsend-go

SuprSend Go SDK

Installation

go get github.com/suprsend/suprsend-go

Usage

Initialize the SuprSend SDK

import (
	"log"

	suprsend "github.com/suprsend/suprsend-go"
)

func main() {
    opts := []suprsend.ClientOption{
		// suprsend.WithDebug(true),
	}
    suprClient, err := suprsend.NewClient("__api_key__", "__api_secret__", opts...)
	if err != nil {
		log.Println(err)
	}
}

Trigger Workflow
package main

import (
	"log"

	suprsend "github.com/suprsend/suprsend-go"
)

func main() {
	// Instantiate Client
	suprClient, err := suprsend.NewClient("__api_key__", "__api_secret__")
	if err != nil {
		log.Println(err)
		return
	}
	// Create workflow body
	wfBody := map[string]interface{}{
		"name":                  "Workflow Name",
		"template":              "template slug",
		"notification_category": "category",
		// "delay":                 "15m", // Chek duration format in documentation
		"users": []map[string]interface{}{
			{
				"distinct_id": "0f988f74-6982-41c5-8752-facb6911fb08",
				// if $channels is present, communication will be tried on mentioned channels only.
				// "$channels": []string{"email"},
				"$email": []string{"user@example.com"},
				"$androidpush": []map[string]interface{}{
					{"token": "__android_push_token__", "provider": "fcm", "device_id": ""},
				},
			},
		},
		// delivery instruction. how should notifications be sent, and whats the success metric
		"delivery": map[string]interface{}{
			"smart":   false,
			"success": "seen",
		},
		// # data can be any json / serializable python-dictionary
		"data": map[string]interface{}{
			"first_name":   "User",
			"spend_amount": "$10",
			"nested_key_example": map[string]interface{}{
				"nested_key1": "some_value_1",
				"nested_key2": map[string]interface{}{
					"nested_key3": "some_value_3",
				},
			},
		},
	}

	wf := &suprsend.Workflow{
		Body:           wfBody,
		IdempotencyKey: "",
		TenantId:        "",
	}
    // Call TriggerWorkflow to send request to Suprsend
	_, err = suprClient.TriggerWorkflow(wf)
	if err != nil {
		log.Fatalln(err)
	}
}


Check SuprSend docs here https://docs.suprsend.com/docs

Check examples directory to understand how to use different functionalities.

Documentation

Index

Constants

View Source
const (
	//
	VERSION = "0.5.0"
	//
	DEFAULT_URL = "https://hub.suprsend.com/"

	// an Event should not have apparent body size of more than 100KB
	SINGLE_EVENT_MAX_APPARENT_SIZE_IN_BYTES          = 100 * 1024
	SINGLE_EVENT_MAX_APPARENT_SIZE_IN_BYTES_READABLE = "100KB"

	// a API call should not have apparent body size of more than 800KB
	BODY_MAX_APPARENT_SIZE_IN_BYTES          = 800 * 1024
	BODY_MAX_APPARENT_SIZE_IN_BYTES_READABLE = "800KB"

	// in general url-size wont exceed 2048 chars or 2048 utf-8 bytes
	ATTACHMENT_URL_POTENTIAL_SIZE_IN_BYTES = 2100

	// few keys added in-flight, amounting to almost 200 bytes increase per workflow-body
	WORKFLOW_RUNTIME_KEYS_POTENTIAL_SIZE_IN_BYTES = 200

	// max workflow-records in one bulk api call.
	MAX_WORKFLOWS_IN_BULK_API = 100

	// max event-records in one bulk api call
	MAX_EVENTS_IN_BULK_API = 100

	ALLOW_ATTACHMENTS_IN_BULK_API = true

	ATTACHMENT_UPLOAD_ENABLED = false

	// single Identity event limit
	IDENTITY_SINGLE_EVENT_MAX_APPARENT_SIZE_IN_BYTES          = 10 * 1024
	IDENTITY_SINGLE_EVENT_MAX_APPARENT_SIZE_IN_BYTES_READABLE = "10KB"

	MAX_IDENTITY_EVENTS_IN_BULK_API = 400

	// time.RFC1123
	HEADER_DATE_FMT = "Mon, 02 Jan 2006 15:04:05 GMT"
)
View Source
const (
	IDENT_KEY_EMAIL       = "$email"
	IDENT_KEY_SMS         = "$sms"
	IDENT_KEY_ANDROIDPUSH = "$androidpush"
	IDENT_KEY_IOSPUSH     = "$iospush"
	IDENT_KEY_WHATSAPP    = "$whatsapp"
	IDENT_KEY_WEBPUSH     = "$webpush"
	IDENT_KEY_SLACK       = "$slack"
	IDENT_KEY_MS_TEAMS    = "$ms_teams"
)

---------- Identity keys

View Source
const (
	KEY_PUSHVENDOR         = "$pushvendor"
	KEY_PREFERRED_LANGUAGE = "$preferred_language"
	KEY_TIMEZONE           = "$timezone"
)
View Source
const EMAIL_REGEX = "^\\S+@\\S+\\.\\S+$"
View Source
const MOBILE_REGEX = "^\\+[0-9\\s]+"

---------

Variables

View Source
var (
	ErrMissingAPIKey    = errors.New("suprsend: missing api_key")
	ErrMissingAPISecret = errors.New("suprsend: missing api_secret")
	ErrMissingBaseUrl   = errors.New("suprsend: missing base_url")
)
View Source
var LANG_CODE_NAME_MAPPING = map[string]string{}/* 183 elements not displayed */
View Source
var OTHER_RESERVED_KEYS = []string{
	"$messenger", "$inbox",
	KEY_PUSHVENDOR, "$device_id",
	"$insert_id", "$time",
	"$set", "$set_once", "$add", "$append", "$remove", "$unset",
	"$identify", "$anon_id", "$identified_id",
	KEY_PREFERRED_LANGUAGE, KEY_TIMEZONE,
	"$notification_delivered", "$notification_dismiss", "$notification_clicked",
}
View Source
var RESERVED_EVENT_NAMES = []string{
	"$identify",
	"$notification_delivered", "$notification_dismiss", "$notification_clicked",
	"$app_launched", "$user_login", "$user_logout",
}
View Source
var SUPER_PROPERTY_KEYS = []string{
	"$app_version_string", "$app_build_number", "$brand", "$carrier", "$manufacturer", "$model", "$os",
	"$ss_sdk_version", "$insert_id", "$time",
}

Functions

func Bool added in v0.4.0

func Bool(x bool) *bool

func Contains

func Contains(s []string, str string) bool

func CurrentTimeFormatted

func CurrentTimeFormatted() string

func GetAttachmentJson

func GetAttachmentJson(filePath string, ao *AttachmentOption) (map[string]interface{}, error)

func GetSchema

func GetSchema(schemaName string) (*gojsonschema.Schema, error)

Returns schema from memory cache. If not already in memory, loads it from the file system. Returns error if either schema-file is not present or has invalid jsonschema format

func String

func String(x string) *string

Types

type AttachmentOption

type AttachmentOption struct {
	// overrides filename of attachment, otherwise filename is picked from the filepath
	FileName string
	// ignore attachment if there is issue while accessing/downloading attachment from url
	// applicable when filepath is a url.
	IgnoreIfError bool
}

type Brand

type Brand struct {
	BrandId   *string `json:"brand_id,omitempty"`
	BrandName *string `json:"brand_name,omitempty"`
	//
	BlockedChannels        []string `json:"blocked_channels"`
	EmbeddedPreferenceUrl  *string  `json:"embedded_preference_url,omitempty"`
	HostedPreferenceDomain *string  `json:"hosted_preference_domain,omitempty"`
	//
	PrimaryColor   *string                `json:"primary_color,omitempty"`
	SecondaryColor *string                `json:"secondary_color,omitempty"`
	TertiaryColor  *string                `json:"tertiary_color,omitempty"`
	SocialLinks    *BrandSocialLinks      `json:"social_links,omitempty"`
	Properties     map[string]interface{} `json:"properties,omitempty"`
}

type BrandList

type BrandList struct {
	Meta    *ListApiMetaInfo `json:"meta"`
	Results []*Brand         `json:"results"`
}

type BrandListOptions

type BrandListOptions struct {
	Limit  int
	Offset int
}
type BrandSocialLinks struct {
	Website   *string `json:"website,omitempty"`
	Facebook  *string `json:"facebook,omitempty"`
	Linkedin  *string `json:"linkedin,omitempty"`
	Twitter   *string `json:"twitter,omitempty"`
	Instagram *string `json:"instagram,omitempty"`
	Medium    *string `json:"medium,omitempty"`
	Discord   *string `json:"discord,omitempty"`
	Telegram  *string `json:"telegram,omitempty"`
	Youtube   *string `json:"youtube,omitempty"`
}

type BrandsService

type BrandsService interface {
	Get(context.Context, string) (*Brand, error)
	Upsert(context.Context, string, *Brand) (*Brand, error)
	List(context.Context, *BrandListOptions) (*BrandList, error)
}

Brand has been renamed to Tenant. Brand is kept for backward-compatibilty. Use Tenant instead of Brand

type BulkEvents

type BulkEvents interface {
	Append(...*Event)
	Trigger() (*BulkResponse, error)
}

type BulkResponse

type BulkResponse struct {
	Status        string
	FailedRecords []map[string]interface{}
	Total         int
	Success       int
	Failure       int
	Warnings      []string
}

func (BulkResponse) String added in v0.3.0

func (r BulkResponse) String() string

type BulkSubscribers

type BulkSubscribers interface {
	Append(subscribers ...Subscriber)
	Save() (*BulkResponse, error)
}

type BulkWorkflows

type BulkWorkflows interface {
	Append(...*Workflow)
	Trigger() (*BulkResponse, error)
}

type BulkWorkflowsTrigger added in v0.5.0

type BulkWorkflowsTrigger interface {
	Append(...*WorkflowTriggerRequest)
	Trigger() (*BulkResponse, error)
}

type Client

type Client struct {
	ApiKey    string
	ApiSecret string
	//
	Users           *subscribersService
	Tenants         *tenantsService
	Brands          *brandsService
	SubscriberLists *subscriberListsService
	Workflows       *workflowsService
	// todo: Deprecated: this
	BulkWorkflows *bulkWorkflowsService
	//
	BulkEvents *bulkEventsService
	BulkUsers  *bulkSubscribersService
	// contains filtered or unexported fields
}

func NewClient

func NewClient(apiKey string, apiSecret string, opts ...ClientOption) (*Client, error)

func (*Client) TrackEvent

func (c *Client) TrackEvent(event *Event) (*Response, error)

func (*Client) TriggerWorkflow

func (c *Client) TriggerWorkflow(wf *Workflow) (*Response, error)

todo: Deprecated: this

type ClientOption

type ClientOption func(c *Client) error

func WithBaseUrl

func WithBaseUrl(baseUrl string) ClientOption

func WithDebug

func WithDebug(debug bool) ClientOption

func WithHTTPClient

func WithHTTPClient(client *http.Client) ClientOption

func WithTimeout

func WithTimeout(timeoutInSeconds int) ClientOption

type Event

type Event struct {
	DistinctId     string
	EventName      string
	Properties     map[string]interface{}
	IdempotencyKey string
	TenantId       string
	// Brand has been renamed to Tenant. Brand is kept for backward-compatibilty.
	// Use Tenant instead of Brand
	BrandId string
}

func (*Event) AddAttachment

func (e *Event) AddAttachment(filePath string, ao *AttachmentOption) error

type ListApiMetaInfo

type ListApiMetaInfo struct {
	Count  int `json:"count"`
	Limit  int `json:"limit"`
	Offset int `json:"offset"`
}

type LoggingRoundTripper

type LoggingRoundTripper struct {
	Proxied http.RoundTripper
}

func (LoggingRoundTripper) RoundTrip

func (l LoggingRoundTripper) RoundTrip(req *http.Request) (res *http.Response, e error)

type Response

type Response struct {
	Success    bool   `json:"success"`
	StatusCode int    `json:"status_code"`
	Message    string `json:"message"`
}

func (Response) String added in v0.3.0

func (r Response) String() string

type Subscriber

type Subscriber interface {
	Save() (*Response, error)
	//
	AppendKV(string, interface{})
	Append(map[string]interface{})
	SetKV(string, interface{})
	Set(map[string]interface{})
	SetOnceKV(string, interface{})
	SetOnce(map[string]interface{})
	IncrementKV(string, interface{})
	Increment(map[string]interface{})
	RemoveKV(string, interface{})
	Remove(map[string]interface{})
	Unset([]string)
	//
	SetPreferredLanguage(string)
	SetTimezone(string)
	//
	AddEmail(value string)
	RemoveEmail(value string)
	//
	AddSms(value string)
	RemoveSms(value string)
	//
	AddWhatsapp(value string)
	RemoveWhatsapp(value string)
	//
	AddAndroidpush(value, provider string)
	RemoveAndroidpush(value, provider string)
	//
	AddIospush(value, provider string)
	RemoveIospush(value, provider string)
	//
	AddWebpush(value map[string]interface{}, provider string)
	RemoveWebpush(value map[string]interface{}, provider string)
	//
	AddSlack(value map[string]interface{})
	RemoveSlack(value map[string]interface{})
	//
	AddMSTeams(value map[string]interface{})
	RemoveMSTeams(value map[string]interface{})
}

type SubscriberList added in v0.3.0

type SubscriberList struct {
	ListId          string `json:"list_id,omitempty"`
	ListName        string `json:"list_name,omitempty"`
	ListDescription string `json:"list_description,omitempty"`
	ListType        string `json:"list_type,omitempty"`
	//
	SubscribersCount int    `json:"subscribers_count,omitempty"`
	Source           string `json:"source,omitempty"`
	IsReadonly       bool   `json:"is_readonly,omitempty"`
	Status           string `json:"status,omitempty"`
	//
	TrackUserEntry bool `json:"track_user_entry,omitempty"`
	TrackUserExit  bool `json:"track_user_exit,omitempty"`
	//
	CreatedAt string `json:"created_at,omitempty"`
	UpdatedAt string `json:"updated_at,omitempty"`
	// version_id will be present its a draft version
	VersionId string `json:"version_id,omitempty"`
	// drafts will be present if there are any drafts started from this list
	Drafts []*SubscriberListVersion `json:"drafts,omitempty"`
}

type SubscriberListAll added in v0.3.0

type SubscriberListAll struct {
	Meta    *ListApiMetaInfo  `json:"meta"`
	Results []*SubscriberList `json:"results"`
}

GetAll response

type SubscriberListAllOptions added in v0.3.0

type SubscriberListAllOptions struct {
	Limit  int
	Offset int
}

GetAll options

type SubscriberListBroadcast added in v0.3.0

type SubscriberListBroadcast struct {
	Body           map[string]interface{}
	IdempotencyKey string
	TenantId       string
	// Brand has been renamed to Tenant. BrandId is kept for backward-compatibilty.
	// Use TenantId instead of BrandId
	BrandId string
}

Broadcast request params on SubscriberList

func (*SubscriberListBroadcast) AddAttachment added in v0.3.0

func (s *SubscriberListBroadcast) AddAttachment(filePath string, ao *AttachmentOption) error

type SubscriberListCreateInput added in v0.3.0

type SubscriberListCreateInput struct {
	ListId          string `json:"list_id,omitempty"`
	ListName        string `json:"list_name,omitempty"`
	ListDescription string `json:"list_description,omitempty"`
	//
	TrackUserEntry *bool `json:"track_user_entry,omitempty"`
	TrackUserExit  *bool `json:"track_user_exit,omitempty"`
	// list_type enums: query_based, static_list
	ListType *string `json:"list_type,omitempty"`
	// Query: applicable when list_type='query_based'
	Query *string `json:"query,omitempty"`
}

Create subscriberlist request input

type SubscriberListVersion added in v0.4.0

type SubscriberListVersion struct {
	VersionId        string `json:"version_id,omitempty"`
	SubscribersCount int    `json:"subscribers_count,omitempty"`
	CreatedAt        string `json:"created_at,omitempty"`
	UpdatedAt        string `json:"updated_at,omitempty"`
}

type Tenant added in v0.4.0

type Tenant struct {
	TenantId   *string `json:"tenant_id,omitempty"`
	TenantName *string `json:"tenant_name,omitempty"`
	//
	BlockedChannels        []string `json:"blocked_channels"`
	EmbeddedPreferenceUrl  *string  `json:"embedded_preference_url,omitempty"`
	HostedPreferenceDomain *string  `json:"hosted_preference_domain,omitempty"`
	//
	PrimaryColor   *string                `json:"primary_color,omitempty"`
	SecondaryColor *string                `json:"secondary_color,omitempty"`
	TertiaryColor  *string                `json:"tertiary_color,omitempty"`
	SocialLinks    *TenantSocialLinks     `json:"social_links,omitempty"`
	Properties     map[string]interface{} `json:"properties,omitempty"`
}

type TenantList added in v0.4.0

type TenantList struct {
	Meta    *ListApiMetaInfo `json:"meta"`
	Results []*Tenant        `json:"results"`
}

type TenantListOptions added in v0.4.0

type TenantListOptions struct {
	Limit  int
	Offset int
}
type TenantSocialLinks struct {
	Website   *string `json:"website,omitempty"`
	Facebook  *string `json:"facebook,omitempty"`
	Linkedin  *string `json:"linkedin,omitempty"`
	Twitter   *string `json:"twitter,omitempty"`
	Instagram *string `json:"instagram,omitempty"`
	Medium    *string `json:"medium,omitempty"`
	Discord   *string `json:"discord,omitempty"`
	Telegram  *string `json:"telegram,omitempty"`
	Youtube   *string `json:"youtube,omitempty"`
}

type TenantsService added in v0.4.0

type TenantsService interface {
	Get(context.Context, string) (*Tenant, error)
	Upsert(context.Context, string, *Tenant) (*Tenant, error)
	List(context.Context, *TenantListOptions) (*TenantList, error)
	Delete(context.Context, string) error
}

type Workflow

type Workflow struct {
	Body           map[string]interface{}
	IdempotencyKey string
	TenantId       string
	// Brand has been renamed to Tenant. Brand is kept for backward-compatibilty.
	// Use TenantId instead of BrandId
	BrandId string
}

todo: Deprecated: this

func (*Workflow) AddAttachment

func (w *Workflow) AddAttachment(filePath string, ao *AttachmentOption) error

type WorkflowTriggerRequest added in v0.5.1

type WorkflowTriggerRequest struct {
	Body            map[string]interface{}
	IdempotencyKey  string
	TenantId        string
	CancellationKey string
}

func (*WorkflowTriggerRequest) AddAttachment added in v0.5.1

func (w *WorkflowTriggerRequest) AddAttachment(filePath string, ao *AttachmentOption) error

type WorkflowsService added in v0.5.0

type WorkflowsService interface {
	Trigger(*WorkflowTriggerRequest) (*Response, error)
	BulkTriggerInstance() BulkWorkflowsTrigger
}

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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