magicbell

package module
v0.0.0-...-5e2b71b Latest Latest
Warning

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

Go to latest
Published: Mar 2, 2023 License: MIT Imports: 12 Imported by: 0

README

magicbell-go: Unofficial Go API Library for MagicBell

Go Reference mbctl

This is still a work in progress, expect breaking changes until v1.0.0

What is MagicBell?

See https://magicbell.io/.

Library Installation

go get -u github.com/tizz98/magicbell-go

Library Usage

Send Notification
package main

import (
	"fmt"

	"github.com/ecoralic/magicbell-go"
)

func main() {
	magicbell.Init(magicbell.Config{
		APIKey:    "my-key",
		APISecret: "my-secret",
	})

	notification, _ := magicbell.CreateNotification(magicbell.CreateNotificationRequest{
		Title: "Welcome to MagicBell",
		Recipients: []magicbell.NotificationRecipient{
			{Email: "hana@magicbell.io"},
			{ExternalID: "some-id"},
        },
		Content: "The notification inbox for your product. Get started in minutes.",
		CustomAttributes: map[string]interface{}{
			"order": map[string]string{
				"id": "1234567",
				"title": "A title you can use in your templates",
			},
		},
		ActionURL: "https://developer.magicbell.io",
		Category:  "new_message",
	})
	fmt.Printf("Created notification %s\n", notification.ID)
}
Create user
package main

import (
	"fmt"
	
	"github.com/ecoralic/magicbell-go"
)

func main() {
	magicbell.Init(magicbell.Config{
		APIKey:    "my-key",
		APISecret: "my-secret",
	})

	user, _ := magicbell.CreateUser(magicbell.CreateUserRequest{
		ExternalID: "56780",
		Email:      "hana@magicbell.io",
		FirstName:  "Hana",
		LastName:   "Mohan",
		CustomAttributes: map[string]interface{}{
			"plan":              "enterprise",
			"pricing_version":   "v10",
			"preferred_pronoun": "She",
		},
	})

	fmt.Printf("%#v\n", user)
}

mbctl CLI Installation

Download the latest release for your OS from https://github.com/tizz98/magicbell-go/releases and add the binary to your PATH.

mbctl CLI Usage

mbctl --version
mbctl --help
Initialize Config

This will save your API key and API secret in a config.yaml file.

mbctl config init
Notification Commands

Commands related to Notifications.

Create Notification

Send a notification to a set of users. Separate multiple recipients with a comma. Any string with an @ will be considered an email address and sent to the API in that field.

mbctl notifications create \
  --title="CLI test" \
  --recipients hana@magicbell.io,foo@example.com,my-external-id \
  --content="Notification content" \
  --action-url https://google.com \
  --category new_message
User Commands

Commands related to Users.

Generate HMAC

Generate and return a base64-encoded HMAC signature of the provided email. The HMAC key is the API secret.

mbctl users generate-hmac hana@magicbell.io

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func GenerateUserEmailHMAC

func GenerateUserEmailHMAC(userEmail string) string

GenerateUserEmailHMAC is a global shortcut to API.GenerateUserEmailHMAC

func Init

func Init(config Config)

Init initializes the global MagicBell API. This allows for shorthand access to all the API methods instead of instantiating and managing your own IAPI instance.

func IsAPIErrors

func IsAPIErrors(err error) bool

IsAPIErrors returns true when err is not nil and is an instance of APIErrors

func IsInternalServerError

func IsInternalServerError(err error) bool

IsInternalServerError returns true when the underlying error is an InternalServerError

Types

type API

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

API implements the IAPI interface for making HTTP requests to the MagicBell API. Use New to instantiate this struct.

func (*API) CreateNotification

func (a *API) CreateNotification(req CreateNotificationRequest) (*BaseNotification, error)

CreateNotification sends a notification to one or multiple users.

func (*API) CreateNotificationC

func (a *API) CreateNotificationC(ctx context.Context, req CreateNotificationRequest) (*BaseNotification, error)

CreateNotificationC sends a notification to one or multiple users, using a context.Context in the HTTP request.

func (*API) CreateUser

func (a *API) CreateUser(req CreateUserRequest) (*User, error)

CreateUser creates a new user in MagicBell. Please note that you must provide the user's email or the external id so MagicBell can uniquely identify the user. The external id, if provided, must be unique to the user.

func (*API) CreateUserC

func (a *API) CreateUserC(ctx context.Context, req CreateUserRequest) (*User, error)

CreateUserC creates a new user in MagicBell, using a context.Context in the HTTP request. Please note that you must provide the user's email or the external id so MagicBell can uniquely identify the user. The external id, if provided, must be unique to the user.

func (*API) GenerateUserEmailHMAC

func (a *API) GenerateUserEmailHMAC(userEmail string) string

GenerateUserEmailHMAC generates a sha256 HMAC signature of the user's email using the APISecret as the HMAC key. The returned value is a base64 encoded string of the resulting HMAC signature. See https://developer.magicbell.io/reference#performing-api-requests-from-javascript

func (*API) RoundTrip

func (a *API) RoundTrip(r *http.Request) (*http.Response, error)

RoundTrip implements the http.RoundTripper interface and is used for the API's http.Client http.Transport. This method will automatically add the Config.APIKey and Config.APISecret as headers for all HTTP requests. After doing so, the http.DefaultTransport will be used to finish making the request.

func (*API) UpdateUser

func (a *API) UpdateUser(userID string, req UpdateUserRequest) (*User, error)

UpdateUser updates a user in MagicBell with the given ID. The user id is the MagicBell user id. Alternatively, provide an id like email:theusersemail@example.com or external_id:theusersexternalid as the user id.

func (*API) UpdateUserC

func (a *API) UpdateUserC(ctx context.Context, userID string, req UpdateUserRequest) (*User, error)

UpdateUserC updates a user in MagicBell with the given ID, using a context.Context in the HTTP request. The user id is the MagicBell user id. Alternatively, provide an id like email:theusersemail@example.com or external_id:theusersexternalid as the user id.

type APIError

type APIError struct {
	Code       APIErrorCode `json:"code"`
	Suggestion string       `json:"suggestion"`
	Message    string       `json:"message"`
	HelpLink   string       `json:"help_link"`
}

APIError represents a single error returned from the MagicBell API. It's unclear which fields are mandatory to be returned, so only count on APIError.Code being set and check the other fields for being empty strings before use.

func (APIError) Error

func (e APIError) Error() string

Error returns the message contained in this APIError or the APIErrorCode if no message is set.

func (APIError) IsCode

func (e APIError) IsCode(c APIErrorCode) bool

IsCode returns true when the provided APIErrorCode matches the stored APIError.Code

type APIErrorCode

type APIErrorCode string

APIErrorCode is a string returned from the API that represents some known error state. See https://developer.magicbell.io/reference#error-codes

const (
	// APIErrorCodeAPIKeyNotProvided is returned when no API key was provided with the HTTP request
	APIErrorCodeAPIKeyNotProvided APIErrorCode = "api_key_not_provided"
	// APIErrorCodeIncorrectAPIKey is returned when an API key was provided but is not valid
	APIErrorCodeIncorrectAPIKey APIErrorCode = "incorrect_api_key"
	// APIErrorCodeAPISecretNotProvided is returned when no API secret was provided with the HTTP request
	APIErrorCodeAPISecretNotProvided APIErrorCode = "api_secret_not_provided"
	// APIErrorCodeAPISecretIsIncorrect is returned when an API secret was provided but is not valid
	APIErrorCodeAPISecretIsIncorrect APIErrorCode = "api_secret_is_incorrect"
	// APIErrorCodeForbidden is returned when the API request is forbidden because of a permission issue
	APIErrorCodeForbidden APIErrorCode = "forbidden"
	// APIErrorCodeNeitherUserHMACNorAPISecretProvided is returned when neither the User email HMAC
	// nor the API secret are not provided. See https://developer.magicbell.io/reference#performing-api-requests-from-javascript
	APIErrorCodeNeitherUserHMACNorAPISecretProvided APIErrorCode = "neither_user_hmac_nor_api_secret_provided"
	// APIErrorCodeUserEmailNotProvided is returned when a user's email should have been provided with the HMAC
	// but was not set.
	APIErrorCodeUserEmailNotProvided APIErrorCode = "user_email_not_provided"
)

type APIErrors

type APIErrors []APIError

APIErrors is an alias to a slice of APIError. This is useful for parsing API responses.

func (APIErrors) Error

func (e APIErrors) Error() string

Error returns a string of the first APIError

type BaseNotification

type BaseNotification struct {
	// ID is the MagicBell ID for the notification
	ID string `json:"id"`
}

BaseNotification is the simplest data that can be returned for a MagicBell notification. The Notification struct is generally used, but when creating a new notification only the ID is returned.

