Table of contents

PHP client documentation

This documentation is for developers interested in using the GOV.UK Notify PHP client to send emails, text messages or letters.

Set up the client

The Notify PHP Client is based on a PSR-7 HTTP model [external link]. To install it, you must select your preferred HTTP client. You can follow these instructions to use Guzzle v6 and v5 and cURL [external links].

Guzzle v6

  1. Use Composer [external link] to install the GOV.UK Notify PHP client. Run the following in the command line:

    composer require php-http/guzzle6-adapter alphagov/notifications-php-client
    

    You can now use the autoloader [external link] to download the GOV.UK Notify PHP client.

  2. Add the following code to your application to create a new instance of the client:

    $notifyClient = new \Alphagov\Notifications\Client([
        'apiKey' => '{your api key}',
        'httpClient' => new \Http\Adapter\Guzzle6\Client
    ]);
    

To get an API key, sign in to GOV.UK Notify and go to the API integration page. Refer to the API keys section of this documentation for more information.

Guzzle v5

  1. Use Composer [external link] to install the GOV.UK Notify PHP client. Run the following in the command line:

    composer require php-http/guzzle5-adapter php-http/message alphagov/notifications-php-client
    

    You can now use the autoloader [external link] to download the GOV.UK Notify PHP client.

  2. Add the following code to your application to create a new instance of the client:

    $notifyClient = new \Alphagov\Notifications\Client([
        'apiKey'        => '{your api key}',
        'httpClient'    => new \Http\Adapter\Guzzle5\Client(
            new \GuzzleHttp\Client,
            new \Http\Message\MessageFactory\GuzzleMessageFactory
        ),
    ]);
    
  3. Run $notifyClient to access the GOV.UK Notify API.

To get an API key, sign in to GOV.UK Notify and go to the API integration page. Refer to the API keys section of this documentation for more information.

cURL

  1. Use Composer [external link] to install the GOV.UK Notify PHP client. Run the following in the command line:

    composer require php-http/curl-client php-http/message alphagov/notifications-php-client
    

You can now use the autoloader [external link] to download the GOV.UK Notify PHP client.

  1. Add the following code to your application to create a new instance of the client:

    $notifyClient = new \Alphagov\Notifications\Client([
        'apiKey'        => '{your api key}',
        'httpClient'    => new \Http\Client\Curl\Client(
            new \Http\Message\MessageFactory\GuzzleMessageFactory,
            new \Http\Message\StreamFactory\GuzzleStreamFactory
        ),
    ]);
    
  2. Run $notifyClient to access the GOV.UK Notify API.

To get an API key, sign in to GOV.UK Notify and go to the API integration page. Refer to the API keys section of this documentation for more information.

Send a message

You can use GOV.UK Notify to send text messages, emails and letters.

Send a text message

Method

sendSms( $phoneNumber, $templateId, array $personalisation = array(), $reference = '', $smsSenderId = NULL  )

For example:

try {
    $response = $notifyClient->sendSms(
        '+447777111222',
        'df10a23e-2c6d-4ea5-87fb-82e520cbf93a', [
            'name' => 'Betty Smith',
            'dob'  => '12 July 1968'
        ],
        'unique_ref123',
        '862bfaaf-9f89-43dd-aafa-2868ce2926a9'
    );

} catch (NotifyException $e){}

Arguments

phoneNumber (required)

The phone number of the recipient of the text message. This can be a UK or international number.

templateId (required)

Sign in to GOV.UK Notify and go to the Templates page to find the template ID.

personalisation (optional)

If a template has placeholder fields for personalised information such as name or application date, you must provide their values in a dictionary with key value pairs. For example:

$personalisation = [
    'name' => 'Amala',
    'application_date'  => '2018-01-01'
];

You can leave out this argument if a template does not have any placeholder fields for personalised information.

reference (optional)

A unique identifier you can create if necessary. This reference identifies a single unique notification or a batch of notifications. It must not contain any personal information such as name or postal address. For example:

$reference = 'STRING';

You can leave out this argument if you do not have a reference.

smsSenderId (optional)

A unique identifier of the sender of the text message notification. You can find this information on the Text Message sender settings screen:

  1. Sign in to your GOV.UK Notify account.
  2. Go to Settings.
  3. If you need to change to another service, select Switch service and then select the correct service.
  4. Go to the Text Messages section and select Manage on the Text Message sender row.

You can then either:

  • copy the sender ID that you want to use and paste it into the method
  • select Change to change the default sender that the service will use, and select Save
$smsSenderId='8e222534-7f05-4972-86e3-17c5d9f894e2'

You can leave out this argument if your service only has one text message sender, or if you want to use the default sender.

Response

If the request to the client is successful, the client returns an array:

