TencentCosService.php 2.7 KB
<?php

namespace App\Services;

use GuzzleHttp\Client;
use Illuminate\Http\Request;
use Illuminate\Support\Str;

/**
 * @remark :腾讯cos上传
 * @class  :TencentCosService.php
 * @author :lyh
 * @time   :2023/7/18 16:46
 */
class TencentCosService extends BaseService
{
    public $cos = [];//cos配置

    public $method = '';//请求方式

    public $time = 86400;//签名有效时间

    public $config = [
        'cosRegion' => 'COS_REGION', // 存储桶地域
        'appId' => 'COS_APP_ID', // 腾讯云应用ID
        'secretId' => 'COS_SECRET_ID', // 腾讯云API的SecretId
        'secretKey' => 'COS_SECRET_KEY', // 腾讯云API的SecretKey
        'bucket' => 'COS_BUCKET', // 存储桶名称
    ];

    public function __construct(){
        $this->cos = config('filesystems.disks.cos');
        $this->config['cosRegion'] = $this->cos['region'];
        $this->config['appId'] = $this->cos['credentials']['appId'];
        $this->config['secretId'] = $this->cos['credentials']['secretId'];
        $this->config['secretKey'] = $this->cos['credentials']['secretKey'];
        $this->config['bucket'] = $this->cos['bucket'];
    }

    /**
     * @remark :上传图片
     * @name   :uploadToCos
     * @author :lyh
     * @method :post
     * @time   :2023/7/19 14:47
     */
    public function uploadToCos($path,$filename)
    {
        $objectKey = $path.'/'.$filename;
        // 上传到腾讯云 COS
        $httpClient = new Client();
        $response = $httpClient->request('PUT', "https://{$this->config['bucket']}.cos.{$this->config['cosRegion']}.myqcloud.com{$objectKey}", [
            'body' => file_get_contents(config('filesystems.disks.upload')['root'].$objectKey),
            'headers' => $this->generateHeaders($this->config['secretId'], $this->config['secretKey']),
        ]);
        // 若上传成功,则返回上传后的 URL
        var_dump($response);
        die();
        if ($response->getStatusCode() === 200) {
            return "https://{$this->config['bucket']}.cos.{$this->config['cosRegion']}.myqcloud.com{$objectKey}";
        }
        return null;
    }

    /**
     * @remark :签名
     * @name   :generateHeaders
     * @author :lyh
     * @method :post
     * @time   :2023/7/19 14:47
     */
    private function generateHeaders($secretId, $secretKey)
    {
        $keyTime = time() - 1 . ';' . (time() + 300);
        $signKey = hash_hmac('sha1', $keyTime, $secretKey);
        $signature = hash_hmac('sha1', "sha1\n{$keyTime}\n\n", $signKey);
        return [
            'Authorization' => 'q-sign-algorithm=sha1&q-ak=' . $secretId . '&q-sign-time=' . $keyTime
                . '&q-key-time=' . $keyTime . '&q-signature=' . $signature,
        ];
    }
}