O Alibaba Cloud SDK V1.0 for PHP oferece suporte a chamadas de api genéricas. Este tópico descreve como fazer chamadas genéricas com o Alibaba Cloud SDK V1.0 for PHP.
Características
Leveza: Com o Alibaba Cloud SDK V1.0 for PHP, você chama todas as operações de api instalando apenas a biblioteca principal do Alibaba Cloud SDK, sem precisar instalar o SDK de cada serviço individualmente.
Iteração rápida e compatibilidade: Caso um serviço de nuvem não forneça um SDK ou o SDK não esteja atualizado com as operações de api mais recentes, use chamadas genéricas para acessar essas novas APIs imediatamente, sem aguardar atualizações do SDK.
Para obter mais informações, consulte Chamadas genéricas e chamadas especializadas.
Observações de uso
Antes de fazer uma chamada genérica, obtenha e especifique manualmente os metadados necessários, incluindo a versão da api, a url da solicitação e o tipo de parâmetro. Para mais detalhes, consulte Metadados da api.
Instale a biblioteca principal do Alibaba Cloud SDK V1.0 for PHP
Execute o comando abaixo no terminal para instale a biblioteca principal do Alibaba Cloud SDK V1.0 for PHP:
composer require alibabacloud/client
Chame uma operação de api
Inicialize um cliente de solicitação
No pacote AlibabaCloud, crie um client para inicializar o cliente de solicitação e utilize esse client para invocar as API operations. Neste exemplo, usa-se um AccessKey pair para inicializar o cliente. Consulte Gerencie credenciais de acesso para mais informações.
Para evitar vazamentos de AccessKey, armazene o par de AccessKey em variáveis de ambiente. Para mais informações, consulte Configure variáveis de ambiente no Linux, macOS e 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 as informações da operação de api e os parâmetros da solicitação
Use o client do pacote AlibabaCloud para definir as informações básicas e os parâmetros da API operation. Para obter detalhes sobre os parâmetros comuns de solicitação, consulte Configurações avançadas.
O módulo request converte os metadados da api (como número da versão, url e tipo de parâmetro) em uma solicitação HTTP válida por meio de um processo padrão de configuração e retorna os dados brutos da resposta. A forma de passagem dos parâmetros depende do estilo e do design da api.
Parâmetros específicos da operação
A maneira como se passa um parâmetro de solicitação depende dos metadados da operação de api. Por exemplo, a operação DescribeInstanceStatus está definida como {"name":"RegionId","in":"query",...}} nos metadados. Nesse caso, "in":"query" indica que o ID da região (RegionId) deve ser passado em options([ 'query' => [ 'key1' => 'value1'] ]).
Cenário | Como passar o parâmetro |
| options([ 'query' => [ 'key1' => 'value1'] ]) Nota Para especificar uma coleção de pares chave-valor, use o seguinte formato: 'query' => [ 'key.1' => 'value1','key.2' => 'value2']... |
| options([ 'form_params' => [ 'key1' => 'value1'] ]) Nota Se o parâmetro da solicitação não for uma string, converta o valor do parâmetro para uma string JSON e defina essa string como o valor do 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',
// ],
])
Inicie uma solicitação
Use o client para iniciar uma solicitação chamando a função 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 exemplo
Exemplo: Chamar uma operação de api estilo RPC
Este exemplo chama a operação DescribeRegions do ECS para demonstrar como fazer uma chamada genérica de uma operação.
<?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();
Exemplo: Chamar uma operação de api estilo RESTful (ROA)
O código a seguir mostra como usar CommonRequest para chamar a operação DescribeClustersV1 do 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();
Perguntas frequentes
-
O que fazer se a mensagem de erro "Fatal error: Uncaught AlibabaCloud\Client\Exception\ClientException: AccessKey ID cannot be empty inXXX" for retornada?
Causa: O par de AccessKey não está configurado corretamente.
Soluções:
-
Execute os comandos abaixo para verifique se as variáveis de ambiente ALIBABA_CLOUD_ACCESS_KEY_ID e ALIBABA_CLOUD_ACCESS_KEY_SECRET estão 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%Se um par de AccessKey válido for retornado, as variáveis de ambiente estarão configuradas corretamente. Caso nenhum par de AccessKey ou um par inválido seja retornado, configure as variáveis de ambiente conforme necessário. Para mais informações, consulte Configure variáveis de ambiente no Linux, macOS e Windows.
-
Verifique se há erros relacionados ao par de AccessKey no código.
Exemplo de solicitação com erro:
AlibabaCloud::accessKeyClient( getenv('yourAccessKeyID'), getenv('yourAccessKeySecret') )NotaNo exemplo de solicitação com erro acima, os valores de entrada de getenv() são usados como o par de AccessKey. No entanto, essa função serve para ler valores das variáveis de ambiente. Após definir os nomes das variáveis de ambiente como ALIBABA_CLOUD_ACCESS_KEY_ID e ALIBABA_CLOUD_ACCESS_KEY_SECRET na sua máquina, o getenv poderá ler os valores dessas variáveis.
Exemplo de solicitação bem-sucedida:
AlibabaCloud::accessKeyClient( getenv('ALIBABA_CLOUD_ACCESS_KEY_ID'), getenv('ALIBABA_CLOUD_ACCESS_KEY_SECRET') )
-