php对接百度网盘开发平台API开发高级实战案例解析:(环境部署、php封装类、Access Token获取、预上传、分片上传)


前言

在这里插入图片描述

百度网盘是国民级的个人云盘产品,有着先进安全的云存储与传输技术,通过多年积累沉淀的解决方案,来满足不同行业不同阶段合作伙伴的个性化需求,降低开发和购买成。在开放平台,你可以方便快捷地实现应用、设备与百度网盘的连接互通:数据的上传、网盘文件的管理与下载、场景化的影音与相册服务、开发一个小程序入驻网盘等等能力。

传送门 >> 百度网盘开放平台


一、环境部署

1.封装BdPan类库

封装BdPan.php百度网盘开发类;

class BdPan
{
    
    
    const AppID = '303***';
    const Appkey = 'zsBbkMiTO5L86FST***';
    const Secretkey = 'RHwNALMZcLWjluHn***';
    const RedirectUri = 'http://test.com/pan/getcode.php';

    //构造函数
    public function __construct($AppID = '', $Appkey = '', $Secretkey = '')
    {
    
    
        $AppID = self::AppID;
        $Appkey = self::Appkey;
        $Secretkey = self::Secretkey;
        //核检常量参数
        $this->check_auth($AppID, $Appkey, $Secretkey);
    }

    //判断Appkey是否为空
    public function check_auth($AppID, $Appkey, $Secretkey)
    {
    
    
        if ($AppID == '') {
    
    
            die('AppID不能为空');
        }
        if ($Appkey == '') {
    
    
            die('Appkey不能为空');
        }
        if ($Secretkey == '') {
    
    
            die('Secretkey不能为空');
        }
    }
}

2.回调地址配置

http://test.com/pan/getcode.php,为回调地址:
在这里插入图片描述
说明:

  • 授权回调地址支持配置多个,多个地址之间,通过英文逗号进行分隔
  • 授权回调地址修改后在 1 小时后生效;
  • 对于有 server的应用,您必须配置授权回调地址,用以 OAuth2.0 检验授权请求中的 “redirect_uri” 参数。以便保证 OAuth2.0在回调过程中,会回调到安全域名。
  • 也可传redirect_uri=oob。回调后会返回一个平台提供默认回调地址:http://openapi.baidu.com/oauth/2.0/login_success。

二、获取授权码Code

发起授权码 Code 请求,获取用户授权码 Code。

1.手动获取Code

配置链接,格式如下:

    //获取授权码
    public function getCode()
    {
    
    
        $state = md5(md5(time()));
        $url = 'http://openapi.baidu.com/oauth/2.0/authorize?response_type=code&client_id=' . self::Appkey . '&redirect_uri=' . self::RedirectUri . '&scope=basic,netdisk&state=' . $state;
        header("Location:" . $url);
    }
require_once "BdPan.php";
//实例化
$pan = new BdPan();
$token = $pan->makeToken();
echo $token;

如浏览器为正常使用百度账户登录,出现下面界面:
在这里插入图片描述
redirect uri 值为"oob"

  • 对于采用 Authentication Code方式(即适用于绝大部分WEB/WAP网站获取access token)获取access token,如果redirect uri地址为 “oob”,那么我们会有单独的页面展示授权码,方便用户手动复制粘贴,到第三方应用中的授权码输入框中,以便获取access token。
  • 对于采用 Implicit Grant方式(即适用于javascript等应用获取access token)获取access token,如果redirect uri地址为"oob",那么我们会提供一个单独的地(http://openapi.baidu.com/oauth/2.0/login_success),后面加#号跟上相应的返回参数。

2.生成本地token

web端获取Code,以PHP为例:

 //生成本地令牌token
    public function makeToken()
    {
    
    
        $code = $_GET['code'];
        if (empty($code)) {
    
    
            die('授权失败');
        }
        $url = 'https://openapi.baidu.com/oauth/2.0/token?grant_type=authorization_code&code=' . $code . '&client_id=' . self::Appkey . '&client_secret=' . self::Secretkey . '&redirect_uri=' . self::RedirectUri;
        //保存为本地文件;
        $res = json_decode(self::httpGet($url), true);
        $data = array();
        $data['access_token'] = $res['access_token'];
        $data['refresh_token'] = $res['refresh_token'];
        $data['expires_in'] = $res['expires_in'];
        $data['expires'] = time() + $res['expires_in'];
        $jsonStr = json_encode($data);
        $fp = fopen("./data/access_token.json", "w");
        fwrite($fp, $jsonStr);
        fclose($fp);
        return $jsonStr;
    }

3.读取AccessToken凭证

 /**
     * 读取本地$access_token
     */
    public function getToken()
    {
    
    
        $file = file_get_contents("./data/access_token.json", true);
        $result = json_decode($file, true);
        if ($result['access_token'] == NULL || time() > $result['expires']) {
    
    
            //过期或不存在时,再次生成新的$code
            //header("Location:./index.php");
        } else {
    
    
            return $result['access_token'];
        }
    }

4.爬虫函数

爬取函数

   private function httpGet($url)
    {
    
    
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($curl, CURLOPT_TIMEOUT, 500);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, true);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, true);
        curl_setopt($curl, CURLOPT_URL, $url);
        $res = curl_exec($curl);
        curl_close($curl);
        return $res;
    }

