先安裝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);
}
}
}