Windows üzerinde bir IDE kullanarak PHP için Alibaba Cloud SDK'larına başlayın. Bu örnekte Visual Studio (VS) Code kullanılmıştır.
Ön Koşullar
PHP ve Composer yüklüdür. Daha fazla bilgi için bkz. PHP'yi Yükleme.
VS Code yüklenmiştir. Talimatlar için bkz. Windows'ta PHP Geliştirme Ortamı Kurulumu.
SDK Kullanımı
OpenAPI Explorer tarafından sağlanan örnek bir proje kullanma
Tüm API işlemleri için örnek projeler mevcut olmayabilir. İndiremezseniz Mevcut bir projede SDK kullanma bölümüne bakın.
OpenAPI Explorer adresine gidin ve çağırmak istediğiniz API işlemini arayın. Örneğin, ECS'nin DescribeRegions API işlemini çağırmak için arama çubuğuna DescribeRegions yazın ve API hata ayıklama sayfasını açmak için arama sonuçlarında API adına tıklayın.
-
Parameters sekmesinde gerekli parametreleri yapılandırın. Hata ayıklama sayfasının sağ tarafındaki Document sekmesindeki bilgileri inceleyerek kullanım notlarını ve parametre açıklamalarını anlayın. Faturalandırma ile ilgili bilgilere dikkat edin.
Documentation sekmesinde, Request Parameters tablosu her bir parametrenin adını, türünü, açıklamasını ve örnek değerini listeler; örneğin
InstanceChargeType,ResourceTypeveAcceptLanguage. Response Parameters aşağıda listelenmiştir. -
Hata ayıklama sayfasının sağ tarafındaki SDK Sample Code sekmesinde PHP programlama dilini seçin ve örnek proje paketini indirmek için Download Project seçeneğine tıklayın. Ardından paketi sıkıştırılmış halden çıkarın.
SDK sürümü olarak V2.0 (Önerilen) seçeneğini belirleyin, dil sekmesinden PHP seçeneğini işaretleyin ve ardından Download Project düğmesine tıklayın.
-
Sıkıştırması açılan paketi VS Code'da açın ve gerekli bağımlılıkları yüklemek için terminalde
composer installkomutunu çalıştırın.composer installkomutunu çalıştırdığınızda aşağıdaki hatayla karşılaşabilirsiniz:Your requirements could not be resolved to an installable set of packages. Problem 1 - Root composer.json requires alibabacloud/ecs-20140526 ^4.1.6 -> satisfiable by alibabacloud/ecs-20140526[4.1.6]. - alibabacloud/ecs-20140526 4.1.6 requires alibabacloud/tea-utils ^0.2.20 -> found alibabacloud/tea-utils[dev-master, 0.1.0, ..., 0.2.19] but it does not match the constraint.Bu hatayı düzeltmek için composer.json dosyasındaki alibabacloud/ecs-20140526 bağımlılığının sürüm kısıtlamasını değiştirin.
"alibabacloud/ecs-20140526": "^4.1" -
Örnek kodu çalıştırmak için terminalde
php src/Sample.phpkomutunu çalıştırın. Yanıtta"statusCode":200döndürülürse çağrı başarılı olmuştur.PS D:\xxx\download\e11baaaa2-4f02-4671-8432-2423be5a5a6f-PHP> php src/Sample.php [2024-07-03T09:59:56.716282+00:00] tea-console-log.INFO: {"headers":{"Date":["Wed, 03 Jul 2024 10:00:00 GMT"],"Content-Type":["application/json;charset=utf-8"],"Connection":["keep-alive"],"Keep-Alive":["timeout=25"],"Vary":["Accept-Encoding"],"Access-Control-Allow-Origin":["*"],"Access-Control-Expose-Headers":["*"],"x-acs-request-id":["3BA5A6C3-B296-5895-914A-8147910DE781"],"x-acs-trace-id":["086d8bd615f72d4d27daa5a7a7b4b89a"],"ETag":["22UU6WnEtZKE9S/VA80fvig"]},"statusCode":200,"body":{"Regions":{"Region":[{"LocalName":"China (Qingdao)","RegionEndpoint":"ecs.cn-qingdao.aliyuncs.com","RegionId":"cn-qingdao"},{"LocalName":"China (Beijing)","RegionEndpoint":"ecs.cn-beijing.aliyuncs.com","RegionId":"cn-beijing"},{"LocalName":"China (Zhangjiakou)","RegionEndpoint":"ecs.cn-zhangjiakou.aliyuncs.com","RegionId":"cn-zhangjiakou"},{"LocalName":"China (Hohhot)","RegionEndpoint":"ecs.cn-huhehaote.aliyuncs.com","RegionId":"cn-huhehaote"},{"LocalName":"China (Ulanqab)","RegionEndpoint":"ecs.cn-wulanchabu.aliyuncs.com","RegionId":"cn-wulanchabu"},{"LocalName":"China (Hangzhou)","RegionEndpoint":"ecs.aliyuncs.com","RegionId":"cn-hangzhou"},{"LocalName":"China (Shanghai)","RegionEndpoint":"ecs.cn-shanghai.aliyuncs.com","RegionId":"cn-shanghai"},...]},"RequestId":"3BA5A6C3-B296-5895-914A-8147910DE781"}} [] []
Mevcut bir projede SDK kullanma
-
SDK'yı edinin: SDK Center adresini ziyaret edin ve kullanmak istediğiniz cloud ürününü seçin. Bu örnekte ECS kullanılmıştır. SDK Version için V2.0 seçeneğini belirleyin ve Language için PHP seçeneğini işaretleyin.
SDK sayfası ortam gereksinimlerini listeler: PHP 5.6 veya üzeri ve global olarak yüklenmiş bir Composer. SDK'yı Packagist üzerinden yüklemek için
composer require alibabacloud/ecs-20140526 4.1.7komutunu çalıştırın. Alibaba Cloud Composer yansısını kullanmak içincomposer config -g repo.packagist composer https://mirrors.aliyun.com/composer/komutunu çalıştırın. VS Code'u açın. Üst gezinme çubuğunda File > Open Folder seçeneklerini seçin. Bir proje klasörü oluşturun ve seçin veya mevcut bir proje klasörünü seçin. Bu örnekte phpprojects adlı bir klasör oluşturulmuş ve seçilmiştir.
SDK yükleme komutunu kopyalayın ve terminalde çalıştırın.
EXPLORER panelinde boş bir alana sağ tıklayın ve New File seçeneğini belirleyerek bir PHP dosyası oluşturun. Dosyaya demo.php adını verin.
-
Bir istemci başlatın. Alibaba Cloud API işlemlerini çağırmadan önce bir istemci başlatmanız gerekir. Bu örnekte bir ECS istemcisi başlatılmaktadır.
Önemliİstemciyi başlatırken kimlik doğrulamasını tamamlamak için bir AccessKey çifti kullanmanız gerekir. Bu durumda önceden bir AccessKey çifti elde etmeniz gerekir. AccessKey çifti edinme hakkında daha fazla bilgi için bkz. AccessKey Oluşturma.
Bir RAM kullanıcısının AccessKey çiftini elde ettikten sonra bu çifti ortam değişkenlerinde yapılandırmanız gerekir. Daha fazla bilgi için bkz. Linux, macOS ve Windows'ta Ortam Değişkenlerini Yapılandırma.
Uç nokta yapılandırma hakkında daha fazla bilgi için bkz. Uç Noktalar.
<?php use AlibabaCloud\Credentials\Credential\Config; use AlibabaCloud\SDK\Ecs\V20140526\Ecs; class Sample { /** * Create an ECS client instance. * This method initializes and returns an ECS client object that can be used to perform ECS-related operations. * It configures the client by reading the AccessKey ID and AccessKey secret from environment variables, which ensures secure storage and access of sensitive information. * * @return Ecs A configured ECS client instance. */ public static function createClient() { // Create a configuration object. $config = new Config([ "accessKeyId" => getenv("ALIBABA_CLOUD_ACCESS_KEY_ID"), // Obtain the AccessKey ID of a RAM user from an environment variable. "accessKeySecret" => getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET"), // Obtain the AccessKey secret of a RAM user from an environment variable. "endpoint" => "ecs.cn-hangzhou.aliyuncs.com" // Set the endpoint for the ECS service. ]); // Use this configuration to create a new Ecs client instance. return new Ecs($config); } } -
API'yi çağırın. Hedef API için API Documentation belgesini inceleyin. Aşağıdaki örnek, ECS'nin
DescribeRegionsAPI'sini çağırmaktadır.NotHer API,
DescribeRegionsRequestgibi${APIName}${Request}adlandırma kuralını izleyen ayrı bir istek nesnesine sahiptir.<?php require_once 'vendor/autoload.php'; use AlibabaCloud\SDK\Ecs\V20140526\Ecs; use AlibabaCloud\SDK\Ecs\V20140526\Models\DescribeRegionsRequest; use AlibabaCloud\Tea\Utils\Utils\RuntimeOptions; use Darabonba\OpenApi\Models\Config; class Sample { /** * Create an ECS client instance. * This method initializes and returns an ECS client object that can be used to perform ECS-related operations. * It configures the client by reading the AccessKey ID and AccessKey secret from environment variables, which ensures secure storage and access of sensitive information. * * @return Ecs A configured ECS client instance. */ public static function createClient() { // Create a configuration object. $config = new Config([ "accessKeyId" => getenv("ALIBABA_CLOUD_ACCESS_KEY_ID"), // Obtain the AccessKey ID of a RAM user from an environment variable. "accessKeySecret" => getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET"), // Obtain the AccessKey secret of a RAM user from an environment variable. "endpoint" => "ecs.cn-hangzhou.aliyuncs.com" // Set the endpoint for the ECS service. ]); // Use the preceding configuration to create a new Ecs client instance. return new Ecs($config); } /** * * This function demonstrates how to use the SDK client to call the DescribeRegions API operation. * It creates a client instance, constructs a request object, and attempts to call the API operation. * If the call fails, the exception is caught and the error message is printed. */ public static function main() { // Create an SDK client instance. $client = self::createClient(); // Create a DescribeRegionsRequest request object without passing any parameters. $describeRegionsRequest = new DescribeRegionsRequest([]); // Create a RuntimeOptions instance without passing any parameters. $runtime = new RuntimeOptions([]); try { // Call the API operation using the client's describeRegionsWithOptions method. // A try-catch block is used to handle potential exceptions. $result = $client->describeRegionsWithOptions($describeRegionsRequest, $runtime); print_r($result); } catch (Exception $error) { // This is for demonstration purposes only. In a production environment, do not ignore exceptions. var_dump($error->message); } } } Sample::main(); -
Özel durumları yönetin. Üretim ortamında özel durumları asla göz ardı etmeyin. Sisteminizin dayanıklılığını ve kararlılığını sağlamak için özel durumları bildirin, günlükleri kaydedin ve yeniden denemeler gerçekleştirin. Daha fazla bilgi için bkz. Özel Durum İşleme.
<?php require_once 'vendor/autoload.php'; use AlibabaCloud\SDK\Ecs\V20140526\Ecs; use AlibabaCloud\SDK\Ecs\V20140526\Models\DescribeRegionsRequest; use AlibabaCloud\Tea\Utils\Utils\RuntimeOptions; use Darabonba\OpenApi\Models\Config; class Sample { /** * Create an ECS client instance. * This method initializes and returns an ECS client object that can be used to perform ECS-related operations. * It configures the client by reading the AccessKey ID and AccessKey secret from environment variables, which ensures secure storage and access of sensitive information. * * @return Ecs A configured ECS client instance. */ public static function createClient() { // Create a configuration object. $config = new Config([ "accessKeyId" => getenv("ALIBABA_CLOUD_ACCESS_KEY_ID"), // Obtain the AccessKey ID of a RAM user from an environment variable. "accessKeySecret" => getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET"), // Obtain the AccessKey secret of a RAM user from an environment variable. "endpoint" => "ecs.cn-hangzhou.aliyuncs.com" // Set the endpoint for the ECS service. ]); // Use the preceding configuration to create a new Ecs client instance. return new Ecs($config); } /** * * This function demonstrates how to use the SDK client to call the DescribeRegions API operation. * It creates a client instance, constructs a request object, and attempts to call the API operation. * If the call fails, the exception is caught and the error information is printed. */ public static function main() { // Create an SDK client instance. $client = self::createClient(); // Create a DescribeRegionsRequest request object without passing any parameters. $describeRegionsRequest = new DescribeRegionsRequest([]); // Create a RuntimeOptions instance without passing any parameters. $runtime = new RuntimeOptions([]); try { // Call the API operation using the client's describeRegionsWithOptions method. // A try-catch block is used to handle potential exceptions. $result = $client->describeRegionsWithOptions($describeRegionsRequest, $runtime); print_r($result); } catch (Exception $error) { if ($error instanceof TeaError) { // This is for demonstration purposes only. In a production environment, do not ignore exceptions. print_r("message:" . $error->getMessage() . "\n"); print_r("code:" . $error->getCode() . "\n"); print_r($error->data); } elseif ($error instanceof TeaUnableRetryError) { // This is for demonstration purposes only. In a production environment, do not ignore exceptions. print_r($error->getLastException()); } else { // This is for demonstration purposes only. In a production environment, do not ignore exceptions. print_r("message:" . $error->getMessage()); } } } } Sample::main();
SSS
-
Bir API işlemini çağırırken "cURL error 60: SSL certificate problem: unable to get local issuer certificate" hatası oluşursa ne yapmalıyım?
Mozilla gibi güvenilir bir sertifika yetkilisi (CA) sertifikası indirin. Daha fazla bilgi için bkz. CA certificates extracted from Mozilla.
PHP için SSL sertifika yolunu yapılandırın. php.ini dosyasında curl.cainfo parametresini bulun, değerini CA sertifikasının mutlak yolu olarak ayarlayın ve baştaki noktalı virgülü (;) kaldırın.
PHP hizmetini yeniden başlatın.