notify

package module
v0.0.0-...-c57ad55 Latest Latest
Warning

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

Go to latest
Published: Sep 20, 2019 License: MIT Imports: 10 Imported by: 0

README

GOV.UK Notify Go client

Note to anyone cloning this repo

Please be aware that is currently an unsupported client for GOV.UK Notify. If you do want to use this client please contact the Notify team using slack or by submitting feedback. We need to make sure this repo upholds our standards and is updated with new features, has integration tests and is included in our development pipeline.

Installing

The Notify Go Client can be installed with go get.

go get github.com/alphagov/notifications-go-client

Getting started

Create an instance of the Client using:

package main

import "github.com/alphagov/notifications-go-client"

func main() {
	// Configure the client.
	config := notify.Configuration{
		APIKey: "{your api key}",
		ServiceID: "{your service id}",
	}

	// Initialise the client.
	client, err := notify.New(config)
	if err != nil {
		panic(err)
	}
}

Generate an API key by logging in to GOV.UK Notify and going to the API integration page.

Send messages

Text message

The method signature is:

SendSms(phoneNumber, templateID string, personalisation templateData, reference string) (*NotificationEntry, error)

An example request would look like:

data := map[string]string{
	"name": "Betty Smith",
	"dob": "12 July 1968",
}

response, err := client.SendSms("+447777111222", "df10a23e-2c6d-4ea5-87fb-82e520cbf93a", data, "")
Response

If the request is successful, response will be a *notify.NotificationEntry:

type NotificationEntry struct {
	Content   map[string]string
	ID        string
	Reference string
	Template  type Template struct {
		Version int64
		ID      int64
		URI     string
	}
	URI       string
}

Otherwise the notify.APIError will be returned:

`error["status_code"]` `error["message"]`
429
[{
	"error": "RateLimitError",
	"message": "Exceeded rate limit for key type TEAM of 10 requests per 10 seconds"
}]
429
[{
	"error": "TooManyRequestsError",
	"message": "Exceeded send limits (50) for today"
}]
400
[{
	"error": "BadRequestError",
	"message": "Can"t send to this recipient using a team-only API key"
]}
400
[{
	"error": "BadRequestError",
	"message": "Can"t send to this recipient when service is in trial mode
	              - see https://www.notifications.service.gov.uk/trial-mode"
}]
Email

The method signature is:

SendEmail(emailAddress, templateID string, personalisation templateData, reference string) (*NotificationEntry, error)

An example request would look like:

data := map[string]string{
	"name": "Betty Smith",
	"dob": "12 July 1968",
}

response, err := SendEmail("betty@exmple.com", "df10a23e-2c0d-4ea5-87fb-82e520cbf93c", data, "")
Response

If the request is successful, response will be an *notify.NotificationEntry:

type NotificationEntry struct {
	Content   map[string]string
	ID        string
	Reference string
	Template  type Template struct {
		Version int64
		ID      int64
		URI     string
	}
	URI       string
}

Otherwise the client will raise a Alphagov\Notifications\Exception\NotifyException:

`error["status_code"]` `error["message"]`
429
[{
	"error": "RateLimitError",
	"message": "Exceeded rate limit for key type TEAM of 10 requests per 10 seconds"
}]
429
[{
	"error": "TooManyRequestsError",
	"message": "Exceeded send limits (50) for today"
}]
400
[{
	"error": "BadRequestError",
	"message": "Can"t send to this recipient using a team-only API key"
]}
400
[{
	"error": "BadRequestError",
	"message": "Can"t send to this recipient when service is in trial mode
	              - see https://www.notifications.service.gov.uk/trial-mode"
}]
Arguments
templateId

Find by clicking API info for the template you want to send.

personalisation

If a template has placeholders you need to provide their values. For example:

personalisation := map[string]string{
	"name": "Betty Smith",
	"dob": "12 July 1968",
}
reference

An optional identifier you generate if you don’t want to use Notify’s id. It can be used to identify a single notification or a batch of notifications.

Get the status of one message

The method signature is:

GetNotification(id string) (*Notification, error)

An example request would look like:

notification, err := client.GetNotification("c32e9c89-a423-42d2-85b7-a21cd4486a2a")
Response

If the request is successful, notification will be an *notify.Notification:

type Notification struct {
	ID        string
	Body      string
	Subject   string
	Reference string
	Email     string
	Phone     string
	Line1     string
	Line2     string
	Line3     string
	Line4     string
	Line5     string
	Line6     string
	Postcode  string
	Type      string
	Status    string
	Template  type Template struct {
		ID      int64
		URI     string
		Version int64
	}
	CreatedAt time.Time
	SentAt    time.Time
}

