使用官方的案例https://github.com/tencentyun/cos-wx-sdk-v5/tree/master/demo,在服务器用PHPSDK,前端用官方提供的小程序demo,上传图片的例子,PHP部分代码如下
$config = array(
'url' => 'https://sts.tencentcloudapi.com/',
'domain' => 'sts.tencentcloudapi.com',
'proxy' => '',
'secretId' => 'XXXXXXXXXX', // 固定密钥
'secretKey' => 'XXXXXXXXXXX', // 固定密钥
'bucket' => 'testpic-1-1304602719', // 换成你的 bucket
'region' => 'ap-nanjing', // 换成 bucket 所在园区
'durationSeconds' => 1800, // 密钥有效期
'allowPrefix' => '*', // 这里改成允许的路径前缀,可以根据自己网站的用户登录态判断允许上传的目录,例子:* 或者 a/* 或者 a.jpg
'allowActions' => array (
'name/cos:PutObject',
'name/cos:PostObject',
'name/cos:GetService',
)
);
在小程序端也设置了域名白名单,官方demo中上传图片和上传对象cos.postObject都能用
但后面的getService报403错误,请问可能的原因是?
小程序端调用getService方法如下:
cos.getService(function(err, data) {
console.log(err || data);
});
微信开发者工具调试器中打印的信息
VM8 asdebug.js:1 GET https://service.cos.myqcloud.com/ 403 (Forbidden)
getService返回的错误对象,展开如下:
- error:
- Code: "AccessDenied"
- Message: "Access Denied."
- RequestId: "NjA4MTYyOGRfNmNhYjM1MGFfYTdkMF8xMDk3ZWEz"
- Resource: "service.cos.myqcloud.com"
- ServerTime: "2021-04-22T11:48:29Z"
- TraceId: "OGVmYzZiMmQzYjA2OWNhODk0NTRkMTBiOWVmMDAxODczNTBmNjMwZmQ0MTZkMjg0NjlkNTYyNmY4ZTRkZTk0N2JhNjliNmJjMDIyZWRiYmEyNmViMzk5YWU1NjZiN2JlYmZmYmI4OWFjNjNhNGI1ZTRhMDkzNjY3N2RlMTM3ZDI="
- __proto__: Object
- headers:
- connection: "keep-alive"
- content-length: "472"
- content-type: "application/xml"
- date: "Thu, 22 Apr 2021 11:48:29 GMT"
- server: "tencent-cos"
- x-cos-request-id: "NjA4MTYyOGRfNmNhYjMXXXXXXXXXXXk3ZWEz"
- x-cos-trace-id: "OGVmYzZiMmQzYjA2OWNhOXXXXXXXXXXXXXDcz