All Products
Search
Document Center

IoT Platform:Use IoT Platform SDK for PHP

Last Updated:Oct 22, 2023

IoT Platform provides an SDK for PHP. This topic describes how to install and configure IoT Platform SDK for PHP. This topic also provides sample code on how to use the SDK to call API operations of IoT Platform.

The upgraded IoT Platform SDK for PHP allows you to make API requests by installing only IoT Platform SDK instead of depending on the core library. The upgraded SDK can be used to process parameters, assemble requests in the specified formats, and process return values. For more information about the upgraded SDK and the original SDK, visit SDK information center.

Install the SDK

  1. Install a PHP development environment. You must install PHP 5.6 or later.

    Download a PHP installation package from the official PHP website and install PHP.

  2. Install Composer.

    We recommend that you use Composer to manage IoT Platform SDK for PHP. In this case, you must install Composer.

    • For Windows machines, you can download the Composer-Setup.exe program from the getcomposer.org website to install Composer.

    • You can also run the following curl command to install Composer:

      curl -sS https://getcomposer.org/installer | php
      Note

      If the installation fails due to network exceptions, you can use the full image of Alibaba Cloud Composer.

  3. Install Alibaba Cloud SDK for PHP.

    If Composer has been installed for global access in your system, run the following command directly in the project directory to install Alibaba Cloud SDK for PHP as a dependency. For more information about how to install Composer for global access, see Globally.

    composer require alibabacloud/darabonba-openapi
    Important

    The PHP version used to install the SDK must be equal to or lower than the actual version of PHP used to run the SDK.

    For example, if you use PHP 7.2 to install the SDK and generate the vendor directory, you must use the SDK in PHP 7.2 or later. If you use the SDK in PHP 5.6, a compatibility issue occurs.

  4. Add the following dependency to install IoT Platform SDK for PHP:

    composer require alibabacloud/iot-20180120

    The name of the upgraded SDK is in the format of alibabacloud/${Service name}-${API version number}. For more information about the SDK for PHP and user guide, visit alibabacloud-php-sdk/iot- 20180120/.

Initialize the SDK

  1. Create a $config object to store SDK initialization information, such as the AccessKey ID, AccessKey secret, and region ID.

  2. Create a $client instance. Call the Iot($iClientProfile) method to load the SDK initialization information.

For example, if you want to use the SDK in the China (Shanghai) region, you can use the following code to initialize the SDK. In the production environment, you must select the region where IoT Platform is activated.

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 region ID. 
$config->regionId = "cn-shanghai";
$client = new Iot($config);

Parameter

Description

accessKeyId

The AccessKey ID of your Alibaba Cloud account.

You can go to the AccessKey Pair page in the Alibaba Cloud Management Console to create or view your AccessKey pairs.

accessKeySecret

The AccessKey secret of your Alibaba Cloud account.

regionId

The ID of the region where your IoT Platform instance resides. The region ID is used in the endpoint for service access. The endpoint is in the iot.${RegionId}.aliyuncs.com format.

You can view the region in the upper-left corner of the IoT Platform console.

For more information about the formats of region IDs, see Supported regions.

Initiate a request

The SDK encapsulates a class for each API operation. The class name is in the ${API name}+"Request" format. You can use the class to initiate API requests.

Procedure

  1. Initialize the SDK. For more information, see the Initialize the SDK section of this topic.

  2. Create an API request by generating a $request instance of the ${API operation name}+"Request" class.

  3. Call the "set"+${Request parameter} method of the $request instance to specify the request parameters.

  4. Call the ${API operation name}($request) method of the $client instance to obtain the response.

For more information about the API operations of IoT Platform, see List of operations by function. For more information about the request parameters and response parameters of each API operation, see the API reference.

The following example shows how to call the Pub operation to publish a message to a topic. For more information about request parameters, see Pub.

Important

In the following sample code, ${iotInstanceId} specifies the ID of an instance. You can view the ID of the instance on the Overview page in the IoT Platform console.

  • If your instance has an ID, you must specify the ID for this parameter. Otherwise, the call fails.

  • If no Overview page or ID is generated for your instance, you do not need to configure this parameter. You must delete the request code that is related to the IotInstanceId parameter or specify an empty string ("") for the parameter. Otherwise, the call fails.

For more information about IoT Platform instances, see Overview. For more information about how to purchase an instance, see Purchase Enterprise Edition instances. For more information, see FAQ about IoT Platform instances.

$request = new PubRequest([
  // The ID of the IoT Platform instance. 
  "iotInstanceId" => "${iotInstanceId}",
  // The ProductKey of the product. 
  "productKey" => "${productKey}",
  // The content of the message that you want to send. Encode "hello world" in Base64 as a string. 
  "messageContent" => "eyJ0ZXN0IjoidGFzayBwdWIgYnJvYWRjYXN0In0=",
  // The custom topic that is used to publish the message. 
  "topicFullName" => "/${productKey}/${deviceName}/user/get",
  // The message sending mode. IoT Platform SDK supports QoS 0 and QoS 1. 
  "qos" => 0
]);
// Call the Pub operation. 
$response = $client->pub($request);
print_r($response);

Sample code

Note

You can replace the values of the preceding parameters with actual values based on your business scenario.

<?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 your 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 region ID. 
    $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 content of the message that you want to send. Encode "hello world" in Base64 as a string. 
                "messageContent" => "eyJ0ZXN0IjoidGFzayBwdWIgYnJvYWRjYXN0In0=",
                // The custom topic that is used to publish the message. 
                "topicFullName" => "/${productKey}/${deviceName}/user/get",
                // The message sending mode. IoT Platform SDK supports QoS 0 and QoS 1. 
                "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 view or download the sample code of API operations in IoT Platform SDK Sample Center. Sample code of SDKs for Java, Python, PHP, Node.js, Go, C++, and .NET is provided.

Alibaba Cloud OpenAPI Explorer provides online debugging tools for API operations. On the API Debugging page, you can search for API operations, call API operations, and generate sample code for API operations of different SDKs. On the right side of the page, you can view the sample code of an SDK on the Sample Code tab. On the Debugging Result tab, you can view the actual request URL and response in the JSON format.