Amazon SNS with Magento 2

Updates [April 15,2023] : I have developed an extension for this, please purchase from link Promotion SMS Extension.

In one of my project I had to use AWS SNS service to send an SMS from Magento

I am explaining here a basic way to implement the same

1) Refer aws-sdk-php to install AWS SDK
Guide – sdk-for-php

2) Create a Magento configuration to store access key, secret key, version, region, topic

3) Set the SNS client

/**
* GET SNS Client
* @return SnsClient
*/
public function getSnsClient()
{
	$publicKey = $this->getAccessKey();
	$secretKey = $this->getSecretKey();
	$version   = $this->getVersion();
	$region    = $this->getRegion();
	$topic     = $this->getTopic();
	$params    = [
	    'credentials' => [
		'key' => $publicKey,
		'secret' => $secretKey,
	    ],
	    'region' => $region,
	    'version' => $version,
	    'topic'  => $topic,
	];
	try {
	    $snsClient = new SnsClient($params);
	} catch (AwsException $e) {
	    $this->snsLogger->error($e->getMessage());
	}

	return $snsClient;
}//end getSnsClient()

4) Send SMS

 /**
* @param string $mobileNumber Mobile Number
* @param string $message Message
* @param $smsType
* @return bool
*/
public function sendSMS($mobileNumber, $message, $smsType)
{
try {
    $snsClient = $this->getSnsClient();
    if (!empty($mobileNumber)) {
        if (!empty($this->getSenderId())) {
            $snsClient->setSMSAttributes([
                'attributes' => ['DefaultSenderID' => $this->getSenderId()],
            ]);
        }

        /** @var \Aws\Result $result */
        $result        = $snsClient->publish([
            'PhoneNumber' => $mobileNumber,
            'Message' => $message,
        ]);

        $messageStatus = $result->get('@metadata');

        if ($messageStatus['statusCode'] != '200') {
            $this->snsLogger->info(json_encode($result));
            return false;
        }
    } else {
        $this->snsLogger->error('Mobile Number is empty');
        return false;
    }
} catch (AwsException $e) {
    $this->snsLogger->error($e->getMessage());
    return false;
}

Hope this is helpful

Leave a Reply

Your email address will not be published. Required fields are marked *

Scroll to top