All Products
Search
Document Center

Alibaba Cloud SDK:Gunakan Alibaba Cloud SDK untuk PHP di IDE

Last Updated:Jun 22, 2026

Topik ini menjelaskan cara menggunakan Alibaba Cloud SDK untuk PHP di lingkungan pengembangan terintegrasi (IDE) pada Windows, dengan Visual Studio (VS) Code sebagai contoh.

Prasyarat

Gunakan SDK

Gunakan proyek contoh yang disediakan di OpenAPI Explorer

Catatan

Anda mungkin gagal mengunduh proyek contoh untuk operasi API tertentu. Dalam kasus ini, Anda dapat menggunakan SDK dalam proyek yang sudah ada. Untuk informasi selengkapnya, lihat bagian Gunakan SDK dalam proyek yang sudah ada pada topik ini.

  1. Buka OpenAPI Explorer, lalu cari operasi API yang ingin dipanggil. Sebagai contoh, untuk memanggil operasi API DescribeRegions dari ECS, masukkan DescribeRegions di bilah pencarian dan klik nama API pada hasil pencarian untuk membuka halaman debugging API.

  2. Pada tab Parameters, tentukan parameter sesuai kebutuhan Anda. Saat menentukan parameter, baca informasi pada tab Documentation di sisi kanan halaman debugging untuk memahami catatan penggunaan operasi tersebut, deskripsi setiap parameter, serta informasi terkait penagihan.

    Tabel Request Parameters pada tab Documentation mencantumkan nama, tipe, deskripsi, dan nilai contoh untuk setiap parameter, seperti InstanceChargeType, ResourceType, dan AcceptLanguage. Parameter Response Parameters tercantum di bawahnya.

  3. Pada tab SDK Sample Code di sisi kanan halaman debugging, pilih bahasa pemrograman PHP dan klik Download Project untuk mengunduh paket proyek contoh lengkap ke komputer Anda. Kemudian, ekstrak paket tersebut.

    Pilih versi SDK V2.0 (Direkomendasikan), pilih PHP pada tab bahasa, lalu klik Download Project.

  4. Buka paket hasil ekstraksi di VS Code dan jalankan perintah composer install di terminal untuk menginstal dependensi yang dibutuhkan oleh proyek contoh.

    Kesalahan berikut mungkin muncul saat Anda menjalankan perintah composer install:

    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.

    Untuk memperbaiki kesalahan tersebut, modifikasi versi dependensi alibabacloud/ecs-20140526 dalam file composer.json.

    "alibabacloud/ecs-20140526": "^4.1"
  5. Jalankan perintah php src/Sample.php di terminal untuk menjalankan kode contoh. Jika respons berisi "statusCode":200, panggilan berhasil.

    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"}} [] []

Gunakan SDK dalam proyek yang sudah ada

  1. Peroleh SDK: Kunjungi SDK Center, lalu pilih produk cloud yang ingin digunakan. Topik ini menggunakan ECS sebagai contoh. Untuk SDK Version, pilih V2.0, dan untuk Language, pilih PHP.

    Halaman SDK mencantumkan persyaratan lingkungan: PHP 5.6 atau versi lebih baru dan Composer yang diinstal secara global. Untuk menginstal SDK dari Packagist, jalankan perintah composer require alibabacloud/ecs-20140526 4.1.7. Untuk menggunakan mirror Composer Alibaba Cloud, jalankan composer config -g repo.packagist composer https://mirrors.aliyun.com/composer/.

  2. Buka VS Code. Pada bilah navigasi atas, pilih File > Open Folder. Buat dan pilih folder proyek atau pilih folder proyek yang sudah ada. Dalam contoh ini, folder bernama phpprojects dibuat dan dipilih.

  3. Salin perintah yang digunakan untuk menginstal SDK dan jalankan perintah tersebut di terminal untuk menginstal SDK.

  4. Pada panel EXPLORER, klik kanan area kosong lalu pilih New File untuk membuat file PHP. Beri nama file tersebut demo.php.

  5. Inisialisasi client. Untuk memanggil operasi API Alibaba Cloud, Anda harus menginisialisasi client terlebih dahulu. Dalam contoh ini, client ECS diinisialisasi.

    Penting
    1. Anda harus menggunakan pasangan AccessKey untuk menyelesaikan verifikasi identitas saat menginisialisasi client. Oleh karena itu, Anda harus memperoleh pasangan AccessKey terlebih dahulu. Untuk informasi selengkapnya tentang cara memperoleh pasangan AccessKey, lihat Buat AccessKey.

    2. Setelah memperoleh pasangan AccessKey milik Pengguna RAM, Anda harus mengonfigurasi pasangan AccessKey tersebut dalam variabel lingkungan. Untuk informasi selengkapnya, lihat Konfigurasi variabel lingkungan di Linux, macOS, dan Windows.

    3. Untuk informasi selengkapnya tentang cara mengonfigurasi endpoint, lihat Endpoints.

    <?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);
        }
    }
  6. Panggil API. Tinjau Dokumentasi API untuk API yang dituju. Contoh berikut memanggil API DescribeRegions dari ECS.

    Catatan

    Setiap API memiliki objek permintaan terpisah yang mengikuti konvensi penamaan ${APIName}${Request}, seperti DescribeRegionsRequest.

    <?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();
  7. Tangani exception. Tangani exception dengan hati-hati dalam skenario bisnis aktual dan jangan pernah mengabaikan exception dalam proyek Anda. Kami menyarankan agar Anda menangani exception secara tepat dengan melakukan operasi seperti melaporkan exception, mencatat log, dan melakukan retry. Hal ini membantu memastikan ketangguhan dan stabilitas sistem Anda. Untuk informasi selengkapnya tentang cara menangani exception dalam SDK untuk PHP, lihat Tangani exception.

    <?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();

FAQ

  • Apa yang harus saya lakukan jika muncul error "cURL error 60: SSL certificate problem: unable to get local issuer certificate" saat memanggil operasi API?

    • Unduh sertifikat Otoritas Sertifikat (CA) tepercaya. Sebagai contoh, Anda dapat mengunduh sertifikat CA dari Mozilla. Untuk informasi selengkapnya, lihat Sertifikat CA yang diekstrak dari Mozilla.

    • Konfigurasi jalur sertifikat SSL untuk PHP. Cari parameter curl.cainfo dalam file php.ini, atur nilai parameter tersebut ke jalur mutlak sertifikat CA, lalu hapus titik koma (;) sebelum parameter tersebut.

    • Mulai ulang layanan PHP.

Referensi

Referensi lanjutan