func CreateNotification

func CreateNotification(req CreateNotificationRequest) (*BaseNotification, error)

CreateNotification sends a notification to one or multiple users.

func CreateNotificationC

func CreateNotificationC(ctx context.Context, req CreateNotificationRequest) (*BaseNotification, error)

CreateNotificationC sends a notification to one or multiple users, using a context.Context in the HTTP request.

type Config

type Config struct {
	// APIKey is the api key for your MagicBell account
	APIKey string
	// APISecret is the api secret for your MagicBell account
	APISecret string
	// BaseURL is the MagicBell API url, this is optional
	// and will default to https://api.magicbell.io
	BaseURL string `yaml:",omitempty"`
	// Timeout is an optional time.Duration to wait for HTTP requests to timeout.
	// If not provided, it will default to 5 seconds.
	Timeout *time.Duration `yaml:",omitempty"` // optional
}

Config represents the required values to make HTTP requests to the MagicBell API.

type CreateNotificationRequest

type CreateNotificationRequest struct {
	// Title is the title of the notification
	Title string `json:"title"`
	// Recipients are the users to send the notification to
	Recipients []NotificationRecipient `json:"recipients"`
	// Content is the content of the notification to send
	Content string `json:"content,omitempty"`
	// CustomAttributes are a set of key-value pairs that you can attach to a notification
	CustomAttributes CustomAttributes `json:"custom_attributes,omitempty"`
	// ActionURL is a URL to redirect the user to when they click on the notification in MagicBell's embeddable notification center.
	ActionURL string `json:"action_url,omitempty"`
	// Category is the category this notification belongs to.
	Category string `json:"category,omitempty"`
}

CreateNotificationRequest is the data required to create a new notification for a set of recipients in MagicBell. The only required fields are Title and Recipients.

type CreateUserRequest

type CreateUserRequest struct {
	// ExternalID is a unique string that MagicBell can utilize to uniquely identify the user.
	// We recommend setting this attribute to the ID of the user in your database.
	// Provide the external id if the user's email is unavailable.
	ExternalID string `json:"external_id"`
	// Email is the user's email.
	Email string `json:"email"`
	// FirstName is the user's first name.
	FirstName string `json:"first_name,omitempty"`
	// LastName is the user's last name.
	LastName string `json:"last_name,omitempty"`
	// CustomAttributes are any customers attributes that you'd like to associate with the user.
	// These custom attributes can later be utilized in MagicBell's web interface (when writing email templates for example).
	CustomAttributes CustomAttributes `json:"custom_attributes,omitempty"`
}

CreateUserRequest is the set of data required to create a new user in MagicBell. Please note that you must provide the user's email or the external id so MagicBell can uniquely identify the user. The external id, if provided, must be unique to the user.

type CustomAttributes

type CustomAttributes map[string]interface{}

CustomAttributes are any custom fields to map onto certain MagicBell resources. Generally should contain other map[string]interface{} or map[string]string

type IAPI

type IAPI interface {
	// GenerateUserEmailHMAC generates a sha256 HMAC signature of the user's email
	// using the APISecret as the HMAC key. The returned value is a base64 encoded
	// string of the resulting HMAC signature. See https://developer.magicbell.io/reference#performing-api-requests-from-javascript
	GenerateUserEmailHMAC(userEmail string) string
	// CreateNotification sends a notification to one or multiple users.
	CreateNotification(req CreateNotificationRequest) (*BaseNotification, error)
	// CreateNotificationC sends a notification to one or multiple users, using a context.Context in the HTTP request.
	CreateNotificationC(ctx context.Context, req CreateNotificationRequest) (*BaseNotification, error)
	//FetchUserNotifications()
	//FetchUserNotificationsC(ctx context.Context)
	//FetchUserNotification()
	//FetchUserNotificationC(ctx context.Context)
	//DeleteUserNotification()
	//DeleteUserNotificationC(ctx context.Context)
	//MarkNotificationRead()
	//MarkNotificationReadC(ctx context.Context)
	//MarkNotificationUnread()
	//MarkNotificationUnreadC(ctx context.Context)
	//MarkAllNotificationsRead()
	//MarkAllNotificationsReadC(ctx context.Context)
	//MarkAllNotificationsSeen()
	//MarkAllNotificationsSeenC(ctx context.Context)
	// CreateUser creates a new user in MagicBell.
	// Please note that you must provide the user's email or the external id so MagicBell can uniquely identify the user.
	// The external id, if provided, must be unique to the user.
	CreateUser(req CreateUserRequest) (*User, error)
	// CreateUserC creates a new user in MagicBell, using a context.Context in the HTTP request.
	// Please note that you must provide the user's email or the external id so MagicBell can uniquely identify the user.
	// The external id, if provided, must be unique to the user.
	CreateUserC(ctx context.Context, req CreateUserRequest) (*User, error)
	// UpdateUser updates a user in MagicBell with the given ID.
	// The user id is the MagicBell user id. Alternatively, provide an id like
	// email:theusersemail@example.com or external_id:theusersexternalid as the user id.
	UpdateUser(userID string, req UpdateUserRequest) (*User, error)
	// UpdateUserC updates a user in MagicBell with the given ID, using a context.Context in the HTTP request.
	// The user id is the MagicBell user id. Alternatively, provide an id like
	// email:theusersemail@example.com or external_id:theusersexternalid as the user id.
	UpdateUserC(ctx context.Context, userID string, req UpdateUserRequest) (*User, error)
}

