PHP SDK usage guide
IoT Platform provides a cloud SDK for PHP to call cloud APIs. Learn how to install, configure, and use the SDK.
The upgraded IoT Platform cloud SDK for PHP handles request parameters, request format assembly, and return value processing without depending on the SDK Core. For more information about the upgraded and original SDKs, see SDK Information Center.
Install the SDK
-
Install the PHP development environment. PHP 5.6 or a later version is required.
You can go to the official PHP website to download and install the PHP package.
-
Install Composer.
We recommend that you use Composer to manage the IoT PHP SDK. You must install Composer on your system.
-
If you use Windows, go to getcomposer.org and install Composer-Setup.exe.
-
Install Composer using the cURL command.
curl -sS https://getcomposer.org/installer | phpNoteIf the installation fails because of network issues, you can use the Alibaba Cloud Composer full mirror.
-
-
Install the OpenAPI SDK core library.
If you installed Composer globally, you can run the following command in your project folder to install the Alibaba Cloud SDK for PHP as a dependency. For more information, see Globally.
composer require alibabacloud/darabonba-openapiImportantThe PHP version that you use to run this command must be the same as or earlier than the PHP version of your runtime environment.
For example, if you install the SDK in a PHP 7.2 environment, the generated `vendor` folder can be used only with PHP 7.2 or later. If you try to use it in a PHP 5.6 environment, dependency version conflicts will occur.
-
Add the following dependency to install the IoT PHP SDK.
composer require alibabacloud/iot-20180120The upgraded SDKs are named in the format alibabacloud/${ProductName}-${APIVersion}. For more information and usage instructions for the PHP SDK, see alibabacloud-php-sdk/iot-20180120/.
Initialize the SDK
-
Create the $config object to store SDK initialization information, such as the AccessKey ID, AccessKey secret, and region ID.
-
Create an instance of the Iot object named $client. Call the
Iot($iClientProfile)method to load the SDK information and initialize the SDK client.
The following code provides an example of how to initialize the SDK for the China (Shanghai) region. In your actual scenario, replace the endpoint with the one for the region where your IoT Platform service is located.
use AlibabaCloud\SDK\Iot\V20180120\Iot;
use AlibabaCloud\Tea\Config;
$config = new Config([]);
// Your AccessKey ID.
$config->accessKeyId = getenv('ACCESS_KEY_ID');
// Your AccessKey secret.
$config->accessKeySecret = getenv('ACCESS_KEY_SECRET');
// The ID of your region.
$config->regionId = "cn-shanghai";
$client = new Iot($config);
|
Parameter |
Description |
|
accessKeyId |
The AccessKey ID for your Alibaba Cloud account. Create or view your AccessKey on the AccessKey Management page in the Alibaba Cloud console. |
|
accessKeySecret |
The AccessKey secret for your Alibaba Cloud account. |
|
regionId |
The region ID of your IoT Platform service. This is used to construct the service endpoint in the format: iot.${RegionId}.aliyuncs.com. You can view the current service region in the upper-left corner of the IoT Platform console. For more information about how to specify a region ID, see Regions and zones. |
For more information about how to configure HTTP requests, proxies, timeouts, and retries for the SDK client, see V2.0 PHP SDK (Recommended).
Make a call
The IoT Platform cloud SDK encapsulates each API in a ${API_Name}Request class.
Steps
-
Initialize the SDK client. For more information, see Initialize the SDK.
-
Create a request for the API call. This generates an instance of the
${APIName}Requestclass named $request. -
Use the $request object instance and the set${RequestParameterName} method to set the required request parameters.
-
Use the initialized SDK client instance $client to call the ${APIName}($request) method. The method returns the result of the API call.
For more information about IoT Platform cloud APIs, see API list. For descriptions of the request parameters in the request and the response parameters in the response, see the documentation for the specific API.
This topic uses the Pub API as an example to show how to publish a message to a topic. For information about request parameters, see Pub.
In the following code, iotInstanceId is the instance ID. For more information about instances, see Instance overview.
For information about how to purchase an instance, see Purchase an Enterprise instance.
For information about how to obtain an instance ID, see IoT Platform instance-related FAQ.
$request = new PubRequest([
// The ID of the IoT Platform instance.
"iotInstanceId" => "${iotInstanceId}",
// The ProductKey of the product.
"productKey" => "${productKey}",
// The message body to send, which must be a Base64-encoded string.
"messageContent" => "eyJ0ZXN0IjoidGFzayBwdWIgYnJvYWRjYXN0In0=",
// The custom topic of the device that will receive the message.
"topicFullName" => "/${productKey}/${deviceName}/user/get",
// The method to send the message. QoS 0 and QoS 1 are supported.
"qos" => 0
]);
// Call the Pub API.
$response = $client->pub($request);
print_r($response);
Complete code sample
In your actual scenario, replace the parameter values based on the parameter descriptions provided earlier in this topic.
<?php
namespace AlibabaCloud\SDK\Sample;
use AlibabaCloud\SDK\Iot\V20180120\Iot;
use AlibabaCloud\Tea\Tea;
use AlibabaCloud\Tea\Utils\Utils;
use AlibabaCloud\Tea\Console\Console;
use \Exception;
use AlibabaCloud\Tea\Exception\TeaError;
use Darabonba\OpenApi\Models\Config;
use AlibabaCloud\SDK\Iot\V20180120\Models\PubRequest;
class Sample {
/**
* Use an AccessKey ID and AccessKey secret to initialize the client.
*/
public static function createClient() {
$config = new Config([]);
// Your AccessKey ID.
$config->accessKeyId = getenv('ACCESS_KEY_ID');
// Your AccessKey secret.
$config->accessKeySecret = getenv('ACCESS_KEY_SECRET');
// The ID of your region.
$config->regionId = "cn-shanghai";
return new Iot($config);
}
}
/**
* @param string[] $args
* @return void
*/
public static function main($args){
try {
$client = self::createClient("${accessKey}", "${accessKeySecret}");
$request = new PubRequest([
// The ID of the IoT Platform instance.
"iotInstanceId" => "${iotInstanceId}",
// The ProductKey of the product.
"productKey" => "${productKey}",
// The message body to send, which must be a Base64-encoded string.
"messageContent" => "eyJ0ZXN0IjoidGFzayBwdWIgYnJvYWRjYXN0In0=",
// The custom topic of the device that will receive the message.
"topicFullName" => "/${productKey}/${deviceName}/user/get",
// The method to send the message. QoS 0 and QoS 1 are supported.
"qos" => 0
]);
$response = $client->pub($request);
Console::log(Utils::toJSONString(Tea::merge($response)));
}
catch (Exception $error) {
if (!($error instanceof TeaError)) {
$error = new TeaError([], $error->getMessage(), $error->getCode(), $error);
}
Console::log($error->message);
}
}
}
$path = __DIR__ . \DIRECTORY_SEPARATOR . '..' . \DIRECTORY_SEPARATOR . 'vendor' . \DIRECTORY_SEPARATOR . 'autoload.php';
if (file_exists($path)) {
require_once $path;
}
Sample::main(array_slice($argv, 1));
Appendix: Sample code
You can go to the IoT Platform Cloud SDK Example Center to view or download sample code for API calls. The sample code includes examples for SDKs in languages such as Java, Python, PHP, Node.js, Go, C++, and .NET.
The Alibaba Cloud OpenAPI Developer Portal provides an online API debugging tool. On the API debugging page, you can quickly search for and test API calls. The system automatically generates sample SDK code for different languages based on the parameters that you enter. The sample code is displayed on the SDK Example tab on the right side of the page. On the Call Result tab, you can view the request URL and the response in JSON format.