Subscribe to Aliyun Internet of Things Platform Device Message PHP Example Reference Using Message Service (MNS)

Keywords: PHP SDK JSON Java


Internet of Things Platform Server Subscription supports sending device messages to Message Services (MNS). Cloud applications obtain device messages by listening to MNS queues. This article mainly demonstrates the use of the latest version of MNS PHP SDK to consume messages subscribed to MNS Queue.

Operation steps

1. Server-side subscription configuration

Reference link In the link, the configuration of MNS subscription on the server side and the method of retrieving messages in Queue using Java SDK are introduced.

2,MNS PHP SDK install


  "require": {
     "aliyun/aliyun-mns-php-sdk": ">=1.0.0"


composer install

3,Code Sample


require_once 'vendor/autoload.php';

use AliyunMNS\Client;
use AliyunMNS\Exception\MnsException;

class CreateQueueAndSendMessage
    private $accessId;
    private $accessKey;
    private $endPoint;
    private $client;
    private $queueName;

    public function __construct($accessId, $accessKey, $endPoint, $queueName)
        $this->accessId = $accessId;
        $this->accessKey = $accessKey;
        $this->endPoint = $endPoint;
        $this->queueName = $queueName;

    public function run()
        $this->client = new Client($this->endPoint, $this->accessId, $this->accessKey);

        $queue = $this->client->getQueueRef($this->queueName);

        $receiptHandle = NULL;
            // when receiving messages, it's always a good practice to set the waitSeconds to be 30.
            // it means to send one http-long-polling request which lasts 30 seconds at most.
            $res = $queue->receiveMessage(30);
            echo "ReceiveMessage Succeed! \n";
            // json object to array
            $aTest = json_decode($res->getMessageBody(), true);
            // Get the payLoad value
            $payLoad = $aTest["payload"];
            // base64 decoding
            echo base64_decode($payLoad);
            $receiptHandle = $res->getReceiptHandle();
        catch (MnsException $e)
            echo "ReceiveMessage Failed: " . $e;
        // 4. delete message
            $res = $queue->deleteMessage($receiptHandle);
            echo "<br/> DeleteMessage Succeed! \n";
        catch (MnsException $e)
            echo "DeleteMessage Failed: " . $e;

// ak,sk information access can refer to links: ad926a2HiTVqH
// endPoint and queueName are accessed to the MNS management console:
$accessId = "********";
$accessKey = "********";
$endPoint = "http://********";
$queueName = "aliyun-iot-********";

if (empty($accessId) || empty($accessKey) || empty($endPoint))
    echo "Must Provide AccessId/AccessKey/EndPoint to Run the Example. \n";

$instance = new CreateQueueAndSendMessage($accessId, $accessKey, $endPoint,$queueName);


4. Project structure

5. Operation results

Reference link


Posted by phence on Wed, 09 Oct 2019 00:17:40 -0700