RequestBody参数传递

public function curlPost($url, $data = array())
    {
    
    
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        $output = curl_exec($ch);
        curl_close($ch);
        return $output;
    }

二、简化模式授权

简化模式不需要获取授权码 Code,直接获取 Access Token 凭证。简化模式不支持刷新 Access Token,过期后需用户重新登录授权。简化模式适用于无 server 端配合的应用。

平台提供了一种默认的redirect uri参数为 “oob”,回调后会返回一个平台提供默认回调地址(http://openapi.baidu.com/oauth/2.0/login_success ),例如:

http://openapi.baidu.com/oauth/2.0/login_success#expires_in=86400&access_token=1.79b233866fb427d6bb7f0651947b5591.86400.1311151425.3238112329-131640&session_secret=1c07e054952628711b61228f44f46332&session_key=9XMZMoWRoE6Or%2BHLlFGhB1%2FBH2l3Jzi2CLOxIVVbcAMnUT8tyKeNiyF6oPQESDa9UTcD0uYuYtULwe3LbqKNvc90wOkY&scope=basic

三、网盘基础服务

1.获取用户信息

    public function getUserInfo()
    {
    
    
        $access_token = $this->getToken();
        $user_info = 'https://pan.baidu.com/rest/2.0/xpan/nas?method=uinfo&access_token=' . $access_token;
        return self::httpGet($user_info);
    }

2.获取网盘容量信息

    public function getQuota()
    {
    
    
        $access_token = $this->getToken();
        $user_info = 'https://pan.baidu.com/api/quota?access_token=' . $access_token;
        return self::httpGet($user_info);
    }

3.递归获取文件列表

    public function getDirList()
    {
    
    
        $access_token = $this->getToken();
        $res = 'https://pan.baidu.com/rest/2.0/xpan/file?method=list&access_token=' . $access_token;
        return self::httpGet($res);
    }

4.预上传

    //
    public function precreate()
    {
    
    
        $access_token = $this->getToken();
        $data = array(
            'path' => '/apps/1.pdf',
            'size' => filesize("upload/1.pdf"),
            'rtype' => 3,
            'isdir' => 0,
            'autoinit' => 1,
            'block_list' => json_encode([md5('1.pdf')])
        );

        $url = 'https://pan.baidu.com/rest/2.0/xpan/file?method=precreate&access_token=' . $access_token;
        return $this->curlPost($url, $data);
    }

5.分片上传

    //
    public function superfile()
    {
    
    
        $access_token = $this->getToken();
        $params = json_decode($this->precreate(), true);
        $data = [
            'type' => 'tmpfile',
            'path' => $params['path'],
            'uploadid' => $params['uploadid'],
            'partseq' => 0,
            'block_list' => json_encode([md5('1.pdf')])//分片上传必须参数
        ];
        //拼接url
        $url = 'https://d.pcs.baidu.com/rest/2.0/pcs/superfile2?method=upload&access_token=' . $access_token . '&';
        $url .= http_build_query($data);
        $file = ['upload/1.pdf'];//本地要上传的文件
        return $this->curlPost($url, $file);
    }

6.创建文件

   //创建文件
    public function createfile()
    {
    
    
        $access_token = $this->getToken();
        $params = json_decode($this->precreate(), true);
        $params2 = json_decode($this->superfile(), true);
        $data = [
            'path' => $params['path'],
            'size' => filesize("upload/1.pdf"),
            'isdir' => 0,
            'rtype' => 3,
            'block_list' => json_encode([$params2["md5"]]),
            'uploadid' => $params['uploadid']
        ];
        $url = 'https://pan.baidu.com/rest/2.0/xpan/file?method=create&access_token=' . $access_token;
        return $this->curlPost($url, $data);
    }

成功响应返回参数:
在这里插入图片描述


总结

  1. 其中创建文件部分在实际开发中未成功,一直提示errno=2,即参数错误。当注释掉size时,会正常返回参数,但是上传文件却是0B;
    在这里插入图片描述
        $data = [
            'path' => $params['path'],
            //'size' => filesize("upload/1.pdf"),
            'isdir' => 0,
            'rtype' => 3,
            'block_list' => json_encode([$params2["md5"]]),
            'uploadid' => $params['uploadid']
        ];
  1. 翻阅了CSDN和php相关的百度网盘开发,尚未找出对应的解决方案;百度开发平台的技术文档也几经咀嚼,仍一无所获。
  2. 为了不影响正常的开发进度,暂时留坑吧。

@漏刻有时

猜你喜欢

转载自blog.csdn.net/weixin_41290949/article/details/129346074