IAPI contains all the methods for working with the MagicBell API

func New

func New(config Config) IAPI

New instantiates a new API which implements the IAPI interface. Config.APIKey and Config.APISecret must be set in order for API requests to succeed.

type InternalServerError

type InternalServerError struct {
	// StatusCode is the HTTP status code returned from the request
	StatusCode int
	// Body is the response body, if any
	Body string
}

InternalServerError represents a 5xx HTTP error returned from the API

func (InternalServerError) Error

func (e InternalServerError) Error() string

Error returns a simple string describing the HTTP error

type Notification

type Notification struct {
	BaseNotification
}

Notification represents a full notification when retrieved from MagicBell.

type NotificationRecipient

type NotificationRecipient struct {
	// Email is the email of the recipient to send the notification to.
	Email string `json:"email,omitempty"`
	// ExternalID is the unique string to identify the user in your database.
	ExternalID string `json:"external_id,omitempty"`
	Matches    string `json:"matches,omitempty"`
}

NotificationRecipient is a possible recipient of a notification. Generally Email should be specified, but ExternalID can also be provided if the email is not available.

type UpdateUserRequest

type UpdateUserRequest struct {
	// ExternalID is a unique string that MagicBell can utilize to uniquely identify the user.
	// We recommend setting this attribute to the ID of the user in your database.
	// Provide the external id if the user's email is unavailable.
	ExternalID string `json:"external_id"`
	// Email is the user's email.
	Email string `json:"email"`
	// FirstName is the user's first name.
	FirstName string `json:"first_name,omitempty"`
	// LastName is the user's last name.
	LastName string `json:"last_name,omitempty"`
	// CustomAttributes are any customers attributes that you'd like to associate with the user.
	// These custom attributes can later be utilized in MagicBell's web interface (when writing email templates for example).
	CustomAttributes CustomAttributes `json:"custom_attributes,omitempty"`
}

UpdateUserRequest is the set of data required to update an existing user in MagicBell. Note that this is a PUT request, so all data given will overwrite all existing data in MagicBell.

type User

type User struct {
	// ID is the unique ID MagicBell internally uses to represent your user.
	ID string `json:"id"`
	// ExternalID is a unique string that MagicBell can utilize to uniquely identify the user.
	ExternalID string `json:"external_id"`
	// Email is the user's email.
	Email string `json:"email"`
	// FirstName is the user's first name.
	FirstName string `json:"first_name"`
	// LastName is the user's last name.
	LastName string `json:"last_name"`
	// CustomAttributes are any customers attributes that you'd like to associate with the user.
	CustomAttributes CustomAttributes `json:"custom_attributes"`
}

User is MagicBell's representation of a user, uniquely identified by ID.

func CreateUser

func CreateUser(req CreateUserRequest) (*User, error)

CreateUser is a global shortcut to API.CreateUser

func CreateUserC

func CreateUserC(ctx context.Context, req CreateUserRequest) (*User, error)

CreateUserC is a global shortcut to API.CreateUserC

func UpdateUser

func UpdateUser(userID string, req UpdateUserRequest) (*User, error)

UpdateUser is a global shortcut to API.UpdateUser

func UpdateUserC

func UpdateUserC(ctx context.Context, userID string, req UpdateUserRequest) (*User, error)

UpdateUserC is a global shortcut to API.UpdateUserC

Directories

Path Synopsis
cmd

Jump to

Keyboard shortcuts

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