settings(); $location = ['bucket' => (string) ($config['bucket'] ?? ''), 'region' => (string) ($config['region'] ?? '')]; self::validateLocation($location); return $location; } /** $object: bucket / region / key。Content-MD5 由本地字节计算,传输损坏时 COS 直接拒收。 */ public function put(array $object, string $pdf): void { self::validateLocation($object); if (!preg_match('#^private/esign/prescription/(sandbox|production)/\d+-[a-f0-9]{64}\.pdf$#D', (string) ($object['key'] ?? ''))) { throw new DomainException('处方归档对象键无效'); } try { $this->client($object['region'])->putObject([ 'Bucket' => $object['bucket'], 'Key' => $object['key'], 'Body' => $pdf, 'ACL' => 'private', 'ContentType' => 'application/pdf', 'CacheControl' => 'private, no-store, max-age=0', 'ContentDisposition' => 'attachment; filename="prescription-signed.pdf"', 'Headers' => ['Content-MD5' => base64_encode(md5($pdf, true))], 'Metadata' => ['sha256' => hash('sha256', $pdf)], '@http' => ['connect_timeout' => 3, 'timeout' => 10, 'read_timeout' => 10, 'allow_redirects' => false], ]); } catch (\Throwable $e) { $status = method_exists($e, 'getStatusCode') ? (int) $e->getStatusCode() : 0; // 不保留原异常:其中可能带签名 URL 或密钥信息。 throw new DomainException($status === 401 || $status === 403 ? '云存储授权不可用,请检查 COS 密钥与桶权限' : '云存储暂不可用' . ($status > 0 ? "(HTTP {$status})" : '')); } } protected function settings(): array { $config = ConfigService::get('storage', 'qcloud', []); if (!is_array($config) || empty($config['access_key']) || empty($config['secret_key'])) { throw new DomainException('未配置腾讯云 COS 存储'); } return $config; } protected function client(string $region): Client { $config = $this->settings(); // 已安装 SDK 2.6.5 使用 "schema" 而非 "scheme"。 return new Client(['schema' => 'https', 'region' => $region, 'retry' => 0, 'timeout' => 10, 'connect_timeout' => 3, 'allow_redirects' => false, 'credentials' => ['secretId' => $config['access_key'], 'secretKey' => $config['secret_key']]]); } private static function validateLocation(array $object): void { if (!preg_match('/^[a-z0-9][a-z0-9-]{1,62}-[0-9]{5,20}$/D', (string) ($object['bucket'] ?? '')) || !preg_match('/^[a-z]{2}-[a-z0-9-]{2,40}$/D', (string) ($object['region'] ?? ''))) { throw new DomainException('COS 桶或地域配置无效'); } } }