如何使用 codeigniter 创建一个 drive rest api?

How to create a drive rest app using codenighter?

我想创建一个 Android Google 驱动器应用程序,它具有将文件从我的应用程序上传到 google 驱动器的功能,使用 Codenighter 作为后端。我对 Codenighter 很陌生。我浏览了官方文档并得到了以下 PHP quickstart for Google drive v3

我已经完成了以下步骤:

  1. 我创建了一个创建项目并启用了 Google 驱动器 API

  2. 已配置 OAuth 同意屏幕并创建凭据

  3. 已下载credentials.json并复制到我的项目根目录

最后,我创建了一个控制器,如下所示

<?PHP
defined('BASEPATH') OR exit('No direct script access allowed');
define('STDIN',fopen("php://stdin","r"));

class Welcome extends CI_Controller {

/**
 * Index Page for this controller.
 *
 * Maps to the following URL
 *      http://example.com/index.php/welcome
 *  - or -
 *      http://example.com/index.php/welcome/index
 *  - or -
 * Since this controller is set as the default controller in
 * config/routes.php, it's displayed at http://example.com/
 *
 * So any other public methods not prefixed with an underscore will
 * map to /index.php/welcome/<method_name>
 * @see https://codeigniter.com/user_guide/general/urls.html
 */
public function index()
{
    $this->load->view('welcome_message');
}

public function getClient(){
    $client = new Google_Client();
    $client->setApplicationName('Google Drive API PHP Quickstart');
    $client->setScopes(Google_Service_Drive::DRIVE_METADATA_READONLY);
    $client->setAuthConfig('credentials.json');
    $client->setAccessType('offline');
    $client->setPrompt('select_account consent');

    // Load previously authorized token from a file, if it exists.
    // The file token.json stores the user's access and refresh tokens, and is
    // created automatically when the authorization flow completes for the first
    // time.
    $tokenPath = 'token.json';
    if (file_exists($tokenPath)) {
        $accessToken = json_decode(file_get_contents($tokenPath), true);
        $client->setAccessToken($accessToken);
    }

    // If there is no previous token or it's expired.
    if ($client->isAccessTokenExpired()) {
        // Refresh the token if possible, else fetch a new one.
        if ($client->getRefreshToken()) {
            $client->fetchAccessTokenWithRefreshToken($client->getRefreshToken());
        } else {
            // Request authorization from the user.
            $authUrl = $client->createAuthUrl();
            printf("Open the following link in your browser:\n%s\n", $authUrl);
            print 'Enter verification code: ';
            $authCode = trim(fgets(STDIN));

            // Exchange authorization code for an access token.
            $accessToken = $client->fetchAccessTokenWithAuthCode($authCode);
            $client->setAccessToken($accessToken);

            // Check to see if there was an error.
            if (array_key_exists('error', $accessToken)) {
                throw new Exception(join(', ', $accessToken));
            }
        }
        // Save the token to a file.
        if (!file_exists(dirname($tokenPath))) {
            mkdir(dirname($tokenPath), 0700, true);
        }
        file_put_contents($tokenPath, json_encode($client->getAccessToken()));
    }
    return $client;
      $client = getClient();
    $service = new Google_Service_Drive($client);

    // Print the names and IDs for up to 10 files.
    $optParams = array(
    'pageSize' => 10,
    'fields' => 'nextPageToken, files(id, name)'
    );
    $results = $service->files->listFiles($optParams);

    if (count($results->getFiles()) == 0) {
        print "No files found.\n";
    } else {
        print "Files:\n";
        foreach ($results->getFiles() as $file) {
            printf("%s (%s)\n", $file->getName(), $file->getId());
        }
    }
}

}

我创建了两个函数,例如查看文件和getClient。 getClient 已生成令牌(如果尚不存在)并查看我已验证的 google 驱动器中的文件。我不知道将此 getClient() 保存在哪里以及如何及时获得该客户。我想要的只是每当我将文件上传到 google 驱动器时,我还想检查令牌是否过期。如果过期我想生成新的 one.So 我必须做什么?

当我运行上面的代码时,我得到了这样的错误

在浏览器中打开以下 link:https://accounts.google.com/o/oauth2/auth?response_type=code&access_type=offline&client_id=751215721134-94mfvkjlt7nkt5296q640qcj3q96e0fk.apps.googleusercontent.com&redirect_uri=https%3A%2F%2Fdevelopers.google.com%2Foauthplayground&state&scope=https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fdrive.metadata.readonly&prompt=select_account%20consent 输入验证码:遇到未捕获的异常类型:InvalidArgumentException 消息:无效代码文件名:/home/ua5r3kd1on8p/public_html/GDriveApp/vendor/google/apiclient/src/Google/Client.php 行号:178 回溯:文件:/home/ua5r3kd1on8p/public_html/GDriveApp/application/controllers/Welcome.php 行:59 函数:fetchAccessTokenWithAuthCode 文件:/home/ua5r3kd1on8p/public_html/GDriveApp/index.php 行:318 函数:require_once

如何解决?

I don't know exactly where to keep this getClient() and how to get that client very time.

我不太清楚你的意思。 getClient 方法应该始终是您的代码的一部分。您的代码需要 $client 来创建用于访问所有 api 的 Drive 服务对象。如果客户端没有正确加载您的刷新令牌和访问令牌,驱动服务对象将无法工作。

I also want to check whether the token expired or not. If expired I want to generate new one.So what I have to do?

您的代码已经这样做了。如果当前存储在 $client 中的访问令牌已过期,那么它将使用刷新令牌来请求一个新的

// If there is no previous token or it's expired.
if ($client->isAccessTokenExpired()) {
    // Refresh the token if possible, else fetch a new one.
    if ($client->getRefreshToken()) {
        $client->fetchAccessTokenWithRefreshToken($client->getRefreshToken());