我们如何在不使用 PHP 请求访问的情况下与他人共享 google 文档 link?

How we can share a google docs link with others without requesting access using PHP?

是否可以与其他人共享 google 文档 link,以便他们无需请求访问权限即可查看和编辑我的 google 文档。我已经为 "webView link" 完成了这个 link https://developers.google.com/drive/api/v3/reference/files。但是我不知道如何使用 PHP 在我的代码中使用它,这样我就可以在不请求访问的情况下共享我的 google 文档。

这是我的代码-

<?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([
                        "https://www.googleapis.com/auth/documents",
                        "https://www.googleapis.com/auth/drive.file",
                        "https://www.googleapis.com/auth/drive"
                        ]);
    // $client->setScopes(Google_Service_Drive::DRIVE);
    $client->setAuthConfig('credentials.json');
    $client->setAccessType('offline');
    $client->setApprovalPrompt('force');

    // 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));
        // print_f("code:",$authCode);
                
        // 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 = 'Demo document';
$document = new Google_Service_Docs_Document(array(
    'title' => $title
));

$document = $service->documents->create($document);
printf("Created document with title: %s\n", $document->title);
$documentId = $document->getdocumentId();
printf("Document Id: %s\n", $documentId);

$longText = "The lorem ipsum is a placeholder text used in publishing and graphic design. This filler text is a short paragraph that contains all the letters of the alphabet.";
$requests = array();
$requests[] = new Google_Service_Docs_Request([
    'insertText' => [
        'text' => $longText,
        'location' => [
            'index' => 1,
        ],
    ],
]);

$requests [] = new Google_Service_Docs_Request([
    'insertTable' => [
        'rows' =>  2,
        'columns' =>  2,
        'endOfSegmentLocation' => [
          'segmentId' => ''
        ],
    ],
]);

$requests[] = new Google_Service_Docs_Request(array(
    'insertInlineImage' => array(
        'uri' => 'https://www.gstatic.com/images/branding/product/1x/docs_64dp.png',
        'location' => array(
            'index' => 1,
        ),
        'objectSize' => array(
            'height' => array(
                'magnitude' => 50,
                'unit' => 'PT',
            ),
            'width' => array(
                'magnitude' => 50,
                'unit' => 'PT',
            ),
        )
        ),
));

$batchUpdateRequest = new Google_Service_Docs_BatchUpdateDocumentRequest(array(
    'requests' => $requests
));

$response = $service->documents->batchUpdate($documentId, $batchUpdateRequest);

我也使用了正确的范围,在更改范围后我还删除了 token.json 文件并再次对用户进行了身份验证。

然后我也无法执行如何使用 PHP 与其他人共享 google 文档,以便他们可以在不请求访问权限的情况下查看我的文档。

通过上面提到的代码,我能够创建一个 doc 文件并在其中正确插入文本,但现在我想与 others.What 共享它,否则我必须做才能实现这一点。请帮我解决这个问题。

为了帮助和文档,我正在关注这个 link https://developers.google.com/drive/api/v2/manage-sharing 并同时插入我的代码--

$fileId = $documentId;
$service->getClient()->setUseBatch(true);
try {
    $batch = $service->createBatch();

    $userPermission = new Google_Service_Drive_Permission(array(
        'type' => 'user',
        'role' => 'writer',
        'value' => 'user@example.com'
    ));
    $request = $service->permissions->insert(
        $fileId, $userPermission, array('fields' => 'id'));
    $batch->add($request, 'user');
    $domainPermission = new Google_Service_Drive_Permission(array(
        'type' => 'domain',
        'role' => 'reader',
        'value' => 'example.com'
    ));
    $request = $service->permissions->insert(
        $fileId, $domainPermission, array('fields' => 'id'));
    $batch->add($request, 'domain');
    $results = $batch->execute();

    foreach ($results as $result) {
        if ($result instanceof Google_Service_Exception) {
            // Handle error
            printf($result);
        } else {
            printf("Permission ID: %s\n", $result->id);
        }
    }
} finally {
    $service->getClient()->setUseBatch(false);
}

它给出了这个错误-

PHP Fatal error:  Uncaught Error: Call to undefined method Google\Service\Drive\Resource\Permissions::insert()

您需要使用 Google 驱动器 API 的 Permissions: create 方法来使用您需要的参数创建一个新的权限。

使用您希望设置权限的文件的 ID 向驱动器 API 发出 Permissions: create 请求将设置权限。

使用文件 ID,您可以发出请求以及包含权限类型的请求正文:

示例 cURL 请求:

curl --request POST \
  'https://www.googleapis.com/drive/v3/files/<YOUR-FILE-ID-GOES-HERE>/permissions?key=[YOUR_API_KEY]' \
  --header 'Authorization: Bearer [YOUR_ACCESS_TOKEN]' \
  --header 'Accept: application/json' \
  --header 'Content-Type: application/json' \
  --data '{"role":"editor","type":"user","emailAddress":"user@example.com"}' \
  --compressed

data '{"role":"editor","type":"user","emailAddress":"user@example.com"}' 行设置权限,以便电子邮件地址为 user@example.com 的用户具有文件的编辑权限。您可以阅读有关权限资源的更多信息 here