企业🤖AI智能体构建引擎,智能编排和调试,一键部署,支持私有化部署方案 广告
## 阿里云盘 阿里云盘是阿里巴巴集团推出的一款个人云存储服务产品。它为用户提供了一个安全、稳定、高效的云端存储空间,用户可以在其中存储、管理和同步各种类型的文件和数据。 阿里云盘是个人和团队管理数字资产的有力工具,尤其适合需要在多设备间同步工作文件和数据的用户。 ## 开放平台 阿里云盘开放个人云存储能力,允许开发者通过对接 API 的方式,集成阿里云盘个人云存储能力到开发者的应用中。 目前开放的能力包括文件上传下载等基础文件管理能力、音视频文件的在线转码与播放等媒体在线播放能力、用户授权与信息查询等能力。 > 阿里云网盘对接文档地址:https://www.yuque.com/aliyundrive/zpfszx/gogo34oi2gy98w5d ![](https://img.kancloud.cn/37/1d/371d4d1512860717bdcf952da88e42fa_1920x1035.png) ## 接入流程 > 服务端 API 调用流程如下图所示 ![](https://img.kancloud.cn/23/1a/231aec2d4666110e1567861d26d5e2fc_821x96.png) ### 创建应用 ![](https://img.kancloud.cn/71/d6/71d634e66a476637d2b87cce506e0a7b_735x546.png) ![](https://img.kancloud.cn/f7/c6/f7c6d7b3538752b4e2b016432e7476cc_1275x606.png) > 创建应用以获取应用接入凭证,包括 `appid`、`secret` ### 编写应用 核心调用类 ``` <?php /** * @desc ADrive https://www.yuque.com/aliyundrive/zpfszx * @author Tinywan(ShaoBo Wan) * @date 2024/8/7 22:57 */ declare(strict_types=1); namespace app\common\service; use Psr\SimpleCache\InvalidArgumentException; use support\exception\BusinessException; use support\Log; use think\facade\Cache; class ADrive { const ACCESS_TOKEN = 'ADRIVE_ACCESS_TOKEN:'; /** @var array */ private array $config = []; /** @var string */ private string $http = 'https://openapi.aliyundrive.com/'; /** @var string */ private string $redirect_uri = 'http://webman2024.tinywan.com:8484/test/adrive-callback'; /** @var array */ private array $url = [ 'access_token' => 'oauth/access_token', 'authorize' => 'oauth/authorize', 'drive' => 'adrive/v1.0/user/getDriveInfo', 'create' => 'adrive/v1.0/openFile/create', 'complete' => 'adrive/v1.0/openFile/complete', 'fileList' => 'adrive/v1.0/openFile/list', 'deleteFile' => 'adrive/v1.0/openFile/recyclebin/trash', 'searchList' => 'adrive/v1.0/openFile/search', 'updateFile' => 'adrive/v1.0/openFile/update', 'starredList' => 'adrive/v1.0/openFile/starredList', 'getDownloadUrl' => 'adrive/v1.0/openFile/getDownloadUrl' ]; /** * @var PublicHttp|null */ private ?PublicHttp $publicHttp = null; /** * @param int $agencyId */ public function __construct(int $agencyId = 0) { $agencyInfo['id'] = 2024; $agencyInfo['aly_appid'] = '282392bf68014e13b5db2a2b35d9b3ce'; $agencyInfo['aly_secret'] = 'a524d58d17a44c1faaa914db460be16a'; if ($this->publicHttp == null) { $this->publicHttp = new PublicHttp(); } $this->config = $agencyInfo; } /** * @desc 登录授权 * @author Tinywan(ShaoBo Wan) */ public function authorize(): string { return $this->http . $this->url['authorize'] . '?client_id=' . $this->config['aly_appid'] . '&redirect_uri=' . $this->redirect_uri . '&scope=user:base,file:all:read,file:all:write&response_type=code&state=' . $this->config['id']; } /** * @desc getToken * @param int $type * @param string $code * @return bool|mixed|string * @throws InvalidArgumentException * @author Tinywan(ShaoBo Wan) */ public function getToken(string $code, int $type = 1) { $info = [ 'client_id' => $this->config['aly_appid'], 'client_secret' => $this->config['aly_secret'], 'grant_type' => $type == 1 ? 'authorization_code' : 'refresh_token', ]; if ($type == 1) { $info['code'] = $code; } else { if (empty($this->config['id'])) { throw new \Exception('未传入旅行社标识'); } $token = Cache::get(self::ACCESS_TOKEN . $this->config['id']); if (empty($token)) { throw new \Exception('未有阿里云盘缓存'); } $value = $token['refresh_token']; $info['refresh_token'] = $value; } $result = $this->publicHttp->postAlyFile($this->http . $this->url['access_token'], $info); Log::info('[阿里云云盘获取令牌]' . json_encode($result, JSON_UNESCAPED_UNICODE)); if (!is_array($result)) { $result = json_decode($result, true); } Cache::set(self::ACCESS_TOKEN . $this->config['id'], $result, 7200); return $result; } /** * @desc 获取阿里云盘用户drive_id * @throws \Exception * @author Tinywan(ShaoBo Wan) */ public function getUserDrive(): array { $userToken = Cache::get(self::ACCESS_TOKEN . $this->config['id']); if (empty($userToken)) { throw new \Exception('登录失效,请重新授权阿里网盘'); } $result = $this->publicHttp->postAlyFile($this->http . $this->url['drive'], [], ['Authorization:' . $userToken['token_type'] . ' ' . $userToken['access_token']]); if (!is_array($result)) { $result = json_decode($result, true); } if (empty($result['default_drive_id'])) { throw new \Exception('获取阿里云盘drive_id失败'); } Cache::set('aly_drive_' . $this->config['id'], $result['default_drive_id']); Cache::set('aly_userInfo_' . $this->config['id'], $result); return ['status' => 0, 'msg' => '获取用户drive成功', 'data' => $result['default_drive_id']]; } /** * 阿里云盘文件上传 * file_name 文件名称 * file_path 文件路径 * file_id 上传的目录 */ public function updateFile(array $input): array { $userToken = Cache::get(self::ACCESS_TOKEN . $this->config['id']); if (empty($userToken)) { throw new \Exception('登录失效,请重新授权阿里网盘'); } $drive = Cache::get('aly_drive_' . $this->config['id']); if (empty($drive)) { try { $driveInfo = $this->getUserDrive(); $drive = $driveInfo['data']; } catch (\Throwable $exception) { return ['status' => 1, 'msg' => $exception->getMessage()]; } } $fileName = $input['file_name'] . date('Y-m-d-H:i:s'); $result = $this->publicHttp->postAlyFile($this->http . $this->url['create'], [ 'drive_id' => $drive, 'parent_file_id' => empty($input['file_id']) ? 'root' : $input['file_id'], 'type' => 'file', 'check_name_mode' => 'ignore', 'name' => $fileName, ], ['Authorization:' . $userToken['token_type'] . ' ' . $userToken['access_token']]); if (!is_array($result)) { $result = json_decode($result, true); } if (empty($result['part_info_list'][0]['upload_url'])) { throw new \Exception('获取上传路径失败'); } $sourceFile = fopen($input['file_path'], "rb"); $res = $this->publicHttp->putAlyFile($result['part_info_list'][0]['upload_url'], $sourceFile, ['Authorization:' . $userToken['token_type'] . ' ' . $userToken['access_token']]); if ($res['code'] != 1) { throw new \Exception('上传文件失败'); } //上传成功后调用上传完毕 $onMsg = $this->publicHttp->postAlyFile($this->http . $this->url['complete'], [ 'drive_id' => $drive, 'file_id' => $result['file_id'], 'upload_id' => $result['upload_id'], ], ['Authorization:' . $userToken['token_type'] . ' ' . $userToken['access_token']]); if (!is_array($onMsg)) { $onMsg = json_decode($onMsg, true); } if (empty($onMsg['name'])) { throw new \Exception('同步阿里云网盘失败'); } return ['status' => 0, 'msg' => '上传文件成功', 'file_id' => $result['file_id']]; } /** * 新建文件夹 * file_name 文件夹名称 * file_type =1 不追加日期 =2追加日期 **/ public function addFile($input) { $userToken = Cache::get(self::ACCESS_TOKEN . $this->config['id']); if (empty($userToken)) { throw new \Exception('登录失效,请重新授权阿里网盘'); } $drive = Cache::get('aly_drive_' . $this->config['id']); if (empty($drive)) { try { $driveInfo = $this->getUserDrive(); $drive = $driveInfo['data']; } catch (\Throwable $exception) { return ['status' => 1, 'msg' => $exception->getMessage()]; } } $list = [ 'drive_id' => $drive, 'parent_file_id' => empty($input['file_id']) ? 'root' : $input['file_id'], 'type' => 'folder', 'check_name_mode' => 'ignore', 'name' => ($input['file_type'] == 1 ? '' : $input['file_name'] . '-时间:' . date('Y-m-d H:i:s')) ]; $result = $this->publicHttp->postAlyFile($this->http . $this->url['create'], $list, ['Authorization:' . $userToken['token_type'] . ' ' . $userToken['access_token']]); if (!is_array($result)) { $result = json_decode($result, true); } if (empty($result['file_id'])) { return ['status' => 1, 'msg' => '新建文件失败']; } return ['status' => 0, 'msg' => '操作成功', 'file_id' => $result['file_id']]; } /** * 获取文件夹列表 * limit 最大数量 50-100 * marker 分页标记 * parent_file_id root 等于根目录 否则传入文件列表ID * order_by 排序字段 updated_at created_at name size * order_direction DESC ASC * */ public function fileList($input) { $userToken = Cache::get(self::ACCESS_TOKEN . $this->config['id']); if (empty($userToken)) { throw new \Exception('登录失效,请重新授权阿里网盘'); } $drive = Cache::get('aly_drive_' . $this->config['id']); if (empty($drive)) { try { $driveInfo = $this->getUserDrive(); $drive = $driveInfo['data']; } catch (\Throwable $exception) { return ['status' => 1, 'msg' => $exception->getMessage()]; } } $list = [ 'drive_id' => $drive, 'order_by' => empty($input['order_by']) ? 'updated_at' : $input['order_by'], 'order_direction' => empty($input['order_direction']) ? 'DESC' : $input['order_direction'], 'parent_file_id' => empty($input['parent_file_id']) ? 'root' : $input['parent_file_id'], 'type' => 'all', 'limit' => (int)$input['limit'], 'fields' => '*' ]; if (!empty($input['marker'])) { $list['marker'] = $input['marker']; } $result = $this->publicHttp->postAlyFile($this->http . $this->url['fileList'], $list, ['Authorization:' . $userToken['token_type'] . ' ' . $userToken['access_token']]); if (!is_array($result)) { $result = json_decode($result, true); } foreach ($result['items'] as &$value) { $value['created_at'] = date('Y-m-d H:i:s', strtotime($value['created_at'])); $value['updated_at'] = date('Y-m-d H:i:s', strtotime($value['updated_at'])); $value['show_ico'] = false; if ($value['type'] == 'folder') { $value['type_name'] = '文件夹'; } else { $value['type_name'] = '文件'; } } return ['status' => 0, 'rows' => $result['items'], 'next_marker' => $result['next_marker']]; } /** * @desc 文件名称 * keyword 文件名称 * limit 条数 * @param array $input * @return array * @throws \Exception * @author Tinywan(ShaoBo Wan) */ public function searchList(array $input) { $userToken = Cache::get(self::ACCESS_TOKEN . $this->config['id']); if (empty($userToken)) { throw new \Exception('登录失效,请重新授权阿里网盘'); } $drive = Cache::get('aly_drive_' . $this->config['id']); if (empty($drive)) { try { $driveInfo = $this->getUserDrive(); $drive = $driveInfo['data']; } catch (\Throwable $exception) { return ['status' => 1, 'msg' => $exception->getMessage()]; } } $list = [ 'drive_id' => $drive, 'limit' => (int)$input['limit'], 'fields' => '*', 'query' => 'name match "' . $input['keyword'] . '"' ]; if (!empty($input['marker'])) { $list['marker'] = $input['marker']; } $result = $this->publicHttp->postAlyFile($this->http . $this->url['searchList'], $list, ['Authorization:' . $userToken['token_type'] . ' ' . $userToken['access_token']]); if (!is_array($result)) { $result = json_decode($result, true); } foreach ($result['items'] as &$value) { $value['created_at'] = date('Y-m-d H:i:s', strtotime($value['created_at'])); $value['updated_at'] = date('Y-m-d H:i:s', strtotime($value['updated_at'])); $value['show_ico'] = false; if ($value['type'] == 'folder') { $value['type_name'] = '文件夹'; } else { $value['type_name'] = '文件'; } } return ['status' => 0, 'rows' => $result['items'], 'next_marker' => $result['next_marker']]; } /** * @desc 获取收藏列表 * @param $input * @return array * @throws BusinessException|InvalidArgumentException * @author Tinywan(ShaoBo Wan) */ public function starredList($input): array { $userToken = Cache::get(self::ACCESS_TOKEN . $this->config['id']); if (empty($userToken)) { throw new BusinessException('登录失效,请重新授权阿里网盘'); } $drive = Cache::get('aly_drive_' . $this->config['id']); if (empty($drive)) { try { $driveInfo = $this->getUserDrive(); $drive = $driveInfo['data']; } catch (\Throwable $exception) { return ['status' => 1, 'msg' => $exception->getMessage()]; } } $list = [ 'drive_id' => $drive, 'order_by' => empty($input['order_by']) ? 'updated_at' : $input['order_by'], 'order_direction' => empty($input['order_direction']) ? 'DESC' : $input['order_direction'], 'limit' => (int)$input['limit'], ]; if (!empty($input['marker'])) { $list['marker'] = $input['marker']; } $result = $this->publicHttp->postAlyFile($this->http . $this->url['starredList'], $list, ['Authorization:' . $userToken['token_type'] . ' ' . $userToken['access_token']]); if (!is_array($result)) { $result = json_decode($result, true); } foreach ($result['items'] as &$value) { $value['created_at'] = date('Y-m-d H:i:s', strtotime($value['created_at'])); $value['updated_at'] = date('Y-m-d H:i:s', strtotime($value['updated_at'])); $value['show_ico'] = false; if ($value['type'] == 'folder') { $value['type_name'] = '文件夹'; } else { $value['type_name'] = '文件'; } } return ['status' => 0, 'rows' => $result['items'], 'next_marker' => $result['next_marker']]; } /** * @desc 文件重命名或收藏 * @param $input * @return array * @throws \Exception|InvalidArgumentException * @author Tinywan(ShaoBo Wan) */ public function fileRename($input) { $userToken = Cache::get(self::ACCESS_TOKEN . $this->config['id']); if (empty($userToken)) { throw new \Exception('登录失效,请重新授权阿里网盘'); } $drive = Cache::get('aly_drive_' . $this->config['id']); if (empty($drive)) { try { $driveInfo = $this->getUserDrive(); $drive = $driveInfo['data']; } catch (\Throwable $exception) { return ['status' => 1, 'msg' => $exception->getMessage()]; } } $list = [ 'drive_id' => $drive, 'file_id' => $input['file_id'], 'name' => $input['name'], 'starred' => $input['starred'] ]; $result = $this->publicHttp->postAlyFile($this->http . $this->url['updateFile'], $list, ['Authorization:' . $userToken['token_type'] . ' ' . $userToken['access_token']]); if (!is_array($result)) { $result = json_decode($result, true); } if (empty($result['file_id'])) { return ['status' => 1, 'msg' => '操作失败']; } return ['status' => 0, 'msg' => '操作成功']; } /** * @desc 放入回收站 * @param array $input * @return array * @throws \Exception * @author Tinywan(ShaoBo Wan) */ public function deleteFile(array $input): array { $userToken = Cache::get(self::ACCESS_TOKEN . $this->config['id']); if (empty($userToken)) { throw new \Exception('登录失效,请重新授权阿里网盘'); } $drive = Cache::get('aly_drive_' . $this->config['id']); if (empty($drive)) { try { $driveInfo = $this->getUserDrive(); $drive = $driveInfo['data']; } catch (\Throwable $exception) { return ['status' => 1, 'msg' => $exception->getMessage()]; } } $this->publicHttp->postAlyFile($this->http . $this->url['deleteFile'], [ 'drive_id' => $drive, 'file_id' => $input['file_id'] ], ['Authorization:' . $userToken['token_type'] . ' ' . $userToken['access_token']]); return ['status' => 0, 'msg' => '放入成功']; } /** * @desc 获取下载链接 * @param array $input * @return array * @throws \Exception * @throws InvalidArgumentException * @author Tinywan(ShaoBo Wan) */ public function getDownloadUrl(array $input): array { $userToken = Cache::get(self::ACCESS_TOKEN . $this->config['id']); if (empty($userToken)) { throw new \Exception('登录失效,请重新授权阿里网盘'); } $drive = Cache::get('aly_drive_' . $this->config['id']); if (empty($drive)) { try { $driveInfo = $this->getUserDrive(); $drive = $driveInfo['data']; } catch (\Throwable $exception) { return ['status' => 1, 'msg' => $exception->getMessage()]; } } $list = [ 'drive_id' => $drive, 'file_id' => $input['file_id'], ]; $result = $this->publicHttp->postAlyFile($this->http . $this->url['getDownloadUrl'], $list, ['Authorization:' . $userToken['token_type'] . ' ' . $userToken['access_token']]); if (!is_array($result)) { $result = json_decode($result, true); } if (empty($result['url'])) { return ['status' => 1, 'msg' => '获取下载链接失败']; } return ['status' => 0, 'msg' => '操作成功', 'url' => $result['url']]; } } ``` 简单请求类 ``` <?php /** * @desc PublicHttp.php 描述信息 * @author Tinywan(ShaoBo Wan) * @date 2024/8/7 23:05 */ declare(strict_types=1); namespace app\common\service; class PublicHttp { /** * @desc postAlyFile * @param string $_url * @param array $params * @param array $header * @return bool|string * @author Tinywan(ShaoBo Wan) */ public function postAlyFile(string $_url, array $params,array $header=[]) { $headerArray = array("Content-Type:application/json;charset=utf-8", "Accept:application/json"); if (!empty($header)) { $headerArray = array_merge($headerArray, $header); } $ch = curl_init(); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE); curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE); curl_setopt($ch, CURLOPT_URL, $_url); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_HEADER, 0); curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (compatible; MSIE 5.01; Windows NT 5.0)'); curl_setopt($ch, CURLOPT_TIMEOUT, 15); curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($params)); curl_setopt($ch, CURLOPT_HTTPHEADER, $headerArray); $output = curl_exec($ch); curl_close($ch); return $output; } /** * @desc put请求 * @param string $url * @param $sourceFile * @param array $headerArr * @param int $timeout * @return array * @author Tinywan(ShaoBo Wan) */ function putAlyFile(string $url, $sourceFile, array $headerArr = [], int $timeout = 30): array { $ch = curl_init(); //初始化curl curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); //返回字符串,而不直接输出 curl_setopt($ch, CURLOPT_URL, $url); //设置put到的url curl_setopt($ch, CURLOPT_HTTPHEADER, $headerArr); curl_setopt($ch, CURLOPT_TIMEOUT, $timeout); curl_setopt($ch, CURLOPT_HEADER, 1); // 启用时会将头文件的信息作为数据流输出。 curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'PUT'); //设置请求方式 curl_setopt($ch, CURLOPT_PUT, true); //设置为PUT请求 curl_setopt($ch, CURLOPT_INFILE, $sourceFile); //设置资源句柄 $response = curl_exec($ch); if ($error = curl_error($ch)){ $bkArr = array( 'code' => 0, 'msg' => $error, ); } else{ $bkArr = array( 'code' => 1, 'msg' => 'ok', 'data' => $response ); } curl_close($ch); // 关闭 cURL 释放资源 return $bkArr; } } ``` ### 调用编写 获取授权码 ```php /** * @desc: 获取授权码 * @param Request $request * @return Response * @author Tinywan(ShaoBo Wan) */ public function authorize(Request $request): Response { $aDriver = new ADrive(); return redirect($aDriver->authorize()); } ``` 回调配置参考 ``` /** * @param Request $request * @return Response * @throws InvalidArgumentException * @author Tinywan(ShaoBo Wan) */ public function aDriveCallback(Request $request): Response { Log::info('[请求回调参数]:'.json_encode($request->get())); $code = $request->get()['code']; $aDriver = new ADrive(); $token = $aDriver->getToken($code); Log::info('[获取访问凭证 (access_token)]:'.json_encode($token)); return response_json(200, '请求成功',['token'=>$token]); } ``` > 以上回调地址必须可以通过公网访问的到。我这里配置的回调地址是`http://webman2024.tinywan.com:8484/test/adrive-callback` 令牌响应格式为: ```json { "token_type": "Bearer", "access_token": "eyJraWQiOiJxxxxxxxxxxxx", "refresh_token": "eyJ0eXAxxxxxxxxxxxxxxmt7WOaMbEXVWNKJdw", "expires_in": 7200 } ``` > 阿里云盘开放平台使用 OAuth 2.0 授权标准,接入前请阅读。https://www.yuque.com/aliyundrive/zpfszx/rgg2p1qnsfdux61r?singleDoc# ### 授权应用 > 获取授权页面链接:http://webman2024.tinywan.com:8484/test/authorize ![](https://img.kancloud.cn/2c/20/2c20df206f059c1d44a7c8aadb2ebbec_408x829.png) 浏览器打开链接后使用阿里云网盘扫码授权成功后,回调获取用户信息就可以直接调用用户的阿里云网盘功能. ## 上传文件 ``` /** * @desc 文件上传 * @param Request $request * @return Response * @throws \Exception * @author Tinywan(ShaoBo Wan) */ public function uploadFile(Request $request): Response { $aDriver = new ADrive(); $param = [ 'file_name' => '开源技术小栈-文件上传测试', 'file_path' => runtime_path().DIRECTORY_SEPARATOR.'swoole.jpg', ]; $res = $aDriver->updateFile($param); Log::info('[文件上传-响应结果] '.json_encode($res)); return response_json(200, '请求成功',$res); } ``` 响应结果 ```json { "code": 200, "msg": "请求成功", "data": { "status": 0, "msg": "上传文件成功", "file_id": "66b5b06c8e278ff7d300479fac0fb623fdfe299a" } } ``` > 云盘上传结果 ![](https://img.kancloud.cn/04/bc/04bcff830956c4689af65daebc63b05d_1278x576.png)