TencentCosService.php 3.1 KB
<?php

namespace App\Services;

/**
 * @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   :upload
     * @author :lyh
     * @method :post
     * @time   :2023/7/18 16:56
     */
    public function upload_image($path,$fileName){
        // 构建请求URL
        $pathname = '/'.$this->config['bucket'].$path.'/'.$fileName;
        $signature = $this->generateSignature($path.'/'.$fileName);
        $url = 'https://'.$this->config['bucket'].'.cos.'.$this->config['cosRegion'].'.myqcloud.com'.$pathname.'?sign='.$signature;
        // 打开文件流
        $url_path = config('filesystems.disks.upload')['root'].$path.'/'.$fileName;
        $fileContent = file_get_contents($url_path);
        return $this->http_put($url,$fileContent);
    }

    /**
     * @remark :上传文件到第三方
     * @name   : (http_put
     * @author :lyh
     * @method :post
     * @time   :2023/7/18 17:06
     */
    public function http_put($url,$fileContent){
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'PUT');
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $fileContent);
        $response = curl_exec($ch);
        curl_close($ch);
        // 检查上传结果
        if ($response === false) {
            echo '图片上传失败';
        } else {
            var_dump($response);
            die();
            echo '图片上传成功';
        }
    }

    /**
     * @remark : 构造腾讯云 COS 授权签名
     * @name   :cosAuthorization
     * @author :lyh
     * @method :post
     * @time   :2023/7/18 17:10
     */
    public function generateSignature($path) {
        $signTime = time();
        $expiredTime = time() + 3600;
        $plainText =
            'a='.$this->config['appId'].'&b='.$this->config['bucket']. '&k='.$this->config['secretId'].'&e='.$expiredTime.'&t='.$signTime.'&r='.rand().'&f='.$path;
        $sign = base64_encode(hash_hmac('SHA1', $plainText, $this->config['secretKey'], true).$plainText);
        return $sign;
    }
}