PHP SDK connection example
Connect to IoT Platform and receive server-side subscription messages by using the PHP SDK.
Prerequisites
You have obtained a consumer group ID and subscribed to the required topic messages.
Manage AMQP consumer groups: You can use the default consumer group (DEFAULT_GROUP) in IoT Platform or create a consumer group.
Configure an AMQP server-side subscription: Subscribe to the required topic messages using a consumer group.
Download the SDK
This sample code uses the Stomp PHP library to communicate with IoT Platform over the STOMP protocol. Visit Stomp PHP to download the client and view the instructions.
For compatible PHP versions, see the require declaration in the composer.json file of the Stomp PHP SDK.
Stomp PHP versions earlier than 5.0.0 have a known reconnection issue. We recommend version 5.0.0 or later. For more information, see Issues.
Run the following command in your PHP project directory to install 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;
// For parameter details, see the documentation on connecting an AMQP client.
// WARNING: Hard-coding your AccessKey is a security risk. This example retrieves it from an environment variable for enhanced security.
$accessKey = getenv("ALIBABA_CLOUD_ACCESS_KEY_ID");
$accessSecret = getenv('ALIBABA_CLOUD_ACCESS_KEY_SECRET');
$consumerGroupId = "${YourConsumerGroupId}";
$clientId = "${YourClientId}";
// iotInstanceId: The ID of the IoT Platform instance.
$iotInstanceId = "${YourIotInstanceId}";
$timeStamp = round(microtime(true) * 1000);
// The signature algorithm. Supported values are hmacmd5, hmacsha1, and hmacsha256.
$signMethod = "hmacsha1";
// For instructions on how to construct the username, see the AMQP client connection documentation.
// To transmit binary data, add the encode=base64 parameter to the username. The server will then Base64-encode the message body before sending the message. See the "Binary message body" section for more information.
$userName = $clientId . "|authMode=aksign"
. ",signMethod=" . $signMethod
. ",timestamp=" . $timeStamp
. ",authId=" . $accessKey
. ",iotInstanceId=" . $iotInstanceId
. ",consumerGroupId=" . $consumerGroupId
. "|";
$signContent = "authId=" . $accessKey . "×tamp=" . $timeStamp;
// Calculate the signature. For instructions on how to construct the password, see the documentation on connecting an AMQP client.
$password = base64_encode(hash_hmac("sha1", $signContent, $accessSecret, $raw_output = TRUE));
// The connection endpoint. For details, see the AMQP client connection documentation.
$client = new Client('ssl://${YourHost}:61614');
$sslContext = ['ssl' => ['verify_peer' => true, 'verify_peer_name' => false], ];
$client->getConnection()->setContext($sslContext);
// Listen for server heartbeats.
$observer = new ServerAliveObserver();
$client->getConnection()->getObservers()->addObserver($observer);
// Heartbeat configuration. The client expects a heartbeat packet from the server 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;
}
// If the connection is successful, execution continues.
$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;
}
// Add your message processing logic here.
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();
}
}
Replace the placeholder values in the code with your actual values as described in the following table. For more information about the parameters, see Connect an AMQP client to IoT Platform.
Make sure that you specify valid parameter values. Otherwise, the AMQP client fails to connect to IoT Platform.
|
Parameter |
Description |
|
accessKey |
Log on to the IoT Platform console, hover over your profile picture in the upper-right corner, and click AccessKey Management to obtain the AccessKey ID and AccessKey secret. Note
If you use a RAM user, you must grant the RAM user the permission to manage IoT Platform (AliyunIOTFullAccess). Otherwise, the connection fails. For more information about how to grant the permission, see RAM User Access. |
|
accessSecret |
|
|
consumerGroupId |
The ID of the consumer group in the IoT Platform instance. Log on to the IoT Platform console. In the corresponding instance, go to to view your consumer group ID. |
|
iotInstanceId |
The ID of the instance. You can find this on the Overview page of the IoT Platform console.
|
|
clientId |
The client ID. You must define this ID. The ID can be up to 64 characters in length. We recommend that you use a unique identifier, such as the UUID, MAC address, or IP address of the server where your AMQP client is located. After the AMQP client is connected and starts, log on to the IoT Platform console. On the Consumer Groups tab of the page for the instance, click View next to the consumer group. The Consumer Group Details page displays this parameter. This helps you identify different clients. |
|
client |
Creates a connection between the AMQP client and IoT Platform: For information about the AMQP endpoint for |
Sample results
-
Success: A log message similar to the following is returned, indicating that the AMQP client has connected to IoT Platform and successfully received messages.
$ php newfile.php connect successMESSAGE qos:1 destination:/xxx/thing/event/property/post message-id:xxx2096 topic:/xxx/xxx2/thing/event/property/post subscription:xxx generateTime:xxx {"deviceType":"CustomCategory","iotId":"xxx","requestId":"1614065952794","checkFailedData":{},"productKey":"xxx","gmtCreate":1614065819600,"deviceName":"xxx","items":{"Temperature":{"value":11,"time":1614065819597},"Humidity":{"value":28,"time":1614065819597}}} MESSAGE qos:1 destination:/xxx/xxx2/thing/event/property/post -
Failure: A log message similar to the following is returned, indicating that the AMQP client failed to connect to the IoT Platform.
Use the error log to check your code and network settings. Resolve the issue and run the code again.
xxx>php newfile.php PHP Fatal error: Uncaught Stomp\Exception\ConnectionException: Failed to connect. (0: php_network_getaddresses: getaddrinfo failed: □) Fatal error: Uncaught Stomp\Exception\ConnectionException: Failed to connect. (0: php_network_getaddresses: getaddrinfo failed: □) (Host: xxx.un cs.com) in xxx\stomp-php\stomp-php\src\Network\Connection.php:417 Stack trace: #0 xxx\stomp-php\stomp-php\src\Network\Connection.php(353): Stomp\Network\Connection->connectSocket(Array) #1 xxx\stomp-php\stomp-php\src\Network\Connection.php(327): Stomp\Network\Connection->getConnection() #2 xxx\stomp-php\stomp-php\src\Client.php(207): Stomp\Network\Connection->connect() #3 xxx.php(45): Stomp\Client->connect() #4 xxx.php(56): start_consume() #5 {main} Next Stomp\Exception\ConnectionException: Could not connect to a broker (Host: xxx) in xxx\stomp -php\src\Network\Connection.php:358 Stack t in xxx\vendor\stomp-php\stomp-php\src\Network\Connection.php on line 358
Binary message body
To transmit binary data, use a Base64 encoding parameter because STOMP is a text-based protocol. Without encoding, message bodies may be truncated.
Add the encode=base64 parameter to userName as shown below. The server then Base64-encodes the message body before sending it.
$userName = $clientId . "|authMode=aksign"
. ",signMethod=" . $signMethod
. ",timestamp=" . $timeStamp
. ",authId=" . $accessKey
. ",iotInstanceId=" . $iotInstanceId
. ",consumerGroupId=" . $consumerGroupId
. ",encode=base64" . "|";
References
For more information about error codes for server-side subscription messages, see Message-related error codes.