[
    "id" => "bfb50d92-100d-4b8b-b559-14fa3b091cda",
    "reference" => None,
    "content" => [
        "body" => "Some words",
        "from_number" => "40604"
    ],
    "uri" => "https =>//api.notifications.service.gov.uk/v2/notifications/ceb50d92-100d-4b8b-b559-14fa3b091cd",
    "template" => [
        "id" => "ceb50d92-100d-4b8b-b559-14fa3b091cda",
       "version" => 1,
       "uri" => "https://api.notifications.service.gov.uk/v2/templates/bfb50d92-100d-4b8b-b559-14fa3b091cda"
    ]
];

If you are using the test API key, all your messages will come back with a delivered status.

All messages sent using the team and whitelist or live keys will appear on your dashboard.

Error codes

If the request is not successful, the client returns an Alphagov\Notifications\Exception\NotifyException object containing the relevant error code.

exc->getCode() exc->getErrors() How to fix
400 [{
"error": "BadRequestError",
"message": "Can't send to this recipient using a team-only API key"
]}
Use the correct type of 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"
}]
Your service cannot send this notification in trial mode.
403 [{
"error": "AuthError",
"message": "Error: Your system clock must be accurate to within 30 seconds"
}]
Check your system clock.
403 [{
"error": "AuthError",
"message": "Invalid token: signature, api token not found"
}]
Use the correct API key. Refer to API keys for more information.
429 [{
"error": "RateLimitError",
"message": "Exceeded rate limit for key type TEAM/TEST/LIVE of 3000 requests per 60 seconds"
}]
Refer to API rate limits for more information.
429 [{
"error": "TooManyRequestsError",
"message": "Exceeded send limits (LIMIT NUMBER) for today"
}]
Refer to service limits for the limit number.
500 [{
"error": "Exception",
"message": "Internal server error"
}]
Notify was unable to process the request, resend your notification.

Send an email

Method

sendEmail( $emailAddress, $templateId, array $personalisation = array(), $reference = '', $emailReplyToId = NULL )

For example:

try {

    $response = $notifyClient->sendEmail(
        'betty@example.com',
        'df10a23e-2c0d-4ea5-87fb-82e520cbf93c', [
            'name' => 'Betty Smith',
            'dob'  => '12 July 1968'
        ],
        'unique_ref123',
        '862bfaaf-9f89-43dd-aafa-2868ce2926a9'
        );

} catch (NotifyException $e){}

Arguments

emailAddress (required)

The email address of the recipient.

templateId (required)

Sign in to GOV.UK Notify and go to the Templates page to find the template ID.

personalisation (optional)

If a template has placeholder fields for personalised information such as name or reference number, you need to provide their values in a dictionary with key value pairs. For example:

$personalisation = [
    'name' => 'Amala',
    'application_date'  => '2018-01-01'
];

You can leave out this argument if a template does not have any placeholder fields for personalised information.

reference (optional)

A unique identifier you can create if necessary. This reference identifies a single unique notification or a batch of notifications. It must not contain any personal information such as name or postal address.

$reference = 'STRING';

You can leave out this argument if you do not have a reference.

emailReplyToId (optional)

This is an email reply-to address you can specify to receive replies from your users. Your service cannot go live until you set up at least one of these email addresses. To set up:

  1. Sign in to your GOV.UK Notify account.
  2. Go to Settings.
  3. If you need to change to another service, select Switch service and then select the correct service.
  4. Go to the Email section and select Manage on the Email reply-to addresses row.
  5. Select Change to specify the email address to receive replies, and select Save.

For example:

$emailReplyToId='8e222534-7f05-4972-86e3-17c5d9f894e2'

You can leave out this argument if your service only has one email reply-to address, or you want to use the default email address.

Send a document by email

Send files without the need for email attachments.

This is an invitation-only feature. Contact the GOV.UK Notify team to enable this function for your service.

To send a document by email, add a placeholder field to the template and then upload a file. The placeholder field will contain a secure link to download the document.

Add a placeholder field to the template

  1. Sign in to GOV.UK Notify.
  2. Go to the Templates page and select the relevant email template.
  3. Add a placeholder field to the email template using double brackets. For example:

“Download your document at: ((link_to_document))”

Upload your document

The document you upload must be a PDF file smaller than 2MB.

Pass the file object as a value into the personalisation argument. For example:

try {
    $file_data = file_get_contents('/path/to/my/file.pdf');

    $response = $notifyClient->sendEmail(
        'betty@example.com',
        'df10a23e-2c0d-4ea5-87fb-82e520cbf93c',
        [
            'name' => 'Betty Smith',
            'dob'  => '12 July 1968',
            'link_to_document' => $notifyClient->prepareUpload( $file_data )
        ]
    );

} catch (NotifyException $e){}

Response

If the request to the client is successful, the client returns an array:

[
    "id" => "bfb50d92-100d-4b8b-b559-14fa3b091cda",
    "reference" => None,
    "content" => [
        "subject" => "SUBJECT TEXT",
        "body" => "MESSAGE TEXT",
        "from_email" => "SENDER EMAIL
    ],
    "uri" => "https://api.notifications.service.gov.uk/v2/notifications/ceb50d92-100d-4b8b-b559-14fa3b091cd",
    "template" => [
        "id" => "ceb50d92-100d-4b8b-b559-14fa3b091cda",
        "version" => 1,
        "uri" => "https://api.notificaitons.service.gov.uk/service/your_service_id/templates/bfb50d92-100d-4b8b-b559-14fa3b091cda"
    ]
];

Error codes

If the request is not successful, the client returns an Alphagov\Notifications\Exception\NotifyException object containing the relevant error code.

exc->getCode() exc->getErrors() How to fix
400 [{
"error": "BadRequestError",
"message": "Can't send to this recipient using a team-only API key"
]}
Use the correct type of 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"
}]
Your service cannot send this notification in trial mode.
400 [{
"error": "BadRequestError",
"message": "Unsupported document type '{}'. Supported types are: {}"
}]
The document you upload must be a PDF file.
400 [{
"error": "BadRequestError",
"message": "Document didn't pass the virus scan"
}]
The document you upload must be virus free.
400 [{
"error": "BadRequestError",
"message": "Service is not allowed to send documents"
}]
Contact the GOV.UK Notify team.
403 [{
"error": "AuthError",
"message": "Error: Your system clock must be accurate to within 30 seconds"
}]
Check your system clock.
403 [{
"error": "AuthError",
"message": "Invalid token: signature, api token not found"
}]
Use the correct type of API key.
429 [{
"error": "RateLimitError",
"message": "Exceeded rate limit for key type TEAM/TEST/LIVE of 3000 requests per 60 seconds"
}]
Refer to API rate limits for more information.
429 [{
"error": "TooManyRequestsError",
"message": "Exceeded send limits (LIMIT NUMBER) for today"
}]
Refer to service limits for the limit number.
500 [{
"error": "Exception",
"message": "Internal server error"
}]
Notify was unable to process the request, resend your notification.

Send a letter

Prerequisites

When your service first signs up to GOV.UK Notify, you’ll start in trial mode. You can only send letters in live mode. You must ask GOV.UK Notify to make your service live.

  1. Sign in to GOV.UK Notify.
  2. Select Using Notify.
  3. Select requesting to go live.

Method

sendLetter( $templateId, array $personalisation = array(), $reference = '' )

For example:

try {

    $response = $notifyClient->sendEmail(
        'df10a23e-2c0d-4ea5-87fb-82e520cbf93c',
        [
            'name'=>'Fred',
            'address_line_1' => 'Foo',
            'address_line_2' => 'Bar',
            'postcode' => 'Baz'
        ],
        'unique_ref123'
    );

} catch (NotifyException $e){}

Arguments

templateId (required)

Sign in to GOV.UK Notify and go to the Templates page to find the template ID.

personalisation (required)

The personalisation argument always contains the following required parameters for the letter recipient’s address:

  • address_line_1
  • address_line_2
  • postcode

Any other placeholder fields included in the letter template also count as required parameters. You need to provide their values in a dictionary with key value pairs. For example:

$personalisation =
          [
            'address_line_1' => '123 High Street',
            'address_line_2' => 'Richmond',
            'postcode' => 'W4 1FH',
            'name' => 'John Smith',
            'application_id' => '4134325'
          ];

reference (optional)

A unique identifier you can create if necessary. This reference identifies a single unique notification or a batch of notifications. It must not contain any personal information such as name or postal address. For example:

$reference = 'STRING';

personalisation (optional)

The following parameters in the letter recipient’s address are optional:

$personalisation =
    [
    'address_line_3' => '123 High Street',  
    'address_line_4' => 'Richmond upon Thames',     
    'address_line_5' => 'London',       
    'address_line_6' => 'Middlesex',
    ];

Response

If the request to the client is successful, the client returns an array:

[
    "id" => "bfb50d92-100d-4b8b-b559-14fa3b091cda",
    "reference" => "unique_ref123",
    "content" => [
        "subject" => "Licence renewal",
        "body" => "Dear Bill, your licence is due for renewal on 3 January 2016.",
    ],
    "uri" => "https://api.notifications.service.gov.uk/v2/notifications/ceb50d92-100d-4b8b-b559-14fa3b091cd",
    "template" => [
        "id" => "ceb50d92-100d-4b8b-b559-14fa3b091cda",
        "version" => 1,
        "uri" => "https://api.notifications.service.gov.uk/service/your_service_id/templates/bfb50d92-100d-4b8b-b559-14fa3b091cda"
    ],
    "scheduled_for" => null
];

Error codes

If the request is not successful, the client returns an Alphagov\Notifications\Exception\NotifyException object containing the relevant error code.

exc->getCode() exc->getErrors() How to fix
400 [{
"error": "BadRequestError",
"message": "Cannot send letters with a team api key"
]}
Use the correct type of API key
400 [{
"error": "BadRequestError",
"message": "Cannot send letters when service is in trial mode - see https://www.notifications.service.gov.uk/trial-mode"
}]
Your service cannot send this notification in trial mode
400 [{
"error": "ValidationError",
"message": "personalisation address_line_1 is a required property"
}]
Ensure that your template has a field for the first line of the address, check personalisation for more information.
403 [{
"error": "AuthError",
"message": "Error: Your system clock must be accurate to within 30 seconds"
}]
Check your system clock
403 [{
"error": "AuthError",
"message": "Invalid token: signature, api token not found"
}]
Use the correct API key. Refer to API keys for more information
429 [{
"error": "RateLimitError",
"message": "Exceeded rate limit for key type TEAM/TEST/LIVE of 3000 requests per 60 seconds"
}]
Refer to API rate limits for more information
429 [{
"error": "TooManyRequestsError",
"message": "Exceeded send limits (LIMIT NUMBER) for today"
}]
Refer to service limits for the limit number
500 [{
"error": "Exception",
"message": "Internal server error"
}]
Notify was unable to process the request, resend your notification.

Send a precompiled letter

This is an invitation-only feature. Contact the GOV.UK Notify team on the support page or through the Slack channel for more information.

Method

$response = $notifyClient->sendPrecompiledLetter(
    $reference,
    $pdf_data,
    $postage,
);

Arguments

reference (required)

A unique identifier you create if necessary. This reference identifies a single unique notification or a batch of notifications. It must not contain any personal information such as name or postal address.

$reference = 'STRING';

pdf_data (required)

The precompiled letter must be a PDF file which meets the GOV.UK Notify PDF letter specification. The method sends the contents of the file to GOV.UK Notify.

$pdf_data = file_get_contents("path/to/pdf_file");
try {

    $response = $notifyClient->sendPrecompiledLetter(
        'unique_ref123',
        $pdf_data,
        'first',
    );

} catch (NotifyException $e){}

postage (optional)

You can choose first or second class postage for your precompiled letter. Set the value to first for first class, or second for second class. If you do not pass in this argument, the postage will default to second class.

$postage = 'first';

Response

If the request to the client is successful, the client returns an array:

[
  "id" => "740e5834-3a29-46b4-9a6f-16142fde533a",
  "reference" => "unique_ref123",
  "postage" => "first"
];

Error codes

If the request is not successful, the client returns an Alphagov\Notifications\Exception\NotifyException object containing the relevant error code.

exc->getCode() exc->getErrors() How to fix
400 [{
"error": "BadRequestError",
"message": "Cannot send letters with a team api key"
]}
Use the correct type of API key.
400 [{
"error": "BadRequestError",
"message": "Cannot send precompiled letters"
]}
This is an invitation-only feature. Contact the GOV.UK Notify team on the support page or through the Slack channel for more information.
400 [{
"error": "BadRequestError",
"message": "Letter content is not a valid PDF"
]}
PDF file format is required.
400 [{
"error": "BadRequestError",
"message": "Cannot send letters when service is in trial mode - see https://www.notifications.service.gov.uk/trial-mode"
}]
Your service cannot send this notification in trial mode.
400 [{
"error": "BadRequestError",
"message": "Service is not allowed to send precompiled letters"
}]
Contact the GOV.UK Notify team.
400 [{
"error": "ValidationError",
"message": "reference is a required property"
}]
Add a reference argument to the method call.
400 [{
"error": "ValidationError",
"message": "postage invalid. It must be either first or second."
}]
Change the value of postage argument in the method call to either ‘first’ or 'second’
429 [{
"error": "RateLimitError",
"message": "Exceeded rate limit for key type live of 10 requests per 20 seconds"
}]
Use the correct API key. Refer to API keys for more information.
429 [{
"error": "TooManyRequestsError",
"message": "Exceeded send limits (LIMIT NUMBER) for today"
}]
Refer to service limits for the limit number.

Get message status

Message status depends on the type of message that you have sent.

You can only get the status of messages that are 7 days old or newer.

Status - text and email

Status Information
Created GOV.UK Notify has placed the message in a queue, ready to be sent to the provider. It should only remain in this state for a few seconds.
Sending GOV.UK Notify has sent the message to the provider. The provider will try to deliver the message to the recipient. GOV.UK Notify is waiting for delivery information.
Delivered The message was successfully delivered.
Failed This covers all failure statuses:
- permanent-failure - “The provider could not deliver the message because the email address or phone number was wrong. You should remove these email addresses or phone numbers from your database. You’ll still be charged for text messages to numbers that do not exist.”
- temporary-failure - “The provider could not deliver the message after trying for 72 hours. This can happen when the recipient’s inbox is full or their phone is off. You can try to send the message again. You’ll still be charged for text messages to phones that are not accepting messages.”
- technical-failure - “Your message was not sent because there was a problem between Notify and the provider.
You’ll have to try sending your messages again. You will not be charged for text messages that are affected by a technical failure.”

Status - text only

Status Information
Pending GOV.UK Notify is waiting for more delivery information.
GOV.UK Notify received a callback from the provider but the recipient’s device has not yet responded. Another callback from the provider determines the final status of the notification.
Sent / Sent internationally The message was sent to an international number. The mobile networks in some countries do not provide any more delivery information. The GOV.UK Notify client API returns this status as sent. The GOV.UK Notify client app returns this status as Sent internationally.

Status - letter

Status information
Failed The only failure status that applies to letters is technical-failure. GOV.UK Notify had an unexpected error while sending to our printing provider.
Accepted GOV.UK Notify has sent the letter to the provider to be printed.
Received The provider has printed and dispatched the letter.

Status - precompiled letter

Status information
Pending virus check GOV.UK Notify has not completed a virus scan of the precompiled letter file.
Virus scan failed GOV.UK Notify found a potential virus in the precompiled letter file.
Validation failed Content in the precompiled letter file is outside the printable area. See the GOV.UK Notify PDF letter specification for more information.

Get the status of one message

You can only get the status of messages that are 7 days old or newer.

Method

getNotification( $notificationId )

For example:

try {

    $response = $notifyClient->getNotification( 'c32e9c89-a423-42d2-85b7-a21cd4486a2a' );

} catch (NotifyException $e){}

Arguments

notification_id (required)

The ID of the notification. You can find the notification ID in the response to the original notification method call.

You can also find it in your GOV.UK Notify Dashboard.

  1. Sign in to GOV.UK Notify and select Dashboard.
  2. Select either emails sent, text messages sent, or letters sent.
  3. Select the relevant notification.
  4. Copy the notification ID from the end of the page URL, for example https://www.notifications.service.gov.uk/services/af90d4cb-ae88-4a7c-a197-5c30c7db423b/notification/ID.

Response

If the request to the client is successful, the client returns an array:

[
    "id" => "notify_id",
    "body" => "Hello Foo",
    "subject" => "null|email_subject",
    "reference" => "client reference",
    "email_address" => "email address",
    "phone_number" => "phone number",
    "line_1" => "full name of a person or company",
    "line_2" => "123 The Street",
    "line_3" => "Some Area",
    "line_4" => "Some Town",
    "line_5" => "Some county",
    "line_6" => "Something else",
    "postcode" => "postcode",
    "postage" => "null|first|second",
    "type" => "sms|letter|email",
    "status" => "current status",
    "template" => [
        "version" => 1,
        "id" => 1,
        "uri" => "/template/{id}/{version}"
     ],
    "created_at" => "created at",
    "sent_at" => "sent to provider at",
];

Error codes

If the request is not successful, the client will return an Alphagov\Notifications\Exception\NotifyException object containing the relevant error code:

exc->getCode() exc->getErrors() How to fix
400 [{
"error": "ValidationError",
"message": "id is not a valid UUID"
}]
Check the notification ID.
403 [{
"error": "AuthError",
"message": "Error: Your system clock must be accurate to within 30 seconds"
}]
Check your system clock.
403 [{
"error": "AuthError",
"message": "Invalid token: signature, api token not found"
}]
Use the correct API key. Refer to API keys for more information.
404 [{
"error": "NoResultFound",
"message": "No result found"
}]
Check the notification ID.

Get the status of multiple messages

This API call returns one page of up to 250 messages and statuses. You can get either the most recent messages, or get older messages by specifying a particular notification ID in the older_than argument.

You can only get the status of messages that are 7 days old or newer.

Method

listNotifications( array $filters = array() )
    $response = $notifyClient->listNotifications([
        'older_than' => 'c32e9c89-a423-42d2-85b7-a21cd4486a2a',
        'reference' => 'weekly-reminders',
        'status' => 'delivered',
        'template_type' => 'sms'
    ]);

You can leave out the older_than argument to get the 250 most recent messages.

To get older messages, pass the ID of an older notification into the older_than argument. This returns the next 250 oldest messages from the specified notification ID.

Arguments

You can leave out any of these arguments to ignore these filters.

template_type (optional)

You can filter by:

  • email
  • sms
  • letter

You can leave out this argument to ignore this filter.

status (optional)

status description text email letter Precompiled letter
created GOV.UK Notify has placed the message in a queue, ready to be sent to the provider. It should only remain in this state for a few seconds. Yes Yes
sending GOV.UK Notify has sent the message to the provider. The provider will try to deliver the message to the recipient. GOV.UK Notify is waiting for delivery information. Yes Yes
delivered The message was successfully delivered Yes Yes
sent / sent internationally The message was sent to an international number. The mobile networks in some countries do not provide any more delivery information. Yes
pending GOV.UK Notify is waiting for more delivery information.
GOV.UK Notify received a callback from the provider but the recipient’s device has not yet responded. Another callback from the provider determines the final status of the notification.
Yes
failed This returns all failure statuses:
- permanent-failure
- temporary-failure
- technical-failure
Yes Yes
permanent-failure The provider could not deliver the message because the email address or phone number was wrong. You should remove these email addresses or phone numbers from your database. You’ll still be charged for text messages to numbers that do not exist. Yes Yes
temporary-failure The provider could not deliver the message after trying for 72 hours. This can happen when the recipient’s inbox is full or their phone is off. You can try to send the message again. You’ll still be charged for text messages to phones that are not accepting messages. Yes Yes
technical-failure Email / Text: Your message was not sent because there was a problem between Notify and the provider.
You’ll have to try sending your messages again. You will not be charged for text messages that are affected by a technical failure.

Letter: Notify had an unexpected error while sending to our printing provider.

You can leave out this argument to ignore this filter.
Yes Yes
accepted GOV.UK Notify has sent the letter to the provider to be printed. Yes
received The provider has printed and dispatched the letter. Yes
pending-virus-check GOV.UK Notify is scanning the precompiled letter file for viruses. Yes
virus-scan-failed GOV.UK Notify found a potential virus in the precompiled letter file. Yes
validation-failed Content in the precompiled letter file is outside the printable area. Yes

reference (optional)

A unique identifier you can create if necessary. This reference identifies a single unique notification or a batch of notifications. It must not contain any personal information such as name or postal address.

$reference = 'STRING';

You can leave out this argument to ignore this filter.

older_than (optional)

Input the ID of a notification into this argument. If you use this argument, the method returns the next 250 received notifications older than the specified ID.

older_than='740e5834-3a29-46b4-9a6f-16142fde533a'

If you leave out this argument, the method returns the most recent 250 notifications.

The client only returns notifications that are 7 days old or newer. If the notification specified in this argument is older than 7 days, the client returns an empty response.

Response

If the request to the client is successful, the client returns an array.

[
    "notifications" => [
            "id" => "notify_id",
            "reference" => "client reference",
            "email_address" => "email address",
            "phone_number" => "phone number",
            "line_1" => "full name of a person or company",
            "line_2" => "123 The Street",
            "line_3" => "Some Area",
            "line_4" => "Some Town",
            "line_5" => "Some county",
            "line_6" => "Something else",
            "postcode" => "postcode",
            "postage" => "null|first|second",
            "type" => "sms | letter | email",
            "status" => sending | delivered | permanent-failure | temporary-failure | technical-failure
            "template" => [
            "version" => 1,
            "id" => 1,
            "uri" => "/template/{id}/{version}"
        ],
        "created_at" => "created at",
        "sent_at" => "sent to provider at",
        ],
        
  ],
  "links" => [
     "current" => "/notifications?template_type=sms&status=delivered",
     "next" => "/notifications?older_than=last_id_in_list&template_type=sms&status=delivered"
  ]
];

Error codes

If the request is not successful, the client returns an Alphagov\Notifications\Exception\NotifyException object containing the relevant error code:

exc->getCode() exc->getErrors() How to fix
400 [{
"error": "ValidationError",
"message": "bad status is not one of [created, sending, delivered, pending, failed, technical-failure, temporary-failure, permanent-failure]"
}]
Contact the GOV.UK Notify team.
400 [{
"error": "ValidationError",
"message": "Apple is not one of [sms, email, letter]"
}]
Contact the GOV>UK Notify team.
403 [{
"error": "AuthError",
"message": "Error: Your system clock must be accurate to within 30 seconds"
}]
Check your system clock.
403 [{
"error": "AuthError",
"message": "Invalid token: signature, api token not found"
}]
Use the correct API key. Refer to API keys for more information.

Get a template

Get a template by ID

Method

This returns the latest version of the template.

$response = $notifyClient->getTemplate( 'templateId' );

Arguments

templateId (required)

The ID of the template. Sign in to GOV.UK Notify and go to the Templates page to find this.

Response

If the request to the client is successful, the client returns an array.

[
    "id" => "template_id",
    "type" => "sms|email|letter",
    "created_at" => "created at",
    "updated_at" => "updated at",
    "version" => "version",
    "created_by" => "someone@example.com",
    "body" => "body",
    "subject" => "null|email_subject"
];

Error codes

If the request is not successful, the client returns an Alphagov\Notifications\Exception\NotifyException object containing the relevant error code:

exc->getCode() exc->getErrors() How to fix
403 [{
"error": "AuthError",
"message": "Error: Your system clock must be accurate to within 30 seconds"
}]
Check your system clock.
403 [{
"error": "AuthError",
"message": "Invalid token: signature, api token not found"
}]
Use the correct API key. Refer to API keys for more information.
404 [{
"error": "NoResultFound",
"message": "No Result Found"
}]
Check your template ID.

Get a template by ID and version

Method

$response = $notifyClient->getTemplateVersion( 'templateId', 1 );

Arguments

templateId (required)

The ID of the template. Sign in to GOV.UK Notify and go to the Templates page to find this.

version (required)

The version number of the template.

Response

If the request to the client is successful, the client returns an array.

[
    "id" => "template_id",
    "type" => "sms|email|letter",
    "created_at" => "created at",
    "updated_at" => "updated at",
    "version" => "version",
    "created_by" => "someone@example.com",
    "body" => "body",
    "subject" => "null|email_subject"
];

Error codes

If the request is not successful, the client returns an Alphagov\Notifications\Exception\NotifyException object containing the relevant error code:

exc->getCode() exc->getErrors() How to fix
403 [{
"error": "AuthError",
"message": "Error: Your system clock must be accurate to within 30 seconds"
}]
Check your system clock.
403 [{
"error": "AuthError",
"message": "Invalid token: signature, api token not found"
}]
Use the correct API key. Refer to API keys for more information.
404 [{
"error": "NoResultFound",
"message": "No Result Found"
}]
Check your template ID and version.

Get all templates

Method

This returns the latest version of all templates.

    $this->getAllTemplates(
      $template_type  // optional
    );

Arguments

template_type (optional)

If omitted, the method returns all templates. Otherwise you can filter by:

  • email
  • sms
  • letter

Response

If the request to the client is successful, the client returns an array.

[
    "templates"  => [
        [
            "id" => "template_id",
            "type" => "sms|email|letter",
            "created_at" => "created at",
            "updated_at" => "updated at",
            "version" => "version",
            "created_by" => "someone@example.com",
            "body" => "body",
            "subject" => "null|email_subject"
        ],
        [
            ... another template
        ]
    ]
];

If no templates exist for a template type or there no templates for a service, the client returns a dict with an empty templates list element:

[
    "templates"  => []
];

Generate a preview template

Method

This generates a preview version of a template.

    $personalisation = [ "foo" => "bar" ];
    $this->previewTemplate( $templateId, $personalisation );

The parameters in the personalisation argument must match the placeholder fields in the actual template. The API notification client will ignore any extra fields in the method.

Arguments

template_id (required)

The ID of the template. Sign in to GOV.UK Notify and go to the Templates page.

personalisation (required)

If a template has placeholder fields for personalised information such as name or reference number, you need to provide their values in a dictionary with key value pairs. For example:

$personalisation = [
    'first_name' => 'Amala',
    'reference_number' => '300241',
];

Response

If the request to the client is successful, the client returns an array.

[
    "id" => "notify_id",
    "type" => "sms|email|letter",
    "version" => "version",
    "body" => "Hello bar" // with substitution values,
    "subject" => "null|email_subject"
];

Error codes

If the request is not successful, the client returns an Alphagov\Notifications\Exception\NotifyException object containing the relevant error code:

exc->getCode() exc->getErrors() Notes
400 [{
"error": "BadRequestError",
"message": "Missing personalisation: [PERSONALISATION FIELD]"
}]
Check that the personalisation arguments in the method match the placeholder fields in the template.
400 [{
"error": "NoResultFound",
"message": "No result found"
}]
Check the template ID.
403 [{
"error": "AuthError",
"message": "Error: Your system clock must be accurate to within 30 seconds"
}]
Check your system clock.
403 [{
"error": "AuthError",
"message": "Invalid token: signature, api token not found"
}]
Use the correct API key. Refer to API keys for more information.

Get received text messages

This API call returns one page of up to 250 received text messages. You can get either the most recent messages, or get older messages by specifying a particular notification ID in the older_than argument.

You can only get the status of messages that are 7 days old or newer.

You can also set up callbacks for received text messages.

Enable received text messages

Contact the GOV.UK Notify team on the support page or through the Slack channel to enable receiving text messages for your service.

Get a page of received text messages

Method

    $this->listReceivedTexts(
      $older_than  // optional
    );

To get older messages, pass the ID of an older notification into the older_than argument. This returns the next 250 oldest messages from the specified notification ID.

If you leave out the older_than argument, the client returns the most recent 250 notifications.

Arguments

older_than (optional)

Input the ID of a received text message into this argument. If you use this argument, the client returns the next 250 received text messages older than the given ID. For example:

$older_than = '8e222534-7f05-4972-86e3-17c5d9f894e2'

If you leave out the older_than argument, the client returns the most recent 250 notifications.

The client only returns notifications that are 7 days old or newer. If the notification specified in this argument is older than 7 days, the client returns an empty collection response.

Response

If the request to the client is successful, the client returns an array.

[
    "received_text_messages" => [
        [
            "id" => "notify_id",
            "user_number" => "user number",
            "notify_number" => "notify number",
            "created_at" => "created at",
            "service_id" => "service id",
            "content" => "text content"
        ],
        [
            ... another received text message
        ]
    ]
  ],
  "links" => [
     "current" => "/received-text-messages",
     "next" => "/received-text-messages?older_than=last_id_in_list"
  ]
];

Error codes

If the request is not successful, the client returns an Alphagov\Notifications\Exception\NotifyException object containing the relevant error code:

exc->getCode() exc->getErrors() Notes
403 [{
"error": "AuthError",
"message": "Error: Your system clock must be accurate to within 30 seconds"
}]
Check your system clock.
403 [{
"error": "AuthError",
"message": "Invalid token: signature, api token not found"
}]
Use the correct API key. Refer to API keys for more information.

Testing

All testing takes place in the production environment. There is no test environment for GOV.UK Notify.

Smoke testing

If you need to smoke test your integration with GOV.UK Notify on a regular basis, you must use the smoke test phone numbers and email addresses below.

 
Phone number
07700900000
07700900111
07700900222
Email address
simulate-delivered@notifications.service.gov.uk
simulate-delivered-2@notifications.service.gov.uk
simulate-delivered-3@notifications.service.gov.uk

The smoke test phone numbers and email addresses will validate the request and simulate a successful response, but won’t send a real message, produce a delivery receipt or persist the notification to the database.

You can use these smoke test numbers and addresses with any type of API key.

You can smoke test all GOV.UK Notify API client functions except:

  • Get the status of one message
  • Get the status of all messages

You cannot use the smoke test phone numbers or email address with these functions because they return a fake notification_ID. If you need to test these functions, use a test API key and any other phone number or email.

Other testing

You must use a test API key to do non-smoke testing such as performance or integration testing. You can use any non-smoke testing phone numbers or email addresses. You don’t need a specific GOV.UK Notify testing account.

API keys

There are three different types of API keys:

  • test
  • team and whitelist
  • live

To get an API key, sign in to GOV.UK Notify and go to the API integration page.

When you first sign up to Notify, you can create test and team and whitelist keys. You must have a live service to create a live key.

Test

Use a test key to test the performance of your service and its integration with GOV.UK Notify.

Messages sent using a test key:

  • generate realistic responses
  • result in a delivered status
  • are not actually delivered to a recipient
  • do not appear on your dashboard
  • do not count against your text message and email allowances

To test failure responses with a test key, use the following numbers and addresses:

Phone number/Email address Response
07700900003 temporary-failure
07700900002 permanent-failure
temp-fail@simulator.notify temporary-failure
perm-fail@simulator.notify permanent-failure
any other valid number or address delivered

You do not have to revoke test keys.

Team and whitelist

A team and whitelist key lets you send real messages to your team members and addresses/numbers on your whitelist while your account is still in trial mode.

You will get an error if you use these keys to send messages to anyone who isn’t on your team or your whitelist.

Messages sent with a team and whitelist key appear on your dashboard and count against your text message and email allowances.

You do not have to revoke team and whitelist keys.

Live

You can only create live keys once your service is live. You can use live keys to send messages to anyone.

Messages sent with a live key appear on your dashboard and count against your text message and email allowances.

You should revoke and re-create these keys on a regular basis. To revoke a key:

  1. Log into your GOV.UK Notify account.
  2. Select API integration and then API keys.
  3. Select Revoke for the API key you want to revoke.

You can have more than one active key at a time.

You should never send test messages to invalid numbers or addresses using a live key.

Limits

Rate limits

You’re limited to sending 3,000 messages per minute.

This limit is calculated on a rolling basis, per API key type. If you exceed the limit, you will get a 429 error RateLimitError.

Daily limits

There’s a limit to the number of messages you can send each day:

Service status Type of API key Daily limit
Live Team or live 250,000
Trial Team 50
Live or trial Test Unlimited

These limits reset at midnight.

Phone network limits

If you repeatedly send text messages to the same number the phone networks will block them.

There’s an hourly limit of:

  • 20 messages with the same content
  • 100 messages with any content

Your messages may not be delivered if you exceed these limits.

Callbacks

Callbacks are when Notify sends POST requests to your service. You can get callbacks when:

  • a text message or email you’ve sent is delivered or fails
  • your service receives a text message

Set up callbacks

You must provide:

  • a URL where Notify will post the callback to
  • a bearer token which Notify will put in the authorisation header of the requests

To do this, log into your GOV.UK Notify account, go to API integration and select Callbacks.

Delivery receipts

When you send an email or text message through Notify, Notify will send a receipt to your callback URL with the status of the message. This is an automated method to get the status of messages.

This functionality works with test API keys, but does not work with smoke testing phone numbers or email addresses.

The callback message is formatted in JSON. The key, description and format of the callback message arguments will be:

Key Description Format
id Notify’s id for the status receipts UUID
reference The reference sent by the service 12345678
to The email address or phone number of the recipient hello@gov.uk or 07700912345
status The status of the notification delivered, permanent-failure, temporary-failure or technical-failure
created_at The time the service sent the request 2017-05-14T12:15:30.000000Z
completed_at The last time the status was updated 2017-05-14T12:15:30.000000Z or nil
sent_at The time the notification was sent 2017-05-14T12:15:30.000000Z or nil
notification_type The notification type email or sms

Received text messages

If your service receives text messages in Notify, Notify can forward them to your callback URL as soon as they arrive.

Contact the GOV.UK Notify team on the support page or through the Slack channel to enable receiving text messages for your service.

The callback message is formatted in JSON. The key, description and format of the callback message arguments will be:

Key Description Format
id Notify’s id for the received message UUID
source_number The phone number the message was sent from 447700912345
destination_number The number the message was sent to (your number) 07700987654
message The received message Hello Notify!
date_received The UTC datetime that the message was received by Notify 2017-05-14T12:15:30.000000Z

API architecture

Send a message

Notify send a message

Get message status

Notify get message status

Get inbound messages

Notify get inbound messages

Support

Report any problems via the GOV.UK Notify support page.

You can also: