This article describes how to use the SDK for PHP to connect a client with IoT Platform and receive messages from IoT Platform.

Download the SDK for PHP

The sample code is written based on the Stomp PHP library and allows you to connect a Stomp PHP client to IoT Platform over Simple Text Oriented Message Protocol (STOMP). To download a Stomp PHP client and view its instructions, see Stomp PHP.

You can go to the directory where the PHP project file resides, and run the following command to download the dependencies:

composer require stomp-php/stomp-php

Sample code

<?php
require __DIR__ . '/vendor/autoload.php';
use Stomp\Client;
use Stomp\Network\Observer\Exception\HeartbeatException;
use Stomp\Network\Observer\ServerAliveObserver;
use Stomp\StatefulStomp;

// For more information about parameters, see the "Connect an AMQP client to IoT Platform" topic. 
$accessKey = "${YourAccessKeyId}";
$accessSecret = "${YourAccessKeySecret}";
$consumerGroupId = "${YourConsumerGroupId}";
$clientId = "${YourClientId}";
// iotInstanceId: If you use a purchased instance, you must specify the instance ID. If you use a public instance, you can enter an empty string (""). 
$iotInstanceId = "${YourIotInstanceId}";
$timeStamp = round(microtime(true) * 1000);
// The signature algorithm. Valid values: hmacmd5, hmacsha1, and hmacsha256. 
$signMethod = "hmacsha1";
// The structure of the userName parameter. For more information, see the "Connect an AMQP client to IoT Platform" topic. 
// If you need to transmit messages in the binary format, you must specify encode=base64 in the userName parameter. Before IoT Platform sends these messages, it encodes these messages by using the Base64 algorithm. For more information, see the "Messages in the binary format" section. 
$userName = $clientId . "|authMode=aksign"
            . ",signMethod=" . $signMethod
            . ",timestamp=" . $timeStamp
            . ",authId=" . $accessKey
            . ",iotInstanceId=" . $iotInstanceId
            . ",consumerGroupId=" . $consumerGroupId
            . "|";
$signContent = "authId=" . $accessKey . "&timestamp=" . $timeStamp;
// Calculate a signature. For more information about how to specify the password parameter, see the "Connect an AMQP client to IoT Platform" topic. 
$password = base64_encode(hash_hmac("sha1", $signContent, $accessSecret, $raw_output = TRUE));
// The endpoint. For more information, see the "Connect an AMQP client to IoT Platform" topic. 
$client = new Client('ssl://${YourHost}:61614');
$sslContext = ['ssl' => ['verify_peer' => true, 'verify_peer_name' => false], ];
$client->getConnection()->setContext($sslContext);

// Configure a listener to monitor the status of the connection between the client and IoT Platform. 
$observer = new ServerAliveObserver();
$client->getConnection()->getObservers()->addObserver($observer);
// The heartbeat setting. This setting enables IoT Platform to send a heartbeat packet every 10 seconds. 
$client->setHeartbeat(0, 30000);
$client->setLogin($userName, $password);
try {
    $client->connect();
}
catch(StompException $e) {
    echo "failed to connect to server, msg:" . $e->getMessage() , PHP_EOL;
}
// Run the following code if no exceptions occur: 
$stomp = new StatefulStomp($client);
$stomp->subscribe('/topic/#');
echo "connect success";

while (true) {
    try {

        // Check the connection status.
        if (!$client->isConnected()) {
            echo "connection not exists, will reconnect after 10s.", PHP_EOL;
            sleep(10);
            $client->connect();
            $stomp->subscribe('/topic/#');
            echo "connect success", PHP_EOL;
        }

        // Specify the business logic to process messages. 
        echo $stomp->read();
    }
    catch(HeartbeatException $e) {
        echo 'The server failed to send us heartbeats within the defined interval.', PHP_EOL;
        $stomp->getClient()->disconnect();
    } catch(Exception $e) {
        echo 'process message occurs error: '. $e->getMessage() , PHP_EOL;
        $stomp->getClient()->disconnect();
    }
}   
Parameter Example Description
accessKey LTAI4GFGQvKuqHJhFa****** Log on to the IoT Platform console, move the pointer over the profile picture, and then click AccessKey Management to obtain the AccessKey ID and AccessKey secret.
Note If you use a RAM user, you must attach the AliyunIOTFullAccess permission policy to the user. This policy allows the user to manage IoT Platform resources. Otherwise, the connection with IoT Platform fails. For more information about how to authorize a RAM user, see RAM user access.
accessSecret iMS8ZhCDdfJbCMeA005sieKe******
consumerGroupId VWhGZ2QnP7kxWpeSSjt****** The consumer group ID.

Log on to the IoT Platform console. Choose Rules > Server-side Subscription > Consumer Groups and view the ID of the required consumer group.

iotInstanceId "" The ID of the instance. Enter an empty string ("").
clientId 12345 The client ID. You must use a unique identifier, such as the UUID, MAC address, or IP address of the client. The client ID must be 1 to 64 characters in length.

Log on to the IoT Platform console. Choose Rules > Server-side Subscription > Consumer Groups, and click View next to the required consumer group. The Consumer Group Details shows the parameter. This parameter allows you to identify clients.

client new Client('ssl://233***.iot-amqp.cn-shanghai.aliyuncs.com:61614') Establish a connection between the AMQP Client and IoT Platform. Format: $client = new Client('ssl://${YourHost}:61614');

${YourHost} format: ${uid}.iot-amqp.${YourRegionId}.aliyuncs.com.

  • ${uid}: Replace this variable with the ID of your Alibaba Cloud account. You can log on to the IoT Platform console, and move the pointer over the profile picture to view the account ID.
  • ${YourRegionId}: Replace this variable with the ID of the region where your IoT Platform device resides. For more information about region IDs, see Regions and zones.

Sample results

  • Sample success result: After you run the code, the following log data may be returned. The data indicates that the AMQP client is connected to IoT Platform and can receive messages.Success
  • Sample failure result:

    You can check the code or network environment based on logs, solve the problem, and then run the code again.

    Failure

Messages in the binary format

If you need to transmit messages in the binary format, you must use the Base64 algorithm to encode these messages because STOMP is a text-based protocol. Otherwise, messages may be truncated.

The following code shows how to specify encode=base64 in the userName parameter. This setting enables IoT Platform to encode messages by using the Base64 algorithm before IoT Platform send the messages.

$userName = $clientId . "|authMode=aksign"
                . ",signMethod=" . $signMethod
                . ",timestamp=" . $timeStamp
                . ",authId=" . $accessKey
                . ",iotInstanceId=" . $iotInstanceId
                . ",consumerGroupId=" . $consumerGroupId
                . ",encode=base64" . "|";