Skip to content
Advertisement

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

Is it possible to share a google docs link to others so that they can see and edit my google docs without requesting access. I already gone through this link https://developers.google.com/drive/api/v3/reference/files for “webView link”. But I am not getting it how to use it in my code using PHP so that I can share my google docs without requesting access.

This is my code-

<?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%sn", $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 %sn", $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: %sn", $document->title);
$documentId = $document->getdocumentId();
printf("Document Id: %sn", $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);

I have also used the proper scopes and after changing the scopes i have also deleted the token.json file and again authenticated the user.

Then also I am unable to execute how to share a google docs with others using PHP so that they can see my docs without requesting access.

Through the above mentioned code I am able to create a doc file and insert text in it properly but now i want to share it with others.What else I have to do to achieve this. Please help me out with this query.

for help and documentation i was following this link https://developers.google.com/drive/api/v2/manage-sharing and inserted my code at the same as–

$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: %sn", $result->id);
        }
    }
} finally {
    $service->getClient()->setUseBatch(false);
}

it’s giving this error-

PHP Fatal error:  Uncaught Error: Call to undefined method GoogleServiceDriveResourcePermissions::insert()

Advertisement

Answer

You need to use the Permissions: create method of the Google Drive API to create a new Permission with the parameters you require.

Make a Permissions: create request to the Drive API with the ID of the file you wish to set the permission on will set up the permission.

With the file ID you can make the request along with a request body which contains the permission type:

Example cURL Request:

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

The data '{"role":"editor","type":"user","emailAddress":"user@example.com"}' line sets the permissions so that the user with email address user@example.com has edit permissions for the file. You can read more about the Permissions resource here

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement