All Products
Search
Document Center

Alibaba Cloud SDK:Integrate Alibaba Cloud Darabonba SDK for PHP

Last Updated:Jun 19, 2024

The process of integrating Alibaba Cloud Darabonba SDK consists of three steps: configure a credential, import the SDK to your project, and write the code for calling API operations. This topic describes how to integrate Alibaba Cloud Darabonba SDK. In this example, Alibaba Cloud Darabonba SDK for PHP is used to call the SendSms operation of Short Message Service (SMS) to send a text message.

Prerequisites

  • PHP 5.6 or later is installed.

  • Composer is installed globally. For more information, see Globally.

Important

The version of PHP used to install Alibaba Cloud Darabonba SDK by using Composer must be earlier than or equal to the version of PHP used to run Alibaba Cloud Darabonba SDK. For example, the vendor folder generated after Alibaba Cloud Darabonba SDK is installed in PHP 7.2 can be used only in PHP 7.2 or later. If the vendor folder is copied to PHP 5.6, the dependency is incompatible with PHP 5.6. If you fail to install Composer due to network issues, you can run the following command to use the full image of Composer provided by Alibaba Cloud:

composer config -g repo.packagist composer https://mirrors.aliyun.com/composer/

An AccessKey pair is required if you use Alibaba Cloud Darabonba SDK to call API operations. For more information, see Credential. To prevent AccessKey pair leaks, you can record the AccessKey pair in environment variables. For information about other security solutions, see Credential security solutions. In this example, the ALIBABA_CLOUD_ACCESS_KEY_ID and ALIBABA_CLOUD_ACCESS_KEY_SECRET environment variables are configured.

  • Linux and macOS

    1. Create the .bash_profile file.

      Note

      If you configure environment variables for the first time, you can run the touch ~/.bash_profile command to create the configuration file. If the configuration file already exists, run the vim ~/.bash_profile command to edit the configuration file.

      touch ~/.bash_profile
      vim ~/.bash_profile
    2. Configure the .bash_profile file.

      # Replace <ACCESS_KEY_ID> and <ACCESS_KEY_SECRET> in the following commands with your AccessKey ID and AccessKey secret. 
      # Replace the variable names based on your business requirements, such as OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET. 
      export ALIBABA_CLOUD_ACCESS_KEY_ID=<ACCESS_KEY_ID>
      export ALIBABA_CLOUD_ACCESS_KEY_SECRET=<ACCESS_KEY_SECRET>

      Save the file after the configuration.

    3. Use the .bash_profile file.

      # Run the following command in the configuration file.
      source ~/.bash_profile
      # Check whether the configuration takes effect.
      echo $ALIBABA_CLOUD_ACCESS_KEY_ID

      If the valid AccessKey ID is returned, the configuration is successful.

  • Windows

    In this example, the ALIBABA_CLOUD_ACCESS_KEY_ID and ALIBABA_CLOUD_ACCESS_KEY_SECRET environment variables are configured.

    Use GUI

    • Procedure

      If you want to use GUI to configure environment variables in Windows 10, perform the following steps:

      On the Windows desktop, right-click This PC and select Properties. On the page that appears, click Advanced system settings. In the System Properties dialog box, click Environment Variables on the Advanced tab. In the Environment Variables dialog box, click New in the User variables or System variables section. Then, configure the variables described in the following table.

      Variable

      Example

      AccessKey ID

      • Variable name: ALIBABA_CLOUD_ACCESS_KEY_ID

      • Variable value: LTAI4GDty8ab9W4Y1D****

      AccessKey Secret

      • Variable name: ALIBABA_CLOUD_ACCESS_KEY_SECRET

      • Variable value: IrVTNZNy5yQelTETg0cZML3TQn****

    • Check whether the configuration is successful.

      On the Windows desktop, click Start or press Win + R. In the Run dialog box, enter cmd. Then, click OK or press the Enter key. On the page that appears, run the echo %ALIBABA_CLOUD_ACCESS_KEY_ID% and echo %ALIBABA_CLOUD_ACCESS_KEY_SECRET% commands. If the valid AccessKey pair is returned, the configuration is successful.

    Use CMD

    • Procedure

      Open a Command Prompt window as an administrator and run the following commands to add environment variables in the operating system:

      setx ALIBABA_CLOUD_ACCESS_KEY_ID LTAI4GDty8ab9W4Y1D**** /M
      setx ALIBABA_CLOUD_ACCESS_KEY_SECRET IrVTNZNy5yQelTETg0cZML3TQn**** /M

      /M indicates that the environment variable is of system level. You cannot use this parameter when you configure a user-level environment variable.

    • Check whether the configuration is successful.

      On the Windows desktop, click Start or press Win + R. In the Run dialog box, enter cmd. Then, click OK or press the Enter key. On the page that appears, run the echo %ALIBABA_CLOUD_ACCESS_KEY_ID% and echo %ALIBABA_CLOUD_ACCESS_KEY_SECRET% commands. If the valid AccessKey pair is returned, the configuration is successful.

    Use Windows PowerShell

    In PowerShell, configure new environment variables. The environment variables apply to all new sessions.

    [System.Environment]::SetEnvironmentVariable('ALIBABA_CLOUD_ACCESS_KEY_ID', 'LTAI4GDty8ab9W4Y1D****', [System.EnvironmentVariableTarget]::User)
    [System.Environment]::SetEnvironmentVariable('ALIBABA_CLOUD_ACCESS_KEY_SECRET', 'IrVTNZNy5yQelTETg0cZML3TQn****', [System.EnvironmentVariableTarget]::User)

    Configure environment variables for all users. You must run the following commands as a administrator.

    [System.Environment]::SetEnvironmentVariable('ALIBABA_CLOUD_ACCESS_KEY_ID', 'LTAI4GDty8ab9W4Y1D****', [System.EnvironmentVariableTarget]::Machine)
    [System.Environment]::SetEnvironmentVariable('ALIBABA_CLOUD_ACCESS_KEY_SECRET', 'IrVTNZNy5yQelTETg0cZML3TQn****', [System.EnvironmentVariableTarget]::Machine)

    Configure temporary environment variables. The environment variables apply only to the current session.

    $env:ALIBABA_CLOUD_ACCESS_KEY_ID = "LTAI4GDty8ab9W4Y1D****"
    $env:ALIBABA_CLOUD_ACCESS_KEY_SECRET = "IrVTNZNy5yQelTETg0cZML3TQn****"

    In PowerShell, run the Get-ChildItem env:ALIBABA_CLOUD_ACCESS_KEY_ID and Get-ChildItem env:ALIBABA_CLOUD_ACCESS_KEY_SECRET commands. If the valid AccessKey pair is returned, the configuration is successful.

