Alibaba Cloud SDK V1.0 for PHP admite llamadas genéricas a la API. Este tema describe cómo hacer llamadas genéricas con Alibaba Cloud SDK V1.0 for PHP.
Características
Ligero: puede usar Alibaba Cloud SDK V1.0 for PHP para llamar a todas las operaciones de la API con solo instalar la biblioteca principal del SDK de Alibaba Cloud. No es necesario instalar el SDK de cada servicio.
Iteración rápida y compatibilidad: si un servicio en la nube no proporciona un SDK, o bien este no se ha actualizado para las operaciones más recientes de la API, puede recurrir a las llamadas genéricas. De esta forma, llama a las operaciones más recientes sin esperar a que se actualice el SDK.
Para obtener más información, consulte Generic calls and specialized calls.
Notas de uso
Antes de hacer una llamada genérica, obtenga y especifique manualmente los metadatos obligatorios, como la versión de la API, la URL de la solicitud y el tipo de parámetro. Para obtener más información, consulte API metadata.
Instale la biblioteca principal de Alibaba Cloud SDK V1.0 for PHP
Ejecute el siguiente comando en su terminal para instalar la biblioteca principal de Alibaba Cloud SDK V1.0 for PHP:
composer require alibabacloud/client
Llame a una operación de la API
Inicialice un cliente de solicitudes
En el paquete AlibabaCloud, cree un client para inicializar el cliente de solicitudes. Después, utilice ese client para llamar a las API operations. En este ejemplo se usa un AccessKey pair para inicializar el cliente de solicitudes. Para obtener más información, consulte Manage access credentials.
Para evitar filtraciones del AccessKey, guarde el par de claves en variables de entorno. Para obtener más información, consulte Configure environment variables in Linux, macOS, and Windows.
use AlibabaCloud\Client\AlibabaCloud;
// getenv indicates that the AccessKey pair obtained from environment variables is used to initialize the client.
AlibabaCloud::accessKeyClient(
getenv('ALIBABA_CLOUD_ACCESS_KEY_ID'),
getenv('ALIBABA_CLOUD_ACCESS_KEY_SECRET')
)
->regionId('cn-hangzhou') // Specify the region ID.
->asDefaultClient(); // Specify the client as the default client.
Configure la información de la operación de la API y los parámetros de la solicitud
Use el client del paquete AlibabaCloud para configurar la información básica y los parámetros de solicitud de la API operation. Para obtener más información sobre los parámetros de solicitud comunes, consulte Advanced settings.
El módulo request convierte los metadatos de la API (como el número de versión, la URL y el tipo de parámetro) en una solicitud HTTP válida mediante un proceso estándar de configuración. Luego devuelve los datos de respuesta originales. La forma de pasar los parámetros depende del estilo y el diseño de la API.
Parámetros específicos de la operación
La manera de enviar un parámetro de solicitud depende de los metadatos de la operación de la API. Por ejemplo, la operación DescribeInstanceStatus se define como {"name":"RegionId","in":"query",...}} en los metadatos. En este caso, "in":"query" indica que el identificador de región (RegionId) debe pasarse en options([ 'query' => [ 'key1' => 'value1'] ]).
Escenario | Cómo se pasa el parámetro |
| options([ 'query' => [ 'key1' => 'value1'] ]) Nota Para especificar una colección de pares clave-valor, use el siguiente formato: 'query' => [ 'key.1' => 'value1','key.2' => 'value2']... |
| options([ 'form_params' => [ 'key1' => 'value1'] ]) Nota Si el parámetro de solicitud no especifica una cadena, convierta el valor del parámetro a una cadena JSON y asígnela como valor del parámetro. |
// The query parameters when they are of the collection type.
$instanceIDs = ["i-bp1axhql4dqXXXXXXXX", "i-bp124uve8zqXXXXXXXX"];
// Common parameters.
$queryParams = [
'RegionId' => 'cn-hangzhou',
'PageNumber' => 1,
'PageSize' => 30,
];
// Process the collection parameters by converting them to the format of InstanceId.1, InstanceId.2.
foreach ($instanceIDs as $index => $id) {
$queryKey = 'InstanceId.' . ($index + 1);
$queryParams[$queryKey] = $id;
}
// Configure the basic information about and request parameters of the API operation.
$result = AlibabaCloud::rpc() // The API operation style, such as remote procedure call (RPC) and resource-oriented architecture (ROA).
// 1.Configure the basic information about the API operation.
->host('ecs.cn-hangzhou.aliyuncs.com')
->product('Ecs') // The service name.
->version('2014-05-26') // Make sure that the version number must be the same as that in the API reference.
->action('DescribeInstanceStatus') // The name of the API operation. When you call an RPC-style API operation, you must configure action() to specify the name of the API operation.
->method('POST') // The request method. Valid values: GET and POST.
->setProtocolType('HTTPS') // The request protocol. Valid values: HTTP and HTTPS. We recommend that you use HTTPS.
// ->pathPattern() // The resource path, which is required by ROA-style API operations. Do not configure this parameter for RPC-style API operations.
// 2.Configure the request parameters.
->options([
// Scenario 1: Configure query parameters.
'query' => $queryParams
// Scenario 2: Configure the request body in form_params.
// 'form_params' => [
// 'key1' => 'value1',
// 'key2' => 'value2',
// 'key3' => 'value3',
// ],
])
Envíe una solicitud
Utilice el client para enviar una solicitud mediante la función request().
// Call an RPC-style API operation.
$result = AlibabaCloud::rpc()
->request()
// Call an ROA-style API operation.
// $result = AlibabaCloud::roa()
// ->request()
// If the response is of the byte type, the request ID and response parameters are returned.
print_r($result->toArray());
Código de ejemplo
Ejemplo: llame a una operación de la API de estilo RPC
En este ejemplo se llama a la operación DescribeRegions de ECS para mostrar cómo hacer una llamada genérica a una operación.
<?php
namespace AlibabaCloud\SDK\Sample;
require_once 'vendor/autoload.php';
use AlibabaCloud\Tea\Utils\Utils;
use AlibabaCloud\Client\AlibabaCloud;
use AlibabaCloud\Client\Exception\ClientException;
use AlibabaCloud\Client\Exception\ServerException;
class Sample
{
public static function main()
{
// getenv indicates that the AccessKey pair obtained from environment variables is used to initialize the client.
AlibabaCloud::accessKeyClient(
getenv('ALIBABA_CLOUD_ACCESS_KEY_ID'),
getenv('ALIBABA_CLOUD_ACCESS_KEY_SECRET')
)
->regionId('cn-hangzhou') // Specify the region ID.
->asDefaultClient(); // Specify the client as the default client.
// Configure query parameters when they are of the collection type.
$instanceIDs = ["i-bp1axhql4dqXXXXXXXX", "i-bp124uve8zqXXXXXXXX"];
// Common parameters.
$queryParams = [
'RegionId' => 'cn-hangzhou',
'PageNumber' => 1,
'PageSize' => 30,
];
// Process the collection parameters by converting them to the format of InstanceId.1, InstanceId.2.
foreach ($instanceIDs as $index => $id) {
$queryKey = 'InstanceId.' . ($index + 1);
$queryParams[$queryKey] = $id;
}
try {
$result = AlibabaCloud::rpc()
->method('POST') // The request method.
->verify(false) // Disable certification authentication.
->debug(true) // Enable logging.
->setProtocolType('HTTPS') // Configure a protocol.
->host('ecs.cn-hangzhou.aliyuncs.com') // Configure the endpoint.
->version('2014-05-26') // Make sure that the version number must be the same as that in the API reference.
->action('DescribeInstanceStatus') // Specify the API operation name.
// Configure request parameters.
->options([
'query' => $queryParams
])
// Send the request.
->request();
print_r($result->toArray());
} catch (ClientException | ServerException $e) {
echo $e->getErrorMessage();
} catch (ServerException $exception) {
print_r($exception->getErrorMessage());
}
}
}
Sample::main();
Ejemplo: llame a una operación de la API de estilo RESTful (ROA)
A continuación se muestra cómo usar CommonRequest para llamar a la operación DescribeClustersV1 de Container Service for Kubernetes (ACK):
<?php
namespace AlibabaCloud\SDK\Sample;
require_once 'vendor/autoload.php';
use AlibabaCloud\Client\AlibabaCloud;
use AlibabaCloud\Client\Exception\ClientException;
use AlibabaCloud\Client\Exception\ServerException;
class Sample
{
public static function main()
{
try {
$result = AlibabaCloud::roa()
->regionId('cn-hangzhou) // The region ID. If this parameter is not specified, the region of the client or the default region is used.
->product('CS') // The service name.
->version('2015-12-15 ') // The service version.
->serviceCode('cs') // The service code for addressing. This parameter is optional.
->endpointType('openAPI') // The endpoint type. This parameter is optional.
->method('GET') // The request method.
->host('cs.aliyun.com ') // The domain name. If this parameter is specified, addressing is not performed. If a service uses bearer tokens for authentication, you must specify the domain name.
->pathPattern('/api/v1/clusters') // The URL of the API operation. When you call an ROA-style API operation, you must configure pathPattern() to specify the complete URL of the API operation. You can obtain the URL of an API operation from the API metadata.
->request(); // Initiate the request and obtain the result. This parameter must be at the end of the settings.
print_r($result->toArray());
} catch (ClientException $exception) {
print_r($exception->getErrorMessage());
} catch (ServerException $exception) {
print_r($exception->getErrorMessage());
}
}
}
Sample::main();
Preguntas frecuentes
-
¿Qué debo hacer si aparece el mensaje de error "Fatal error: Uncaught AlibabaCloud\Client\Exception\ClientException: AccessKey ID cannot be empty inXXX"?
Causa: el par de AccessKey no está configurado correctamente.
Soluciones:
-
Ejecute los siguientes comandos para comprobar si las variables de entorno ALIBABA_CLOUD_ACCESS_KEY_ID y ALIBABA_CLOUD_ACCESS_KEY_SECRET están configuradas.
Linux/macOS
echo $ALIBABA_CLOUD_ACCESS_KEY_ID echo $ALIBABA_CLOUD_ACCESS_KEY_SECRETWindows
echo %ALIBABA_CLOUD_ACCESS_KEY_ID% echo %ALIBABA_CLOUD_ACCESS_KEY_SECRET%Si se devuelve un par de AccessKey válido, las variables de entorno están bien configuradas. Si no se devuelve ningún par o el valor es incorrecto, configure las variables de entorno según corresponda. Para obtener más información, consulte Configure environment variables in Linux, macOS, and Windows.
-
Revise el código en busca de errores relacionados con el par de AccessKey.
Ejemplo de solicitud con error:
AlibabaCloud::accessKeyClient( getenv('yourAccessKeyID'), getenv('yourAccessKeySecret') )NotaEn el ejemplo anterior, los valores de entrada de getenv() se usan directamente como el par de AccessKey. Sin embargo, esta función lee valores de las variables de entorno. Una vez que defina los nombres de las variables de entorno como ALIBABA_CLOUD_ACCESS_KEY_ID y ALIBABA_CLOUD_ACCESS_KEY_SECRET en su máquina, getenv podrá leer los valores correspondientes.
Ejemplo de solicitud correcta:
AlibabaCloud::accessKeyClient( getenv('ALIBABA_CLOUD_ACCESS_KEY_ID'), getenv('ALIBABA_CLOUD_ACCESS_KEY_SECRET') )
-