Receiving Amazon SNS Messages in PHP
A little over a year ago, we announced a new feature in the AWS SDK for PHP that allowed customers to validate inbound SNS messages. In the latest version of the SDK, this functionality is now available in its own package, one that does not depend on the SDK, so it’s simpler to listen to SNS topics with lightweight web services. In this blog post, I’ll show you how to use the Amazon SNS message validator for PHP to parse messages in a single-file web application.
About SNS
Amazon Simple Notification Service (Amazon SNS) is a fast and fully managed push messaging service that can deliver messages over email, SMS, mobile push, and HTTP/HTTPS endpoints.
With Amazon SNS, you can set up topics to publish custom messages to subscribed endpoints. SNS messages are used by many of the other AWS services to communicate information asynchronously about your AWS resources. Some examples include:
- Configuring Amazon Glacier to notify you when a retrieval job is complete.
- Configuring AWS CloudTrail to notify you when a new log file has been written.
- Configuring Amazon Elastic Transcoder to notify you when a transcoding job changes status (e.g., from “Progressing” to “Complete”)
Receiving SNS Messages and Verifying Their Signature
<?php require 'path/to/vendor/autoload.php'; $message = AwsSnsMessage::fromRawPostData(); echo $message->get('Message');
Amazon SNS sends different types of messages, including SubscriptionConfirmation
, Notification
, and UnsubscribeConfirmation
. The formats of these messages are described in the Appendix: Message and JSON Formats section of the Amazon SNS Developer Guide.
Messages from Amazon SNS are signed. As a best practice, you should use the MessageValidator
class to verify the signature and ensure a message was sent from Amazon SNS.
<?php use AwsSnsMessage; use AwsSnsMessageValidator; $message = Message::fromRawPostData(); // Validate the message $validator = new MessageValidator(); $validator->validate($message);
Instances of AwsSnsMessageValidator
have two methods for validating messages, both of which take an instance of AwsSnsMessage
as their only argument. validate
(shown above) will throw an AwsSnsExceptionInvalidSnsMessageException
. isValid
will return a Boolean — true
for valid messages and false
for invalid ones.
Confirming a Subscription to a Topic
In order for an HTTP(S) endpoint to receive messages, it must first be subscribed to an SNS topic. Subscriptions are confirmed over HTTP(S), so you’ll need to create and deploy an endpoint before you set up a subscription. SubscriptionConfirmation
messages provide a URL you can use to confirm the subscription.
$message = AwsSnsMessage::fromRawPostData(); // Validate the message $validator = new MessageValidator(); if ($validator->isValid($message)) { file_get_contents($message->get('SubscribeURL')); }
Handling Notifications
Let’s put it all together and add some extra code for handling both notifications and subscription control messages.
<?php if ('POST' !== $_SERVER['REQUEST_METHOD']) { http_response_code(405); die; } require 'path/to/vendor/autoload.php'; try { $message = AwsSnsMessage::fromRawPostData(); $validator = new AwsSnsMessageValidator(); $validator->validate($message); if (in_array($message['Type'], ['SubscriptionConfirmation', 'UnsubscribeConfirmation']) { file_get_contents($message['SubscribeURL']); } $log = new SplFileObject('../messages.log', 'a'); $log->fwrite($message['Message'] . "n"); } catch (Exception $e) { http_response_code(404); die; }
Conclusion
As you can see, receiving, verifying, and handling Amazon SNS messages is simple. Setting up your application to receive SNS messages will allow you to create applications that can handle asynchronous communication from AWS services and other parts of your application.
相關推薦
Receiving Amazon SNS Messages in PHP
A little over a year ago, we announced a new feature in the AWS SDK for PHP that allowed customers to validate inbound SNS messages. In the lates
Introducing support for Amazon S3 Select in the AWS SDK for PHP
We’re excited to announce support for the Amazon Simple Storage Service (Amazon S3) SelectObjectContent API with event streams in the AWS SDK for
Encrypting messages published to Amazon SNS with AWS KMS
Amazon Simple Notification Service (Amazon SNS) is a fully managed pub/sub messaging service for decoupling event-driven microservices, distribute
PHP7新特性 What will be in PHP 7/PHPNG
分享一下我老師大神的人工智慧教程!零基礎,通俗易懂!http://blog.csdn.net/jiangjunshow 也歡迎大家轉載本篇文章。分享知識,造福人民,實現我們中華民族偉大復興!  
google'map in php (thinkphp5)
<!DOCTYPE html> <html lang="en"> <head> <meta http-equiv="X-UA-Compatible" content="IE=7" /> <meta http-equiv="Content-Type
How do I interpret scsi status messages in RHEL like "sd 2:0:0:243: SCSI error: return code = 0x0800
Issue What does "return code = 0xNNNNNNNN" mean, for example 0x08000002 within the following: Raw Oct 23 14:56:25 uname kernel: sdas: C
Zend Signal in PHP 5.4
在PHP5.4中, 根據由Rasmus提交的RFC, 引入了一套新的訊號處理機制, 目的是為了使得訊號遮蔽機制可以應用到任何SAPI中, 並且提高在這個過程中的PHP效能. 新的機制, 叫做zend signal, 它的理念, 來自Yahoo的”延遲訊號處理”(Yah
Parsing HTML in PHP
Have you ever wanted to get a list of the links contained in a HTML page? Or a list of images, the title or every other non-nested tag for
Useful functions in PHP
從手冊上整理了一些有用且比較常用的php函式, 便於以後查閱. 1. htmlspecialchars Convert special characters to HTML entities (PHP 4, PHP 5) string htmlspecialchar
Use the Results of an Amazon Athena Query in Another Query
Amazon Web Services is Hiring. Amazon Web Services (AWS) is a dynamic, growing business unit within Amazon.com. We are currently hiring So
Amazon RDS Stuck in Modifying
By design, storage scaling operations for an Amazon RDS instance have a minimal impact on ongoing database operations. For this reason, the ope
Recreate an Amazon SNS Cross
Amazon Web Services is Hiring. Amazon Web Services (AWS) is a dynamic, growing business unit within Amazon.com. We are currently hiring So
Simplify Your Pub/Sub Messaging with Amazon SNS Message Filtering
Contributed by: Stephen Liedig, Senior Solutions Architect, ANZ Public Sector, and Otavio Ferreira, Manager, Amazon Simple Notification Service
Troubleshoot Failed Amazon SNS Push Notification Deliveries
“Failed” is appended to the log entry if the delivery was unsuccessful. The logs provide the time taken (dwellTimeMs), message ID, d
Amazon RDS Launch in VPC
Amazon Web Services is Hiring. Amazon Web Services (AWS) is a dynamic, growing business unit within Amazon.com. We are currently hiring So
Subscribe an SQS Queue to an SNS Topic in Another CloudFormation Stack
Amazon Web Services is Hiring. Amazon Web Services (AWS) is a dynamic, growing business unit within Amazon.com. We are currently hiring So
Bites of IoT – Rules Engine and Amazon SNS
Welcome to another installment in the Bites of IoT blog series. In this bite, we will use the AWS IoT rules engine to select and route a m
Launch an Amazon EMR Cluster in a VPC Environment
Amazon Web Services is Hiring. Amazon Web Services (AWS) is a dynamic, growing business unit within Amazon.com. We are currently hiring So
Invoking AWS Lambda functions via Amazon SNS
We released a new feature today for Amazon SNS that enables developers to perform custom message handling or publish messages to other AWS servic
Amazon SNS 訊息推送_資訊收發與移動推送服務
Amazon Simple Queue Service (SQS) 是一種持久、安全、完全託管的釋出/訂閱訊息收發服務,可以輕鬆分離微服務、分散式系統和無伺服器應用程式。Amazon SNS 提供了面向高吞吐量、多對多推送式訊息收發的主題。藉助 Amazon SNS 主題,釋出系統可以向大