wayhood / huaweicloud-sdk-php
华为云SDK for PHP
Requires
- php: >=5.6.0
- guzzlehttp/guzzle: 6.3.0
- guzzlehttp/promises: 1.3.1
- guzzlehttp/psr7: 1.4.2
- monolog/monolog: ^2.0
- psr/http-message: 1.0.1
This package is auto-updated.
Last update: 2024-09-13 23:26:40 UTC
README
英语 | 简体中文
华为云PHP软件开发套件(PHP SDK)
华为云PHP SDK允许您轻松使用华为云服务,如弹性云服务器(ECS)和虚拟专用云(VPC),无需处理API相关任务。
本文档介绍了如何获取和使用华为云PHP SDK。
入门指南
-
要使用华为云PHP SDK,您必须有华为云账户以及华为云账户的访问密钥和密钥。
初始化
{Service}Client
时需要访问密钥。您可以在华为云控制台创建访问密钥。有关更多信息,请参阅我的凭证。 -
华为云PHP SDK需要PHP 5.6或更高版本。
安装PHP SDK
华为云PHP SDK支持PHP 5.6或更高版本。运行 PHP --version
检查PHP版本。
-
使用Composer
安装SDK的推荐方法是使用Composer。Composer是PHP的一个依赖管理工具,它允许您声明项目需要的依赖项并将它们安装到项目中。
# Install Composer curl -sS https://getcomposer.org/installer | php # Install the PHP SDK composer require huaweicloud/huaweicloud-sdk-php:3.0.3-beta
安装后,您需要包含Composer的自动加载器
require 'path/to/vendor/autoload.php';
使用PHP SDK
-
如下导入所需模块
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;
-
配置
{Service}Client
配置2.1 使用默认配置
# Use default configuration $config = HttpConfig::getDefaultConfig();
2.2 代理(可选)
# Use Proxy if needed $config->setProxyProtocol('http'); $config->setProxyHost('proxy.huawei.com'); $config->setProxyPort(8080); $config->setProxyUser('username'); $config->setProxyPassword('password');
2.3 连接(可选)
# seconds to wait for the server to send data before giving up, as a float, or (connect timeout, read timeout) $config->setTimeout(3);
2.4 SSL证书(可选)
# Skip ssl certification checking while using https protocol if needed $config->setIgnoreSslVerification(true); # Server ca certification if needed $config->setCertFile($yourCertFile);
-
初始化凭证
注意:华为云服务有两种类型,区域服务和全球服务。全球服务目前仅支持IAM。
区域服务的认证需要projectId。全球服务的认证需要domainId。
ak
是您的账户的访问密钥ID。sk
是您的账户的秘密访问密钥。project_id
是您要操作的区域的项目的ID。domain_id
是华为云的账户ID。security_token
是使用临时AK/SK时的安全令牌。
3.1 使用永久AK/SK
# Region services $credentials = new BasicCredentials($ak,$sk,$projectId); # Global services $credentials = new GlobalCredentials($ak,$sk,$domainId);
3.2 使用临时AK/SK
建议首先获取临时访问密钥、安全密钥和安全令牌,这可以通过永久访问密钥和安全密钥或通过代理获取。
通过永久访问密钥和安全密钥获取临时访问密钥令牌,请参阅文档: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。上述文档中提到的API对应于IAM SDK中的createTemporaryAccessKeyByAgency方法。
# Regional services $credentials = BasicCredentials(ak, sk, projectId).withSecurityToken(securityToken); # Global services $credentials = GlobalCredentials(ak, sk, domainId).withSecurityToken(securityToken);
-
初始化
{Service}Client
实例# Initialize specified service client instance, take IamClient for example $iamClient = IamClient::newBuilder() ->withHttpConfig($config) ->withEndpoint($endpoint) ->withCredentials(null) ->withStreamLogger($stream = 'php://stdout',$logLevel =Logger::INFO) // Write log files ->withFileLogger($logPath='./test_log.txt', $logLevel = Logger::INFO) // Write log to console ->build();
其中
- $
endpoint
: 服务特定端点,请参阅区域和端点。 withFileLogger
:$logPath
: 日志文件路径。$logLevel
: 日志级别,默认为INFO。$logMaxFiles
:日志文件的数量,默认为5。
withStreamLogger
:$stream
:流对象,默认为sys.stdout。$logLevel
: 日志级别,默认为INFO。
启用日志后,SDK默认将打印访问日志,每个请求都会在控制台记录,例如:
"{httpMethod} {uri}" {httpStatusCode} {responseContentLength} {requestId}
[2020-10-16 03:10:29][INFO] "GET https://iam.cn-north-1.myhuaweicloud.com/v3.0/OS-CREDENTIAL/credentials/W8VHHFEFPIJV6TFOUOQO" 200 244 7a68399eb8ed63fc91018426a7c4b8a0
- $
-
发送请求并打印响应。
# 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;
-
异常
# 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->getErrorCode() . "\n"; echo $e->getErrorMsg() . "\n"; }
-
异步请求
# 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();
-
故障排除
在某些情况下,您可能需要调试您的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支持addRequestHandlers和addResponseHandlers。
代码示例
-
以下示例显示了如何在特定区域查询IAM列表,您需要在实际使用中将
IamClient
替换为您的真实{Service}Client
。 -
替换
{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; $ak = "{your ak string}"; $sk = "{your sk string}"; $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->getErrorCode() . "\n"; echo $e->getErrorMsg() . "\n"; } } listPermanentAccessKeys($iamClient);