使用访问令牌将文件上传到Google Drive,需要什么范围的身份验证


Upload file to Google Drive using access token, What scope of authentication is required?

我正在尝试用PHP将文件上传到Google Drive。

对于授权代码,我使用以下范围:

https://www.googleapis.com/auth/drive  
https://docs.google.com/feeds/  
https://docs.googleusercontent.com/  
https://spreadsheets.google.com/feeds/  

我已经收到了一个有效的refresh_token,我可以随时使用它来获取新的access_token

现在的问题是,当我试图使用这个access_token执行上传时(它没有被释放,也还没有被使用),它说:

stdClass Object
(
    [error] => stdClass Object
        (
            [errors] => Array
                (
                    [0] => stdClass Object
                        (
                            [domain] => global
                            [reason] => required
                            [message] => Login Required
                            [locationType] => header
                            [location] => Authorization
                        )
                )
            [code] => 401
            [message] => Login Required
        )
)

我使用卷曲与以下标题:

Array
(
    [0] => Content-Type: text/plain
    [1] => Content-Length: 503242
    [2] => Authorization: Bearer ya29.AHES6ZRWXZkZDDi6AFV9PK2QonHp93nIfJbYqipXFT1uCsg
    [3] => GData-Version: 3.0
)

以下URL:

https://www.googleapis.com/upload/drive/v2/files?uploadType=media

CURL命令类似于:

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HTTPHEADERS, $headers);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, file_get_contents($file));
$return = curl_exec($ch);
curl_close($ch);

如有任何帮助,我们将不胜感激。。。提前感谢。。。

您需要将文件上传到驱动器的唯一OAuth作用域是https://www.googleapis.com/auth/drive.file

对于所有可能的作用域,请查看文档:https://developers.google.com/drive/scopes

顺便说一下,Drive API不是基于GData的,因此您不需要将GData-Version头添加到请求中。

我还建议您将您的请求与OAuth 2.0 Playground发送的请求进行比较,以便更容易发现错误:

https://developers.google.com/oauthplayground/

尝试使用以下范围:https://www.googleapis.com/auth/drive.file

还要验证您是否已经完全完成了文档中给出的步骤

https://developers.google.com/drive/about-auth

如果你不想使用卷曲。您可以使用Googlephpclientlibary的插入方法来插入文件。

否则,将请求与Claudio 提到的OauthPlayground进行比较

CURLOPT_HTTPHEADER,而不是CURLOPT-HTTPHEADERS