繁体   English   中英

谷歌云端硬盘下载API IN php

[英]Google Drive Download API IN php

$drive_service = new Google_Service_Drive($client);
$content = $drive_service->files->export($file_id, 'application/pdf', array('alt' => 'media' ));

我使用的是 API 版本 1,如果有 API v1 下载文件代码,请给我链接。 驱动器的 API v2 不起作用,所以请。

在此处输入图片说明

集成 Google Drive API 的说明

从 Google Drive API 仪表板下载client_secret.json 一旦你把它存储在你可以访问的地方。 然后使用composer从谷歌官方github存储库为谷歌驱动器Api安装谷歌客户端PHP库 它仍处于测试阶段,但有效。 我自己测试过。

composer.json有以下代码片段,然后运行composer update

"require": {
    "php": ">=7",
    "google/apiclient": "^2.0"
}

在供应商目录中拥有 google/apiclient 后,将其包含在您的工作流程中。

示例代码片段

下面是我最近在我的一个项目中使用的示例代码片段。 您可以调整它以满足您的需要。 我从 google 官方 github repo 借用了这段代码片段。 Google API PHP 客户端示例

<?php
session_start();
error_reporting(E_ALL);
require_once __DIR__ . '/vendor/autoload.php';

$credentialPath = 'creds/accesstoken.json';

$authCode = $_GET['code'] ?: null ;

$client = new Google_Client();

$client->setApplicationName('Drive API PHP Quickstart');
$client->setScopes(implode(' ', [Google_Service_Drive::DRIVE, Google_Service_Drive::DRIVE_FILE]));
$client->setAuthConfig(__DIR__ . '/client_secret.json');
$client->setAccessType('offline');

if (is_null($authCode)) {
    $authUrl = $client->createAuthUrl();
    header('Location: ' . $authUrl);
    exit;
} else {
    if (file_exists($credentialPath)) {
        $accessToken = json_decode(file_get_contents($credentialPath), true);
    } else {
        $accessToken = $client->fetchAccessTokenWithAuthCode($authCode);

        $_SESSION['access_token'] = json_encode($accessToken);

        file_put_contents($credentialPath, json_encode($accessToken));

        print 'Token stored successfully';
    }

    $client->setAccessToken($accessToken);

    // Refresh the token if it's expired.
    if ($client->isAccessTokenExpired()) {
        print $client->getRefreshToken();

        $client->fetchAccessTokenWithRefreshToken($client->getRefreshToken());

        $accessToken = $client->getAccessToken();

        file_put_contents($credentialPath, json_encode($accessToken));

        $client->setAccessToken($accessToken);

        print_r($accessToken);
    }
}

建议

尝试研究给出的代码,一旦您了解了该脚本的生命周期,您就可以轻松地将Google Drive API集成到任何框架、脚本中。 您不必依赖第三方服务。 虽然有时这是想做的事情。 让我们知道此脚本是否适合您。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM