Site icon Web Niraj

AWS SNS: Sending a SMS Message using the AWS PHP SDK

Amazon makes it really easy to send SMS messages worldwide using their SNS or Simple Notification Service. This tutorial shows you how you can send a SMS in less than 10 lines of code. This particular example uses composer to install the AWS SDK.

Installation

Start by installing the AWS PHP SDK using composer:

composer require aws/aws-sdk-php

AWS Access Key and Secret

If you haven’t setup a Key and Secret to access the AWS APIs, you can do so using the IAM Management Console. Here are some basic instructions you can follow:

  1. User Details
    1. Create a new “User name”, e.g. “SMS”
    2. Set the “Access type” to “Programmatic access”
  2. Permissions
    1. Select “Attach existing policies directly”
    2. Search for “SNS”
    3. Check the box for “AmazonSNSFullAccess” to allow SNS access
  3. Complete
    1. Make a note of the “Access key ID” and “Secret access key”. You won’t be able to access the “Secret access” key again.

The Code

The below code can be used to send a SMS. Extra line breaks have been added to make the code readable – otherwise, the code can be condensed to as little as 5 lines.

See the gist on github.

On line 7, you’ll need to set the “key” (which is your “Access key ID”) and the “secret” (which is your “Secret access key”). If you wish to use a different AWS region, you can update line 5 to your region ID.

Lines 10-17 can be updated to specify your SMS message (using “Message”) and the phone number (using “PhoneNumber”, remember to include the international country code) to send the message to.

If you haven’t set a Sender ID from the SNS Console, you can specify one in the code (update “WebNiraj” in the code to an alphanumeric string (no spaces or symbols allowed).

The Result

Calling the API successfully will return a message ID in the form 4f218c80-3c95-5b41-b4c7-de59b89b01c3. As for the actual delivery of the message, this can be tracked from the SNS Console.

Exit mobile version