82 lines
2.3 KiB
PHP
82 lines
2.3 KiB
PHP
<?php
|
|
|
|
namespace Extend\Alibaba;
|
|
|
|
use App\Exception\BusinessException;
|
|
use DateTime;
|
|
use DateTimeInterface;
|
|
use OSS\Core\OssException;
|
|
use OSS\OssClient;
|
|
|
|
/**
|
|
* 阿里云oss
|
|
*/
|
|
class Oss
|
|
{
|
|
protected array $config;// 系统配置
|
|
|
|
public function __construct()
|
|
{
|
|
$this->config = config("alibaba.oss");
|
|
}
|
|
|
|
/**
|
|
* 创建客户端
|
|
* @return OssClient
|
|
*/
|
|
public function createClient(): OssClient
|
|
{
|
|
try {
|
|
return new OssClient($this->config['accessKey'], $this->config['accessKeySecret'], $this->config['endpoint']);
|
|
} catch (OssException $e) {
|
|
throw new BusinessException($e->getMessage());
|
|
}
|
|
}
|
|
|
|
/**
|
|
* 获取签名
|
|
* @param string $dir 用户上传文件时指定的前缀。
|
|
* @return array
|
|
*/
|
|
public function signature(string $dir): array
|
|
{
|
|
try {
|
|
$now = time();
|
|
$expire = 30; //设置该policy超时时间是10s. 即这个policy过了这个有效时间,将不能访问。
|
|
$end = $now + $expire;
|
|
$expiration = $this->gmt_iso8601($end);
|
|
|
|
$start = array(0 => 'starts-with', 1 => '$key', 2 => $dir);
|
|
$conditions[] = $start;
|
|
|
|
$arr = array('expiration' => $expiration, 'conditions' => $conditions);
|
|
$policy = json_encode($arr);
|
|
$base64_policy = base64_encode($policy);
|
|
$string_to_sign = $base64_policy;
|
|
$signature = base64_encode(hash_hmac('sha1', $string_to_sign, $this->config['accessKeySecret'], true));
|
|
|
|
$response = array();
|
|
$response['accessid'] = $this->config['accessKey'];
|
|
$response['host'] = $this->config['bucket'] . '.' . $this->config['endpoint'];
|
|
$response['policy'] = $base64_policy;
|
|
$response['signature'] = $signature;
|
|
$response['expire'] = $end;
|
|
$response['callback'] = "";
|
|
$response['dir'] = $dir; // 这个参数是设置用户上传文件时指定的前缀。
|
|
return $response;
|
|
|
|
} catch (\Exception $e) {
|
|
throw new BusinessException($e->getMessage());
|
|
}
|
|
}
|
|
|
|
/**
|
|
* @param $time
|
|
* @return string
|
|
* @throws \Exception
|
|
*/
|
|
protected function gmt_iso8601($time): string
|
|
{
|
|
return str_replace('+00:00', '.000Z', gmdate('c', $time));
|
|
}
|
|
} |