To integrate Alibaba Cloud SDK, you must perform the following steps: install Alibaba Cloud SDK, configure an access credential, and write code for calling API operations. This topic describes how to integrate Alibaba Cloud SDK V2.0. In this example, Alibaba Cloud SDK V2.0 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 globally installed. For more information, see the "Globally" section of the Getting Started topic.
The version of PHP used to install Alibaba Cloud SDK V2.0 by using Composer must be earlier than or equal to the version of PHP used to run Alibaba Cloud SDK V2.0. For example, the vendor folder generated after Alibaba Cloud SDK V2.0 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/
1. Install the SDK for PHP
Log on to SDK Center and select the service whose SDK you want to use. In this example, Short Message Service (SMS) is selected.
On the Short Message Service page, select PHP in the All languages section. On the Quick Start tab, obtain the installation method of Short Message Service (SMS) SDK.
2. Configure an access credential
To call API operations of an Alibaba Cloud service, you must configure an access credential, such as an AccessKey pair
or a Security Token Service (STS) token
. For more information, see Credential. To prevent AccessKey pair leaks, you can record the AccessKey pair in environment variables. For more 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.
Configure environment variables in Linux and macOS
Configure environment variables by using the export command
The temporary environment variables configured by using the export command are valid only for the current session. After you exit the session, the configured environment variables become invalid. To configure permanent environment variables, you can add the export command to the startup configuration file of the corresponding operating system.
Configure the AccessKey ID and press Enter.
# Replace <ACCESS_KEY_ID> with your AccessKey ID. export ALIBABA_CLOUD_ACCESS_KEY_ID=<ACCESS_KEY_ID>
Configure the AccessKey secret and press Enter.
# Replace <ACCESS_KEY_SECRET> with your AccessKey secret. export ALIBABA_CLOUD_ACCESS_KEY_SECRET=<ACCESS_KEY_SECRET>
Check whether the configuration is successful.
Run the
echo $ALIBABA_CLOUD_ACCESS_KEY_ID
command. If the valid AccessKey ID is returned, the environment variables are configured.
Configure environment variables in Windows
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 Enter. On the page that appears, run the
echo %ALIBABA_CLOUD_ACCESS_KEY_ID%
andecho %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 can choose not to 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 Enter. On the page that appears, run the
echo %ALIBABA_CLOUD_ACCESS_KEY_ID%
andecho %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 an 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.
3. Call an API operation
3.1 Initialize a request client
You can use multiple methods to initialize a request client. For more information, see Manage access credentials. In this example, an AccessKey pair is used to initialize a request client.
<?php
namespace AlibabaCloud\SDK\Sample;
use AlibabaCloud\SDK\Dysmsapi\V20170525\Dysmsapi;
use Darabonba\OpenApi\Models\Config;
class Sample {
/**
* Use your AccessKey ID and AccessKey secret to initialize a client.
* @return Dysmsapi Client
*/
public static function createClient(){
$config = new Config([
// Required. Make sure that the ALIBABA_CLOUD_ACCESS_KEY_ID environment variable is configured in the code runtime environment.
"accessKeyId" => getenv("ALIBABA_CLOUD_ACCESS_KEY_ID"),
// Required. Make sure that the ALIBABA_CLOUD_ACCESS_KEY_SECRET environment variable is configured in the code runtime environment.
"accessKeySecret" => getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET")
]);
$config->endpoint = "dysmsapi.aliyuncs.com";
return new Dysmsapi($config);
}
}
3.2 Create a request object and configure runtime configurations
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 parameters.
$sendSmsRequest = new SendSmsRequest([
"signName" => "<YOUR_VALUE>",
"templateCode" => "<YOUR_VALUE>",
"phoneNumbers" => "<YOUR_VALUE>",
]);
// Create a runtime configuration object.
$runtime = new RuntimeOptions([]);
3.3 Initiate an API request
In Alibaba Cloud SDK V2.0, the client of each Alibaba Cloud service contains all the API operations provided by the service. In addition, Alibaba Cloud SDK V2.0 provides three methods to define each API operation. This design aims to improve the flexibility and efficiency of development, and ensure that developers can call API operations in an optimal way based on their project requirements.
The name of the API operation is in lowercase letters.
<API operation>
: uses the default runtime configurations to initiate a request. You do not need to specify runtime parameters.<?php namespace AlibabaCloud\SDK\Sample; use AlibabaCloud\SDK\Dysmsapi\V20170525\Dysmsapi; use \Exception; use AlibabaCloud\Tea\Exception\TeaError; use AlibabaCloud\Tea\Utils\Utils; use Darabonba\OpenApi\Models\Config; use AlibabaCloud\SDK\Dysmsapi\V20170525\Models\SendSmsRequest; class Sample { /** * Use your AccessKey ID and AccessKey secret to initialize a client. * @return Dysmsapi Client */ public static function createClient(){ $config = new Config([ // Required. Make sure that the ALIBABA_CLOUD_ACCESS_KEY_ID environment variable is configured in the code runtime environment. "accessKeyId" => getenv("ALIBABA_CLOUD_ACCESS_KEY_ID"), // Required. Make sure that the ALIBABA_CLOUD_ACCESS_KEY_SECRET environment variable is configured in the code runtime environment. "accessKeySecret" => getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET") ]); $config->endpoint = "dysmsapi.aliyuncs.com"; return new Dysmsapi($config); } /** * @param string[] $args * @return void */ public static function main($args){ $client = self::createClient(); // Create a request object and specify parameters. $sendSmsRequest = new SendSmsRequest([ "signName" => "<YOUR_VALUE>", "templateCode" => "<YOUR_VALUE>", "phoneNumbers" => "<YOUR_VALUE>", ]); try { // Write your own code to display the response of the API operation if necessary. $client->sendSms($sendSmsRequest); } catch (Exception $error) { if (!($error instanceof TeaError)) { $error = new TeaError([], $error->getMessage(), $error->getCode(), $error); } // Handle exceptions with caution in actual business scenarios and never ignore exceptions in your project. In this example, error messages are displayed for reference only. // The error message. var_dump($error->message); // The information for troubleshooting. var_dump($error->data["Recommend"]); Utils::assertAsString($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));
<API operation>WithOptions
: uses the custom runtime configurations to initiate a request. For more information, see Advanced configuration.<?php namespace AlibabaCloud\SDK\Sample; use AlibabaCloud\SDK\Dysmsapi\V20170525\Dysmsapi; use \Exception; use AlibabaCloud\Tea\Exception\TeaError; use AlibabaCloud\Tea\Utils\Utils; use Darabonba\OpenApi\Models\Config; use AlibabaCloud\SDK\Dysmsapi\V20170525\Models\SendSmsRequest; use AlibabaCloud\Tea\Utils\Utils\RuntimeOptions; class Sample { /** * Use your AccessKey ID and AccessKey secret to initialize a client. * @return Dysmsapi Client */ public static function createClient(){ $config = new Config([ // Required. Make sure that the ALIBABA_CLOUD_ACCESS_KEY_ID environment variable is configured in the code runtime environment. "accessKeyId" => getenv("ALIBABA_CLOUD_ACCESS_KEY_ID"), // Required. Make sure that the ALIBABA_CLOUD_ACCESS_KEY_SECRET environment variable is configured in the code runtime environment. "accessKeySecret" => getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET") ]); $config->endpoint = "dysmsapi.aliyuncs.com"; return new Dysmsapi($config); } /** * @param string[] $args * @return void */ public static function main($args){ $client = self::createClient(); // Create a request object and specify parameters. $sendSmsRequest = new SendSmsRequest([ "signName" => "<YOUR_VALUE>", "templateCode" => "<YOUR_VALUE>", "phoneNumbers" => "<YOUR_VALUE>", ]); // Create a runtime configuration object. $runtime = new RuntimeOptions([]); try { // Write your own code to display the response of the API operation if necessary. $client->sendSmsWithOptions($sendSmsRequest, $runtime); } catch (Exception $error) { if (!($error instanceof TeaError)) { $error = new TeaError([], $error->getMessage(), $error->getCode(), $error); } // Handle exceptions with caution in actual business scenarios and never ignore exceptions in your project. In this example, error messages are displayed for reference only. // The error message. var_dump($error->message); // The information for troubleshooting. var_dump($error->data["Recommend"]); Utils::assertAsString($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));
<API operation>Advance
: used for API operations that require file uploading. By default, you must specify runtime parameters. The following sample code shows how to initiate a request to upload a file and call an API operation to usethe human face and body recognition feature of Vision Intelligent API (VIAPI)
.composer require alibabacloud/facebody-20191230 4.1.2
<?php namespace AlibabaCloud\SDK\Sample; use AlibabaCloud\SDK\Facebody\V20191230\Facebody; use \Exception; use AlibabaCloud\Tea\Exception\TeaError; use AlibabaCloud\Tea\Utils\Utils; use Darabonba\OpenApi\Models\Config; use AlibabaCloud\SDK\Facebody\V20191230\Models\DetectBodyCountRequest; use AlibabaCloud\Tea\Utils\Utils\RuntimeOptions; class Sample { /** * Use your AccessKey ID and AccessKey secret to initialize a client. * @return Facebody Client */ public static function createClient(){ $config = new Config([ // Required. Make sure that the ALIBABA_CLOUD_ACCESS_KEY_ID environment variable is configured in the code runtime environment. "accessKeyId" => getenv("ALIBABA_CLOUD_ACCESS_KEY_ID"), // Required. Make sure that the ALIBABA_CLOUD_ACCESS_KEY_SECRET environment variable is configured in the code runtime environment. "accessKeySecret" => getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET") ]); $config->endpoint = "facebody.cn-shanghai.aliyuncs.com"; return new Facebody($config); } /** * @param string[] $args * @return void */ public static function main($args){ $client = self::createClient(); // Create a request object and specify parameters. $detectBodyCountRequest = new DetectBodyCountRequest([ "imageURL" => "<YOUR_VALUE>" ]); // Create a runtime configuration object. $runtime = new RuntimeOptions([]); try { // Write your own code to display the response of the API operation if necessary. $client->detectBodyCountWithOptions($detectBodyCountRequest, $runtime); } catch (Exception $error) { if (!($error instanceof TeaError)) { $error = new TeaError([], $error->getMessage(), $error->getCode(), $error); } // Handle exceptions with caution in actual business scenarios and never ignore exceptions in your project. In this example, error messages are displayed for reference only. // The error message. var_dump($error->message); // The information for troubleshooting. var_dump($error->data["Recommend"]); Utils::assertAsString($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));