1

I am working on google docs api and I want to send request and get the auth code which in exchange will give the access token. Below code is working fine but the problem is I have to copy the auth url and paste it to the browser and then from browser url, I am copying the auth code and pasting it to the terminal which in return a token.json file is being created it my directory. But the thing is I want to implement the same thing in my project and I can't do it like this copying url from one place to another.I want it all dynamically.

can anybody help in this how we can modify the below code for sending auth url request and in return i get auth code from which i can fetch the access token without copying and pasting it to the terminal for processing.

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->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();        
        $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;
}
1
  • For example, if you want to achieve your goal, as a workaround, how about using python for only authorization? When python is used, the browser is automatically opened and the authorization code can be retrieved. Ref At that time, the retrieved values are saved as a file for using your PHP script. If this was not the direction you expect, I apologize. Commented Feb 15, 2022 at 12:08

1 Answer 1

2

The PHP client library is not designed to open the web browser for you with console applications or installed applications. You need to show the user the Oauth2 browser link that they can then open in a browser and then paste back into the code.

The library does not support the functionality to open the browser window for you in a console application.

       // 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);
Sign up to request clarification or add additional context in comments.

5 Comments

@DalmTo, there is no way in which we can use some alternatives with PHP? every time we have do like this? as this way is quite unprofessional.
The Google .Net client library will open a new browser for you. I think the Java Client library will as well. Both from an installed console application. May i ask are you giving this code to others? are you instructing them in how to create their own credentials.json?
@DalmTo, No I am not giving my code to others. Instructing them to create their own.
@DalmTo, with this "composer require google/apiclient:^2.12.1" library it's possible or not? to open a new browser with the auth url.
As i mentioned already The PHP client library is not designed to open the web browser for you with console applications. You need to display the browser window to the user and let them open it themselves in a web browser copy the authorizaotn code and paste it back into your application. Libraries that do support this would be the .Net client library, the Java client library I think the node.js client library also opens the web browser for you.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.