编辑代码

<?php 
function dogecloud_api($apiPath, $data = array(), $jsonMode = false) {
    // 这里替换为你的 DogeCloud 永久 AccessKey 和 SecretKey,可在用户中心 - 密钥管理中查看
    $accessKey = '26a84c12';
    $secretKey = 'c698';

    $body = $jsonMode ? json_encode($data) : http_build_query($data);
    $signStr = $apiPath . "\n" . $body;
    $sign = hash_hmac('sha1', $signStr, $secretKey);
    $Authorization = "TOKEN " . $accessKey . ":" . $sign;

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, "https://api.dogecloud.com" . $apiPath);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 1); // 如果是本地调试,或者根本不在乎中间人攻击,可以把这里的 1 和 2 修改为 0,就可以避免报错
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2); // 建议实际使用环境下 cURL 还是配置好本地证书
    if(isset($data) && $data){
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $body);
        curl_setopt($ch, CURLOPT_HTTPHEADER, array(
            'Content-Type: ' . ($jsonMode ? 'application/json' : 'application/x-www-form-urlencoded'),
            'Authorization: ' . $Authorization
        ));
    }
    $ret = curl_exec($ch);
    curl_close($ch);
    return json_decode($ret, true);
}

// 该 API 参考文档: https://docs.dogecloud.com/oss/api-tmp-token
$api = dogecloud_api('/auth/tmp_token.json', array(
    "channel" => "OSS_FULL",
    "scopes" => array("*")
), true);
// 这里推荐使用 Redis 之类的缓存将获取到的临时密钥缓存下来,两小时内有效

if ($api && $api['code'] == 200) {
    $credentials = $api['data']['Credentials'];
} else {
    // 失败
}


use Aws\S3\S3Client;
use Aws\Exception\AwsException;
$s3Client = new S3Client([
    'region'          => 'automatic',
    'version'         => '2006-03-01',
    'endpoint'        => 'https://cos.ap-guangzhou.myqcloud.com', // 这里替换为需要操作的存储空间的 s3Endpoint 值,控制台存储空间 SDK 参数选项卡中可以找到,
                                                     // 上面获取临时密钥时 $api['data']['Buckets'] 中也有各空间的 s3Endpoint 值
    'credentials' => [
        'key' => $credentials['accessKeyId'],
        'secret' => $credentials['secretAccessKey'],
        'token' => $credentials['sessionToken']
    ]
]);