【问题标题】:Cannot Create Google Docs using PHP API无法使用 PHP API 创建 Google 文档
【发布时间】:2021-04-10 10:05:46
【问题描述】:
    $client->setAccessToken($_SESSION['access_token']);
    $service = new Google_Service_Docs($client);

    $title = $_SESSION['class'].' - '.date("Y-m-d");
    $document = new Google_Service_Docs_Document(array(
        'title' => $title
    ));

    //everything works until here. For some reason, this line doesn't run. It doesn't even proceed.
    $document = $service->documents->create($document);
    
    //this line isn't even printed
    print_r("success!");

    $documentId = $document->documentId;

    header('Location: https://docs.google.com/document/d/'.$documentId);
    exit();

我已经为此苦苦思索了好几个小时。我不知道为什么我不能创建一个新的 Google Doc。除了谷歌之外,网上绝对没有这样的例子,这里的大部分代码都是直接从他们那里复制而来的。

这是我在分配标题后但在执行服务以创建新文档之前打印 $document 时得到的结果。

Google_Service_Docs_Document Object
(
    [bodyType:protected] => Google_Service_Docs_Body
    [bodyDataType:protected] => 
    [documentId] => 
    [documentStyleType:protected] => Google_Service_Docs_DocumentStyle
    [documentStyleDataType:protected] => 
    [footersType:protected] => Google_Service_Docs_Footer
    [footersDataType:protected] => map
    [footnotesType:protected] => Google_Service_Docs_Footnote
    [footnotesDataType:protected] => map
    [headersType:protected] => Google_Service_Docs_Header
    [headersDataType:protected] => map
    [inlineObjectsType:protected] => Google_Service_Docs_InlineObject
    [inlineObjectsDataType:protected] => map
    [listsType:protected] => Google_Service_Docs_DocsList
    [listsDataType:protected] => map
    [namedRangesType:protected] => Google_Service_Docs_NamedRanges
    [namedRangesDataType:protected] => map
    [namedStylesType:protected] => Google_Service_Docs_NamedStyles
    [namedStylesDataType:protected] => 
    [positionedObjectsType:protected] => Google_Service_Docs_PositionedObject
    [positionedObjectsDataType:protected] => map
    [revisionId] => 
    [suggestedDocumentStyleChangesType:protected] => Google_Service_Docs_SuggestedDocumentStyle
    [suggestedDocumentStyleChangesDataType:protected] => map
    [suggestedNamedStylesChangesType:protected] => Google_Service_Docs_SuggestedNamedStyles
    [suggestedNamedStylesChangesDataType:protected] => map
    [suggestionsViewMode] => 
    [title] => Computer 9 - Charity - 2021-01-04
    [internal_gapi_mappings:protected] => Array
        (
        )

    [modelData:protected] => Array
        (
        )

    [processed:protected] => Array
        (
        )

)

【问题讨论】:

    标签: php google-api google-docs google-api-php-client google-docs-api


    【解决方案1】:

    PHP Quickstart 提供有关如何使用 Google Docs API 阅读 Google 文档的完整教程。

    要创建新文档,请使用上面的示例并替换:

    $documentId = '195j9eDD3ccgjQRttHhJPymLJUCOUjs-jmwTrekvdjFE';
    $doc = $service->documents->get($documentId);
    printf("The document title is: %s\n", $doc->getTitle());
    

    与:

    $title = 'My Document';
    $document = new Google_Service_Docs_Document(array(
        'title' => $title
    ));
    
    $document = $service->documents->create($document);
    printf("Created document with title: %s\n", $document->title);
    

    另外,请确保将项目的 SCOPE 更改为 Google_Service_Docs::DOCUMENTS,并在运行代码之前,删除 Token.json 以重新启动验证过程并使用您指定的范围创建新令牌。

    您的代码应如下所示:

    <?php
    require __DIR__ . '/vendor/autoload.php';
    
    /**
     * Returns an authorized API client.
     * @return Google_Client the authorized client object
     */
    function getClient()
    {
        $client = new Google_Client();
        $client->setApplicationName('Google Docs API PHP Quickstart');
        $client->setScopes(Google_Service_Docs::DOCUMENTS);
        $client->setAuthConfig('credentials.json');
        $client->setAccessType('offline');
    
        // Load previously authorized credentials from a file.
        $credentialsPath = expandHomeDirectory('token.json');
        if (file_exists($credentialsPath)) {
            $accessToken = json_decode(file_get_contents($credentialsPath), true);
        } 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);
    
            // Store the credentials to disk.
            if (!file_exists(dirname($credentialsPath))) {
                mkdir(dirname($credentialsPath), 0700, true);
            }
            file_put_contents($credentialsPath, json_encode($accessToken));
            printf("Credentials saved to %s\n", $credentialsPath);
        }
        $client->setAccessToken($accessToken);
    
        // Refresh the token if it's expired.
        if ($client->isAccessTokenExpired()) {
            $client->fetchAccessTokenWithRefreshToken($client->getRefreshToken());
            file_put_contents($credentialsPath, json_encode($client->getAccessToken()));
        }
        return $client;
    }
    
    /**
     * Expands the home directory alias '~' to the full path.
     * @param string $path the path to expand.
     * @return string the expanded path.
     */
    function expandHomeDirectory($path)
    {
        $homeDirectory = getenv('HOME');
        if (empty($homeDirectory)) {
            $homeDirectory = getenv('HOMEDRIVE') . getenv('HOMEPATH');
        }
        return str_replace('~', realpath($homeDirectory), $path);
    }
    
    // Get the API client and construct the service object.
    $client = getClient();
    $service = new Google_Service_Docs($client);
    
    $title = 'My Document';
    $document = new Google_Service_Docs_Document(array(
        'title' => $title
    ));
    
    $document = $service->documents->create($document);
    printf("Created document with title: %s\n", $document->title);
    

    参考:

    DocsScopes

    Creating Document

    【讨论】:

    • getClient 要求代码在 CLI 上运行,但我的代码已经在 Web 服务器上运行。我确实在我的范围$client-&gt;addScope("https://www.googleapis.com/auth/documents"); 中包含了这些文档。除了getClient() 的区别之外,为什么我的代码不起作用?我知道$client-&gt;setAccessToken($_SESSION['access_token']); 必须工作,因为我使用同一行代码来访问Sheets API 和GMail API。那么为什么 Docs 突然不同了呢?
    • 您在执行代码时是否收到任何错误?如果是,您可以将其包含在您的帖子中吗?
    • 没有错误。只是一个空白页。太奇怪了。我的一部分认为这可能是语法问题,但没有其他适用于 Google Docs 的文档。
    • 这是我用来为我的客户设置访问令牌的参考。适用于除 Google Docs 之外的所有其他 API。
    猜你喜欢
    • 1970-01-01
    • 2016-12-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-09-05
    • 1970-01-01
    • 2014-10-25
    相关资源
    最近更新 更多