Otherwise the client will raise a notify.APIError:

`error["status_code"]` `error["message"]`
404
[{
	"error": "NoResultFound",
	"message": "No result found"
}]
400
[{
	"error": "ValidationError",
	"message": "id is not a valid UUID"
}]

Get the status of all messages

The method signature is:

ListNotifications(filters notify.Filters) (*NotificationList, error)

An example request would look like:

filters := notify.Filters{
	OlderThan: "c32e9c89-a423-42d2-85b7-a21cd4486a2a",
	Reference: "weekly-reminders",
	Status: "delivered",
	TemplateType: "sms",
}

list, err := client.ListNotifications(filters)
Response

If the request is successful, list will be an *notify.NotificationList:

type NotificationList struct {
	Client *Client

	Notifications []Notification
	Links         Pagination
}

Otherwise the client will raise a notify.APIError:

`error["status_code"]` `error["message"]`
400
[{
	'error': 'ValidationError',
	'message': 'bad status is not one of [created, sending, delivered, pending, failed, technical-failure, temporary-failure, permanent-failure]'
}]
400
[{
	"error": "ValidationError",
	"message": "Apple is not one of [sms, email, letter]"
}]
Notification list pagination

The method signatures are:

Next() error
Previous() error

An example request would look like:

var err error
a := list.Notifications[0].ID // Recorded for demonstration only.

err = list.Next()
if err != nil {
	fmt.Printf("Could be that there are no more pages that way. %#v", err)
}

fmt.Println(list.Notifications[0].ID == a) // false

err = list.Previous()
if err != nil {
	fmt.Printf("Could be that there are no more pages that way. %#v", err)
}

fmt.Println(list.Notifications[0].ID == a) // true
Arguments
older_than

If omitted all messages are returned. Otherwise you can filter to retrieve all notifications older than the given notification id.

template_type

If omitted all messages are returned. Otherwise you can filter by:

  • email
  • sms
  • letter
status

If omitted all messages are returned. Otherwise you can filter by:

  • sending - the message is queued to be sent by the provider.
  • delivered - the message was successfully delivered.
  • failed - this will return all failure statuses permanent-failure, temporary-failure and technical-failure.
  • permanent-failure - the provider was unable to deliver message, email or phone number does not exist; remove this recipient from your list.
  • temporary-failure - the provider was unable to deliver message, email box was full or the phone was turned off; you can try to send the message again.
  • technical-failure - Notify had a technical failure; you can try to send the message again.
reference

This is the reference you gave at the time of sending the notification. This can be omitted to ignore the filter.

Development

Tests

There are unit and integration tests that can be run to test functionality of the client.

To run the tests:

ginkgo

Or in the traditional way:

go test

License

The Notify Go Client is released under the MIT license, a copy of which can be found in LICENSE.

Documentation

Index

Constants

View Source
const BaseURLProduction = "https://api.notifications.service.gov.uk"

BaseURLProduction is the The API endpoint for Notify production.

View Source
const PathNotificationList = "/v2/notifications"

PathNotificationList directs to the appropriate endpoint responsible for retrieving the list of notifications.

View Source
const PathNotificationLookup = "/v2/notifications/%s"

PathNotificationLookup directs to the appropriate endpoint responsible for lookup of any notifications.

View Source
const PathNotificationSendEmail = "/v2/notifications/email"

PathNotificationSendEmail directs to the appropriate endpoint responsible for sending an email message.

View Source
const PathNotificationSendLetter = "/v2/notifications/letter"

PathNotificationSendLetter directs to the appropriate endpoint responsible for sending a letter.

View Source
const PathNotificationSendSms = "/v2/notifications/sms"

PathNotificationSendSms directs to the appropriate endpoint responsible for sending a text message.

View Source
const Version = "1.0.0"

