先安装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);
$this->red->setex($key, $token[‘ExpireTime‘] - 1000, $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);
}
}
}
PHP获取阿里云accessToken