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.
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:
- User Details
- Create a new “User name”, e.g. “SMS”
- Set the “Access type” to “Programmatic access”
- Select “Attach existing policies directly”
- Search for “SNS”
- Check the box for “AmazonSNSFullAccess” to allow SNS access
- 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 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.
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).
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.