Step 2: Import the SDK to your project

Alibaba Cloud Darabonba SDK allows you to make generic and specialized calls. For more information, see Generic calls and specialized calls. The SDK that you need to import varies based on the call type.

Specialized calls

You can visit OpenAPI Explorer, find the service that you want to use, and view the supported languages and installation methods. Then, import the SDK of the service to your project. In this example, SMS SDK is imported. Perform the following steps:

  1. Visit the SMS SDK page.

  2. In the All languages section, select the language that you want to use.

  3. In the Installation Method section, select an installation method and copy the installation code.

  4. Add the dependency to your project.

Run the following command to install SMS SDK for PHP:

composer require alibabacloud/dysmsapi-20170525 2.0.23

Generic calls

You do not need to install the SDK of a service to make generic calls. You need to only import the Darabonba\OpenApi core package. For information about the latest version of the core package, see alibabacloud/darabonba-openapi. Run the following command to install the core package:

composer require alibabacloud/darabonba-openapi

Step 3: Call an API operation

Download the sample code. For more information, see Get started with Alibaba Cloud Darabonba SDK for PHP. In this example, the sample code of a specialized call is used. If you want to make a generic call, turn on Common Request when you download the sample code. For more information, see Generic calls and specialized calls.

Initialize a request client

Method 1: Use an AccessKey pair

<?php
use Darabonba\OpenApi\Models\Config;
use AlibabaCloud\SDK\Dysmsapi\V20170525\Dysmsapi as DysmsAPI;

public static function createClient(){
	$config = new Config([
		// Required. Specify your AccessKey ID.
		"accessKeyId" => getenv('ALIBABA_CLOUD_ACCESS_KEY_ID'),
		// Required. Specify your AccessKey secret.
		"accessKeySecret" => getenv('ALIBABA_CLOUD_ACCESS_KEY_SECRET')
	]);
	// Specify the endpoint. For more information, visit https://api.aliyun.com/product/Dysmsapi.
	$config->endpoint = "dysmsapi.aliyuncs.com";
	// Initialize a request client for a specialized call.
	$dysmsApiClient = new DysmsAPI($config);
}

Method 2: Use an STS token

<?php
use Darabonba\OpenApi\Models\Config;
use AlibabaCloud\SDK\Dysmsapi\V20170525\Dysmsapi as DysmsAPI;

public static function createClient(){
	$config = new Config([
		// Required. Specify your AccessKey ID.
		"accessKeyId" => getenv('ALIBABA_CLOUD_ACCESS_KEY_ID'),
		// Required. Specify your AccessKey secret.
		"accessKeySecret" => getenv('ALIBABA_CLOUD_ACCESS_KEY_SECRET'),
		// Required. Specify your Security Token Service (STS) token.
		"securityToken" => getenv('ALIBABA_CLOUD_SECURITY_TOKEN')
	]);
	// Specify the endpoint. For more information, visit https://api.aliyun.com/product/Dysmsapi.
	$config->endpoint = "dysmsapi.aliyuncs.com";
	// Initialize a request client for a specialized call.
	$dysmsApiClient = new DysmsAPI($config);
}

Method 3: Use the Credentials tool

<?php

use Darabonba\OpenApi\Models\Config;
use AlibabaCloud\Credentials\Credential;
use AlibabaCloud\SDK\Dysmsapi\V20170525\Dysmsapi as DysmsAPI;

// Use the default credential to initialize a Credentials client. 
$credential = new Credential([]);
$config = new Config([
	// Use the SDK Credentials package to configure a credential.
	'credential'        => $credential,
]);
// To call the SMS API, initialize the Client class of the SDK package for SMS.
$config->endpoint = 'dysmsapi.aliyuncs.com';
// Initialize the Client class of the SDK package for SMS.
$dysmsApiClient = new DysmsAPI($config);

Create a request object or a runtime configuration object

In most cases, you can create a request object and specify the parameters based on your business requirements. You can also customize runtime configurations.

// Create a request object and specify the parameters.
$sendSmsRequest = new SendSmsRequest([
"phoneNumbers" => "<YOUR_VALUE>",
"signName" => "<YOUR_VALUE>"
]);
// Create a runtime configuration object.
$runtime = new RuntimeOptions([]);

Initiate a request

In the Darabonba SDK, the client of each Alibaba Cloud service provides three request methods for all API operations of the service. You can specify a request method for an API operation. The name of the request method is the name of the API operation with the first letter in lowercase. The following list describes the request methods:

  • <API operation name>: uses the default runtime configurations to initiate a request. You do not need to specify runtime parameters.

    <?php
    
    use AlibabaCloud\SDK\Dysmsapi\V20170525\Dysmsapi;
    use AlibabaCloud\SDK\Dysmsapi\V20170525\Models\SendSmsRequest;
    use Darabonba\OpenApi\Models\Config;
    use AlibabaCloud\Credentials\Credential;
    
    // Enable autoloading for Composer by using the vendor/autoload.php file.
    require_once('../vendor/autoload.php');
    
    // Use the default credential to initialize a Credentials client. 
    $credentialClient = new Credential([]);
    $smsConfig = new Config([
        // Use the SDK Credentials package to configure a credential.
        'credential' => $credentialClient,
        // Specify the endpoint of the cloud service.
        'endpoint' => 'ecs.aliyuncs.com'
    ]);
    $smsClient = new Dysmsapi($smsConfig);
    // Construct the request object.
    $sendSmsRequest = new SendSmsRequest([]);
    // Obtain the response object.
    $response = $smsClient->sendSms($sendSmsRequest);
    var_dump($response);
  • <API operation name>WithOptions: uses the custom runtime configurations to initiate a request. For more information, see Advanced configuration.

    <?php
    
    use AlibabaCloud\SDK\Dysmsapi\V20170525\Dysmsapi;
    use AlibabaCloud\SDK\Dysmsapi\V20170525\Models\SendSmsRequest;
    use AlibabaCloud\Tea\Utils\Utils\RuntimeOptions;
    use Darabonba\OpenApi\Models\Config;
    use AlibabaCloud\Credentials\Credential;
    
    // Enable autoloading for Composer by using the vendor/autoload.php file.
    require_once('../vendor/autoload.php');
    
    // Use the default credential to initialize a Credentials client. 
    $credentialClient = new Credential([]);
    $smsConfig = new Config([
        // Use the SDK Credentials package to configure a credential.
        'credential' => $credentialClient,
        // Specify the endpoint of the cloud service.
        'endpoint' => 'ecs.aliyuncs.com'
    ]);
    $smsClient = new Dysmsapi($smsConfig);
    // Construct the request object.
    $sendSmsRequest = new SendSmsRequest([]);
    $runtime = new RuntimeOptions();
    // Specify whether to automatically retry a request.
    $runtime->autoretry = true;
    // Set the timeout period for connection requests.
    $runtime->connectTimeout = 10000;
    // Set the timeout period for read requests.
    $runtime->readTimeout    = 10000;
    // Obtain the response object.
    $response = $smsClient->sendSmsWithOptions($sendSmsRequest,$runtime);
    var_dump($response);
  • <API operation name>Advance: used for API operations that require file uploading. By default, you must specify runtime parameters. The following sample code provides an example on how to initiate a request to upload a file and call an API operation to use the human face and body recognition feature of Visual Intelligence API (VIAPI):

    <?php
    
    use Darabonba\OpenApi\Models\Config;
    use GuzzleHttp\Psr7\Stream;
    use AlibabaCloud\Credentials\Credential;
    use AlibabaCloud\Tea\Utils\Utils\RuntimeOptions;
    use AlibabaCloud\Tea\Exception\TeaError;
    use AlibabaCloud\SDK\Facebody\V20191230\Facebody;
    use AlibabaCloud\SDK\Facebody\V20191230\Models\DetectBodyCountAdvanceRequest;
    
    // Enable autoloading for Composer by using the vendor/autoload.php file.
    require_once('../vendor/autoload.php');
    
    $credentialClient = new Credential([]);
    $facebodyConfig = new Config([
        // Use the SDK Credentials package to configure a credential.
        'credential' => $credentialClient,
        // Specify the endpoint of the cloud service.
        'endpoint' => 'facebody.cn-shanghai.aliyuncs.com'
    ]);
    
    $request = new DetectBodyCountAdvanceRequest();
    // Read the file and configure the file stream for the SDK request object.
    $request->imageURLObject = new Stream(fopen("<filepath>", "rb"));
    
    $runtime = new RuntimeOptions();
    $facebodyClient = new Facebody($facebodyConfig);
    
    try {
        // Upload the file by using the method for uploading local files.
        $response = $facebodyClient->detectBodyCountAdvance($request, $runtime);
        var_dump($response);
    } catch (TeaError $e) {
        var_dump($e->getMessage());
        var_dump($e->getErrorInfo());
        var_dump($e->getLastException());
        var_dump($e->getLastRequest());
    }