Version of this client. This follows Semantic Versioning (http://semver.org/)

Variables

This section is empty.

Functions

This section is empty.

Types

type APIError

type APIError struct {
	Message    string
	StatusCode int
	Errors     []Error
}

APIError is a custom error-type struct adjusted for the API usage.

func (*APIError) Error

func (e *APIError) Error() string

Error method is here to return a top level error message as well as define our new error type.

type Client

type Client struct {
	Configuration Configuration
}

Client for accessing GOV.UK Notify.

Before using this client you must have:

  • created an account with GOV.UK Notify
  • found your Service ID and generated an API Key.
  • created at least one template and know its ID.

func New

func New(configuration Configuration) (*Client, error)

New instance of a client will be generated for the use

func (*Client) GetNotification

func (c *Client) GetNotification(id string) (*Notification, error)

GetNotification will fire a request that returns details about the passed notification ID.

func (*Client) ListNotifications

func (c *Client) ListNotifications(filters Filters) (*NotificationList, error)

ListNotifications will fire a request that returns a list of all notifications for the current Service ID.

func (*Client) SendEmail

func (c *Client) SendEmail(emailAddress, templateID string, personalisation templateData, reference string) (*NotificationEntry, error)

SendEmail will fire a request to Send an Email message.

func (*Client) SendLetter

func (c *Client) SendLetter(letter, templateID string, personalisation templateData, reference string) (*NotificationEntry, error)

SendLetter will fire a request to Send a Letter. TODO Establish what this actually is and prepare for usage.

func (*Client) SendSms

func (c *Client) SendSms(phoneNumber, templateID string, personalisation templateData, reference string) (*NotificationEntry, error)

SendSms will fire a request to Send a SMS message.

type Configuration

type Configuration struct {
	APIKey     []byte
	BaseURL    *url.URL
	Claims     *jwt.StandardClaims
	HTTPClient *http.Client
	ServiceID  string
}

Configuration of the Notifications Go Client.

func (*Configuration) Authenticate

func (c *Configuration) Authenticate(secret []byte) (*string, error)

Authenticate a JWT token. JwtTokenCreator uses HMAC-SHA256 signature, by default.

type Error

type Error struct {
	Error   string
	Message string
}

Error may be returned by the API.

type Filters

type Filters struct {
	OlderThan    string `json:"older_than"`
	Reference    string `json:"reference"`
	Status       string `json:"status"`
	TemplateType string `json:"template_type"`
}

Filters for the notifications to be looked at.

func (*Filters) ToURLValues

func (f *Filters) ToURLValues() url.Values

ToURLValues will convert the struct into the url.Values.

type Notification

type Notification struct {
	ID        string    `json:"id"`
	Body      string    `json:"body"`
	Subject   string    `json:"subject"`
	Reference string    `json:"reference"`
	Email     string    `json:"email_address"`
	Phone     string    `json:"phone_number"`
	Line1     string    `json:"line_1"`
	Line2     string    `json:"line_2"`
	Line3     string    `json:"line_3"`
	Line4     string    `json:"line_4"`
	Line5     string    `json:"line_5"`
	Line6     string    `json:"line_6"`
	Postcode  string    `json:"postcode"`
	Type      string    `json:"type"`
	Status    string    `json:"status"`
	Template  Template  `json:"template"`
	CreatedAt time.Time `json:"created_at"`
	SentAt    time.Time `json:"sent_at"`
}

Notification is the object build and returned by GOV.UK Notify.

type NotificationEntry

type NotificationEntry struct {
	Content   map[string]string `json:"content"`
	ID        string            `json:"id"`
	Reference string            `json:"reference"`
	Template  Template          `json:"template"`
	URI       string            `json:"uri"`
}

NotificationEntry is the struct aroung the successful response from the API collected upon the creation of a new Notification.

type NotificationList

type NotificationList struct {
	Client *Client `json:"-"`

	Notifications []Notification `json:"notifications"`
	Links         Pagination     `json:"links"`
}

NotificationList is one the responses from GOV.UK Notify.

func (*NotificationList) Next

func (nl *NotificationList) Next() error

Next page of the list should be loaded in place of the old one.

func (*NotificationList) Previous

func (nl *NotificationList) Previous() error

Previous page of the list should be loaded in place of the old one.

type Pagination

type Pagination struct {
	Current  string `json:"current"`
	Next     string `json:"next"`
	Previous string `json:"previous"`
}

Pagination of the list that's returned as part of the JSON response.

type Payload

type Payload struct {
	EmailAddress    string            `json:"email_address"`
	Letter          string            `json:"letter"` // TODO Establish what this actually is and prepare for usage.
	Personalisation map[string]string `json:"personalisation"`
	PhoneNumber     string            `json:"phone_number"`
	Reference       string            `json:"reference"`
	TemplateID      string            `json:"template_id"`
}

Payload that will be send with different set of requests by the client.

func NewPayload

func NewPayload(service, recipient, templateID string, personalisation templateData, reference string) *Payload

NewPayload is a function that takes different parameters and initialises the Payload struct, to be used in the calls.

type Template

type Template struct {
	ID      int64  `json:"id"`
	URI     string `json:"uri"`
	Version int64  `json:"version"`
}

Template may be returned as part of Notification response.

Jump to

Keyboard shortcuts

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