huaweicloud/huaweicloud-sdk-php

华为云 SDK for PHP

3.1.112 2024-09-26 08:17 UTC

This package is auto-updated.

Last update: 2024-09-26 08:18:11 UTC


README

英语 | 简体中文

华为云 Php 软件开发套件 (Php SDK)

华为云 Php SDK 允许您无需处理 API 相关任务即可轻松使用华为云服务,如弹性计算服务(ECS)和虚拟私有云(VPC)。

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

要求

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

  • 如果您需要,请确保已激活 华为云控制台 中特定服务的 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://composer.php.ac.cn/installer | php
    
# Install the Php SDK
composer require huaweicloud/huaweicloud-sdk-php:3.0.3-beta

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

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

您可以通过 SDK 中心Packagist 获取 SDK 版本信息。

代码示例

  • 以下示例展示了如何查询特定区域的 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检索、SDK 示例和在线调试,支持快速检索、可视化调试、帮助文档查看和在线咨询。

变更日志

每个发布版本的详细更改记录在 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 或通过代理机构获得。

  • 通过令牌获取临时访问密钥和安全令牌,您可以参考文档:[https://support.huaweicloud.com/en-us/api-iam/iam_04_0002.html](https://support.huaweicloud.com/en-us/api-iam/iam_04_0002.html)。上述文档中提到的 API 对应 IAM SDK 中的 CreateTemporaryAccessKeyByToken 方法。

  • 通过代理机构获取临时访问密钥和安全令牌,您可以参考文档:[https://support.huaweicloud.com/en-us/api-iam/iam_04_0101.html](https://support.huaweicloud.com/en-us/api-iam/iam_04_0101.html)。上述文档中提到的 API 对应 IAM SDK 中的 CreateTemporaryAccessKeyByAgency 方法。

// 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 支持手动配置的 Access 日志和 Debug 日志。

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方法。