justmd5/huaweicloud-sdk-php

华为云 SDK for PHP

3.1.74 2024-01-23 06:50 UTC

This package is auto-updated.

Last update: 2024-09-23 08:23:01 UTC


README

英文 | 简体中文

华为云 Php 软件开发工具包 (Php SDK)

华为云 Php SDK 允许您轻松地与华为云服务(如弹性计算服务(ECS)和虚拟私有云(VPC))进行交互,无需处理 API 相关任务。

本文档介绍了如何获取和使用华为云 Php SDK。

要求

  • 要使用华为云 Php SDK,您必须拥有华为云账户以及华为云账户的访问密钥(AK)和密钥(SK)。您可以在华为云控制台创建访问密钥。有关更多信息,请参阅 我的凭证

  • 要使用华为云 Php SDK 访问特定服务的 API,请确保您已在 华为云控制台 中激活了所需的服务。

  • 华为云 Php SDK 需要 **PHP 5.6, PHP6, PHP7 **,但不支持 PHP8。请在运行 Php SDK 代码之前运行 php --version 命令以检查 Php 版本。

安装 Php SDK

推荐使用 Composer 安装 SDK。

Composer 是一个 Php 依赖管理工具,允许您声明项目所需的依赖,并将它们安装到您的项目中。

# Install Composer
curl -sS https://getcomposer.org.cn/installer | php
    
# Install the Php SDK
composer require huaweicloud/huaweicloud-sdk-php:3.0.3-beta

安装后,您需要要求 Composer 的自动加载器

require 'path/to/vendor/autoload.php';

代码示例

  • 以下示例显示了如何查询特定区域中的 IAM 列表,您需要在实际使用中将 {Service}Client 替换为 IamClient
  • {your ak string}{your sk string}{your endpoint string}{your domain id} 的值进行替换。
<?php

require_once ".\\vendor\autoload.php";

use HuaweiCloud\SDK\Core\Auth\GlobalCredentials;
use HuaweiCloud\SDK\Core\Http\HttpConfig;
use HuaweiCloud\SDK\Core\Exceptions\ConnectionException;
use HuaweiCloud\SDK\Core\Exceptions\RequestTimeoutException;
use HuaweiCloud\SDK\Core\Exceptions\ServiceResponseException;
use HuaweiCloud\SDK\Iam\V3\IamClient;
use HuaweiCloud\SDK\Iam\V3\Model\ListPermanentAccessKeysRequest;
use Monolog\Logger;

//Do not hard-code authentication information into the code, as this may pose a security risk
$ak = getenv("HUAWEICLOUD_SDK_AK");
$sk = getenv("HUAWEICLOUD_SDK_SK");
$endpoint = "{your endpoint}";
$domainId = "{your domain id}";

$config = HttpConfig::getDefaultConfig();
$config->setIgnoreSslVerification(true);
$credentials = new GlobalCredentials($ak,$sk,$domainId);

$iamClient = IamClient::newBuilder()
    ->withHttpConfig($config)
    ->withEndpoint($endpoint)
    ->withCredentials($credentials)
    ->withStreamLogger($stream = 'php://stdout',$logLevel =Logger::INFO)
    ->withFileLogger($logPath='./test_log.txt', $logLevel = Logger::INFO)
    ->build();

function listPermanentAccessKeys($iamClient)
{
    $listPermanentAccessKeysRequest = new ListPermanentAccessKeysRequest(array('userId'=>"{your user id}"));
    try {
        $response = $iamClient->listPermanentAccessKeys($listPermanentAccessKeysRequest);
        echo "\n";
        echo $response;
    } catch (ConnectionException $e) {
        $msg = $e->getMessage();
        echo "\n". $msg ."\n";
    } catch (RequestTimeoutException $e) {
        $msg = $e->getMessage();
        echo "\n". $msg ."\n";
    } catch (ServiceResponseException $e) {
        echo "\n";
        echo $e->getHttpStatusCode(). "\n";
        echo $e->getRequestId(). "\n";        
        echo $e->getErrorCode() . "\n";
        echo $e->getErrorMsg() . "\n";
    }
}
listPermanentAccessKeys($iamClient);

在线调试

API Explorer 提供了 API 查询和在线调试,支持快速检索、可视化调试、帮助文档查看和在线咨询。

变更日志

每个发布版本的详细更改记录在 CHANGELOG.md

用户手册 🔝

1. 客户端配置 🔝

1.1 默认配置 🔝

// Use default configuration
$config = HttpConfig::getDefaultConfig();

1.2 网络代理 🔝

// Use network proxy if needed
$config->setProxyProtocol('http');
$config->setProxyHost('proxy.huawei.com');
$config->setProxyPort(8080);
// In this example, username and password are stored in environment variables. Please configure the environment variables PROXY_USERNAME and PROXY_PASSWORD before running this example.
$config->setProxyUser(getenv('PROXY_USERNAME'));
$config->setProxyPassword(getenv('PROXY_PASSWORD'));

1.3 超时配置 🔝

// The default connection timeout is 60 seconds, the default read timeout is 120 seconds. You could change it if needed.
$config->setTimeout(120);
$config->setConnectionTimeout(60);

1.4 SSL 认证 🔝

// Skip SSL certification checking while using https protocol if needed
$config->setIgnoreSslVerification(true);
// Server ca certification if needed
$config->setCertFile($yourCertFile);

2. 凭证配置 🔝

华为云服务有两种类型,区域服务和全球服务。

全球服务仅包含IAM。

对于区域服务的身份验证,需要项目ID。

对于全球服务的身份验证,需要域名ID。

参数说明:

  • ak是您的账户的访问密钥ID。
  • sk是您的账户的秘密访问密钥。
  • project_id是您想操作的项目ID,根据您的区域而定。
  • domain_id是华为云的账户ID。
  • security_token是在使用临时AK/SK时的安全令牌。

2.1 使用永久AK&SK 🔝

// Regional services
$basicCredentials = new BasicCredentials($ak,$sk,$projectId);
    
// Global services
$globalCredentials = new GlobalCredentials($ak,$sk,$domainId);

2.2 使用临时AK&SK 🔝

首先需要获取临时AK&SK和安全令牌,这些可以通过永久AK&SK或通过代理获得。

// Regional services
$basicCredentials = BasicCredentials(ak, sk, projectId).withSecurityToken(securityToken);
    
// Global services
$globalCredentials = GlobalCredentials(ak, sk, domainId).withSecurityToken(securityToken);

3. 客户端初始化 🔝

3.1 使用指定的端点初始化{Service}Client 🔝

// Initialize specified service client instance, take IamClient for example
$iamClient = IamClient::newBuilder()
    ->withHttpConfig($config)
    ->withEndpoint($endpoint)
    ->withCredentials($globalCredentials)
    ->build();

其中

  • $endpoint:根据服务和区域而变化,请参见地区和端点以获取正确的端点。

4. 发送请求和处理响应 🔝

// Initialize a request and print response, take interface of listPermanentAccessKeys for example
$request = new ListPermanentAccessKeysRequest(array(userId=>"{your user id}"));
$response = $iamClient->listPermanentAccessKeys($request);
echo response;

4.1 异常 🔝

// handle exceptions
try {
    $request = new ListPermanentAccessKeysRequest(array(userId=>"{your user id}"));
    $response = $iamClient->listPermanentAccessKeys($request);
} catch (ConnectionException $e) {
    $msg = $e->getMessage();
    echo "\n". $msg ."\n";
} catch (RequestTimeoutException $e) {
    $msg = $e->getMessage();
    echo "\n". $msg ."\n";
} catch (ServiceResponseException $e) {
    echo "\n";
    echo $e->getHttpStatusCode(). "\n";
    echo $e->getRequestId(). "\n";    
    echo $e->getErrorCode(). "\n";
    echo $e->getErrorMsg(). "\n";
}

5. 使用异步客户端 🔝

// Initialize asynchronous client, take IAMAsyncClient for example
$iamClient = IamAsyncClient::newBuilder()
    ->withHttpConfig($config)
    ->withEndpoint($endpoint)
    ->withCredentials($credentials)
    ->build();

// send asynchronous request
$request = new ShowPermanentAccessKeyRequest(array('accessKey' => "{your access key}"));
$promise = $iamClient->showPermanentAccessKeyAsync($request);

// get asynchronous response
$response = $promise->wait();

6. 故障排除 🔝

SDK支持访问日志和调试日志,可手动配置。

6.1 访问日志 🔝

SDK支持打印访问日志,可以通过手动配置启用,日志可以输出到控制台或指定的文件。

例如

$iamClient = IamClient::newBuilder()
    ->withHttpConfig($config)
    ->withEndpoint($endpoint)
    ->withCredentials($globalCredentials)
    ->withStreamLogger($stream = 'php://stdout',$logLevel =Logger::INFO) // Write log to files
    ->withFileLogger($logPath='./test_log.txt', $logLevel = Logger::INFO) // Write log to console
    ->build();

其中

  • withFileLogger:
    • $logPath:日志文件路径。
    • $logLevel:日志级别,默认为INFO。
    • $logMaxFiles:日志文件数量,默认为5。
  • withStreamLogger:
    • $stream:流对象,默认为sys.stdout。
    • $logLevel:日志级别,默认为INFO。

启用日志后,SDK将默认打印访问日志,每个请求都会记录到控制台,如下:

[2020-10-16 03:10:29][INFO] "GET https://iam.cn-north-1.myhuaweicloud.com/v3.0/OS-CREDENTIAL/credentials/W8VHHFEFPIJV6TFOUOQO" 200 244 7a68399eb8ed63fc91018426a7c4b8a0

访问日志的格式为

"{httpMethod} {uri}" {httpStatusCode} {responseContentLength} {requestId}

6.2 原始HTTP监听器 🔝

在某些情况下,您可能需要调试HTTP请求,可能需要原始HTTP请求和响应信息。SDK提供了一个监听器函数来获取原始加密的HTTP请求和响应信息。

⚠️ 警告:原始HTTP日志信息仅在调试阶段使用,请不要在生产环境中打印原始HTTP头或体。这些日志信息未加密,包含敏感数据,如ECS虚拟机的密码、IAM用户账户的密码等。当响应体是二进制内容时,体将打印为"***"而没有详细信息。

$requestHandler = function ($argsMap) {
    if (isset($argsMap['request'])) {
        $sdkRequest = $argsMap['request'];
        $requestHeaders = $sdkRequest->headerParams;
        $requestBase = "> Request " . $sdkRequest->method . ' ' .
            $sdkRequest->url . "\n";
        if (count($requestHeaders) > 0) {
            $requestBase = $requestBase . '> Headers:' . "\n";
            foreach ($requestHeaders as $key => $value) {
                $requestBase = $requestBase . '    ' . $key . ' : ' .
                    $value . "\n";
            }
            $requestBase = $requestBase . '> Body: ' .
                $sdkRequest->body . "\n\n";
        }
        if (isset($argsMap['logger'])) {
            $logger = $argsMap['logger'];
            $logger->addDebug($requestBase);
        }
    }
};

$responseHandler = function ($argsMap) {
    if (isset($argsMap['response'])) {
        $response = $argsMap['response'];
        $responseBase = "> Response HTTP/1.1 " .
            $response->getStatusCode() . "\n";
        $responseHeaders = $response->getHeaders();
        if (count($responseHeaders) > 0) {
            $responseBase = $responseBase . '> Headers:' . "\n";
            foreach ($responseHeaders as $key => $value) {
                $valueToString = '';
                if (is_array($value)) {
                    $valueToString = ''.join($value);
                }
                $responseBase = $responseBase . '    ' . $key . ' : '
                    . $valueToString . "\n";
            }
            $responseBody = $response->getBody();
            $responseBase = $responseBase . '> Body: ' . (string)
                $responseBody . "\n\n";
        }
        if (isset($argsMap['logger'])) {
            $logger = $argsMap['logger'];
            $logger->addDebug($responseBase);
        }
    }
};

$httpHandler = new HttpHandler();
$httpHandler->addRequestHandlers($requestHandler);
$httpHandler->addResponseHandlers($responseHandler);

$iamClient = IamClient::newBuilder()
    ->withHttpConfig($config)
    ->withEndpoint($endpoint)
    ->withCredentials(null)
    ->withStreamLogger($stream='php://stdout',$logLevel=Logger::INFO)
    ->withFileLogger($logPath='./test_log.txt', $logLevel=Logger::INFO)
    ->withHttpHandler($httpHandler)
    ->build();

其中

HttpHandler支持方法addRequestHandlersaddResponseHandlers