PHP 5.6 way to send AWS SNS topic message

This is an example PHP 5.6 script to send AWS SNS topic message.

The architecture and assumption are as follow:

Architecture:

  • SNS (FIFO) -> SQS(FIFO) -> Lambda

  • Only FIFO SNS can connect to FIFO SQS. Standard SNS cannot publish to FIFO SQS.

Assumption:

  • This script is executed in an EC2 instance.

  • Assigned an AWS role to send SNS message.

  • Because of above, supposed that there is no need to use Credential when creating SnsClient object.

  • As the OS and PHP in this EC2 is old, the curlis already outdated. So it set httpto false to bypass SSL verification.  Reference here.

  • The $message part is designed for sending email for different vendor. In other words, it would vary in different case.

  • Since SNS and SQS are FIFO, MessageGroupId must be set. It can be any random string, which is used to group message together for sending purpose.

Here is the code

<?php 
require_once 'vendor/autoload.php';

use Aws\Sns\SnsClient;

try{
    $snsClient = new SnsClient([
        'version' => '2010-03-31',
        'region' => 'ap-east-1',        
        'http' => [
            'verify' => false
        ]
    ]);

    $message = [
        "EmailSubject" => "[SNS] Test email subject ".date("Y-m-d H:i:s"),
        "EmailContent" => "<html><head></head<body>My email content</body></html>",
        "ToAddresses" => "test email|yeworec368@degcos.com",
    ];
    
    $messageAttributes = [
        'ActionTrigger' => [
            'DataType' => 'String',
            'StringValue' => 'sending_email',
        ],
    ];
    
    $params = [
        "MessageGroupId" => date("YmdHi"),
        'Message' => json_encode($message),
        'MessageAttributes' => $messageAttributes,
        'TopicArn' => 'arn:aws:sns:ap-east-1:<your_AWS_account_id>:sns-sending-email.fifo',        
    ];
    
    $result = $snsClient->publish($params);
    
    if ($result['MessageId']) {
        echo "Message sent successfully. Message ID: " . $result['MessageId'];
    } else {
        echo "Error sending message: " . $result['ErrorMessage'];
    }
    
}catch(Exception $e){
    echo $e->getMessage();
    print '<br/>';
}
?>

Hope it helps someone.

Comments

Popular posts from this blog

TCPDF How to show/display Chinese Character?

How to fix fancy box/Easy Fancybox scroll not work in mobile

Wordpress Load balancing: 2 web servers 1 MySQL without any Cloud services