PHP獲取阿里雲accessToken


先安裝sdk

composer require alibabacloud/sdk

需要知道 AccessKeyID,AccessKeySecret

<?php

/**
 * composer require alibabacloud/sdk
 * 獲取阿里雲相關的token
 */

namespace Common\Service;

use AlibabaCloud\Client\AlibabaCloud;
use AlibabaCloud\Client\Exception\ClientException;
use AlibabaCloud\Client\Exception\ServerException;

// 處理圖片上傳
class AliTokenService extends CommonService
{
    public function getToken()
    {
        // 查詢緩存中是否存在
        $key = "ali_access_token_caomall";
        $ttl = $this->red->ttl($key);
        if ($ttl == -2) { // 不存在
            /**
             * 第一步:設置一個全局客戶端
             * 使用阿里雲RAM賬號的AccessKey ID和AccessKey Secret進行鑒權
             */
            AlibabaCloud::accessKeyClient(
                C('ALI.AccessKeyID'),
                C('ALI.AccessKeySecret')
            )
                ->regionId("cn-shanghai")
                ->asDefaultClient();
            try {
                $response = AlibabaCloud::nlsCloudMeta()
                    ->v20180518()
                    ->createToken()
                    ->request();
                // print $response . "\n";
                $token = $response["Token"];

                if ($token != NULL) {
                    // print "Token 獲取成功:\n";
                    // print_r($token);
                    $difftime = $token['ExpireTime'] - time() - 1000;
                    $this->red->setex($key, $difftime, $token['Id']);
                    return $token['Id'];
                } else {
                    return false;
                }
            } catch (ClientException $exception) {
                // 獲取錯誤消息
                return false;
                // print_r($exception->getErrorMessage());
            } catch (ServerException $exception) {
                // 獲取錯誤消息
                return false;
                // print_r($exception->getErrorMessage());
            }
        } else {
            return $this->red->get($key);
        }
    }
}



免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM