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

Prerequisites

The ID of the consumer group that has subscribed to the messages of a topic is obtained.

Download the SDK

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 the instructions, see Stomp PHP.

For information about the PHP versions for which Stomp SDK for PHP is suitable, see the declaration of the require parameter in the composer.json file of Stomp SDK for PHP.

Stomp PHP 5.0.0 or earlier may fail to reconnect to IoT Platform after the SDK is disconnected. We recommend that you download Stomp PHP 5.0.0 or later. For more information, see Issues.

In the PHP project directory, run the following command to download the SDK of Stomp PHP 5.0.0:

composer require stomp-php/stomp-php 5.0.0

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;

// The parameters. For more information, see the "Connect an AMQP client to IoT Platform" topic. 
$accessKey = "${YourAccessKeyId}";
$accessSecret = "${YourAccessKeySecret}";
$consumerGroupId = "${YourConsumerGroupId}";
$clientId = "${YourClientId}";
// iotInstanceId: the ID of the instance. 
$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 want to transmit messages in the binary format, specify encode=base64 in the userName parameter. Before IoT Platform sends these messages, IoT Platform 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 30 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();
    }
}   

You can configure the parameters in the preceding code based on the parameter descriptions in the following table. For more information about the parameters, see Connect an AMQP client to IoT Platform.

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 RAM user. This policy allows the RAM 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 ID of the consumer group.

To view the ID of the consumer group, perform the following steps: Log on to the IoT Platform console and click the card of the instance that you want to manange. Choose Rules Engine > Server-side Subscription > Consumer Groups. The ID is displayed on the Consumer Groups tab.

iotInstanceId "" The ID of the instance. You can view the ID of the instance on the Overview page in the IoT Platform console.
  • If you have an ID value, you must specify the ID for this parameter.
  • If no Overview or ID is generated for your instance, specify an empty string (iotInstanceId = "") for the parameter.
clientId 12345 The ID of the client. You must specify a custom ID. The ID must be 1 to 64 characters in length. We recommend that you use a unique identifier, such as the UUID, MAC address, or IP address of the client.

After the AMQP client is connected to IoT Platform and started, perform the following steps to view the details of the client: Log on to the IoT Platform console and click the card of the instance that you want to manage. Choose Rules Engine > Server-side Subscription > Consumer Groups. Find the consumer group that you want to manage and click View in the Actions column. The ID of each client is displayed on the Consumer Group Details page. You can use client IDs to efficiently identify clients.

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

For more information about the endpoints that you can specify for the ${YourHost} variable, see View the endpoint of an instance.

Sample results

  • Sample success result: If the displayed output is similar to the following log information, the AMQP client is connected to IoT Platform and can receive messages.Success
  • Sample failure result: If the displayed output is similar to the following log information, the AMQP client fails to connect to IoT Platform.

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

    Failed

Messages in the binary format

If you want to transmit messages in the binary format, use the Base64 algorithm to encode the messages. If you do not use the Base64 algorithm to encode the messages, the messages may be truncated because STOMP is a text-based protocol.

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" . "|";

References

For more information about the error codes that are related to server-side subscription, see Error codes that are related to messages.