我正试图用Google (https://github.com/google/google-api-php-client)上传图片,但我似乎无法做到这一点。每当我运行它时,它都会给我一个401 Login Required错误。这是我的代码:
功能:
public function __construct()
{
$this->instance = new \Google_Client();
$this->instance->setApplicationName('DPStatsBot');
$this->instance->setDeveloperKey(Config::getInstance()->getDriveDeveloperKey());
$this->instance->addScope('https://www.googleapis.com/auth/drive');
$this->drive_instance = new \Google_Service_Drive($this->instance);
}
public function upload($image, $dpname)
{
$file = new \Google_Service_Drive_DriveFile();
$file->setTitle($dpname . '_' . RandomString::string());
$upload = $this->drive_instance->files->insert($file,
[
'data' => $image,
'mimeType' => 'image/jpg',
'uploadType' => 'media'
]);
return $upload;
}对职能的调用:
$client = new DriveClient();
foreach($dm->entities->media as $img)
{
Printer::write('Recieved image from "' . $dm->sender->screen_name . '", saving to Drive...');
$client->upload($this->getImage($img->media_url), $dm->sender->screen_name);
}错误:
Fatal error: Uncaught exception 'Google_Service_Exception' with message 'Error c
alling POST https://www.googleapis.com/upload/drive/v2/files?uploadType=multipar
t&key=APIKEYHERE: (401) Login Required' in C:\Doesp
lay\DPStatsBot\vendor\google\apiclient\src\Google\Http\REST.php:110我使用的API密钥来自APIs & auth->Credentials下的,它是一个公共API密钥。
任何帮助都将不胜感激!
谢谢
编辑: DriveClient是包含函数的类
发布于 2015-06-26 12:23:50
公共api密钥用于公共访问api。不属于用户的数据。您需要从web应用程序创建客户端id。
然后您将能够使用Oauth2对其进行身份验证。
这可能会让你开始。驱动Quickstart php
如何知道何时需要进行身份验证:
需要授权
如果文档中说需要身份验证,那么必须对您进行身份验证才能访问该调用。
文件父级
检查$parentId变量,这就是如何将文件上传到特定目录,如果不添加setParents,它将被上传到根文件夹中。代码从
/**
* Insert new file.
*
* @param Google_Service_Drive $service Drive API service instance.
* @param string $title Title of the file to insert, including the extension.
* @param string $description Description of the file to insert.
* @param string $parentId Parent folder's ID.
* @param string $mimeType MIME type of the file to insert.
* @param string $filename Filename of the file to insert.
* @return Google_Service_Drive_DriveFile The file that was inserted. NULL is
* returned if an API error occurred.
*/
function insertFile($service, $title, $description, $parentId, $mimeType, $filename) {
$file = new Google_Service_Drive_DriveFile();
$file->setTitle($title);
$file->setDescription($description);
$file->setMimeType($mimeType);
// Set the parent folder.
if ($parentId != null) {
$parent = new Google_Service_Drive_ParentReference();
$parent->setId($parentId);
$file->setParents(array($parent));
}
try {
$data = file_get_contents($filename);
$createdFile = $service->files->insert($file, array(
'data' => $data,
'mimeType' => $mimeType,
));
// Uncomment the following line to print the File ID
// print 'File ID: %s' % $createdFile->getId();
return $createdFile;
} catch (Exception $e) {
print "An error occurred: " . $e->getMessage();
}
}https://stackoverflow.com/questions/31072388
复制相似问题