How to check if a Google Client API key is valid with Google PHP API library?
Asked Answered
L

1

8

I have correctly implemented a Google API client in my PHP application. I was able to connect to the service I wanted.

But now I want to check if an API key the user enters is valid or not.

I have looked around or at the methods exposed by Google_Client() class but I don't think I am sure how to check this.

Below here's the method in my class that creates a client:

    private function client( $api_key ) {

        $client = new \Google_Client();
        $client->setClassConfig( 'Google_Cache_File', 'directory',  $this->cache_dir );
        $client->setDeveloperKey( $api_key );
        $client->setApplicationName( $this->name );
        $client->setScopes( array( \Google_Service_Calendar::CALENDAR_READONLY ) );
        $client->setAccessType( 'online' );

        return $client;
    }

And I want to make another method to tell if the API key used is valid or not...

    public function validate_api_key( $api_key ) {
        $client = $this->client( $api_key );

        // What should I use here to check if $api_key is valid?

        if ( $client ) {
            return true;
        }
        return 'error';
    }

Or should I connect to a service and then check if I have read access from there? But I believe there is a simpler and better way to do this...

Lagena answered 21/7, 2015 at 13:5 Comment(3)
should I connect to a service and then check if I have read access from there? I am pretty sure that's they only way to test if its validMargravine
well yeah... I was hoping though for a direct method in the client object returning a bool or something... the thing is that Google_Client or a Google Service instantiated by the client will still attempt to connect and the service will respond anyway, so the steps to verify if the api key is valid by pulling data are quite a few actuallyLagena
Yeah but the only way for the lib to validate it would be to send a request. I drought Google has exposed the formatting of its keys. even checkToken() looks like it just attempts to make a dummy request.Margravine
A
1

you can check with JavaScript; a wrongful key will always set the undocumented property window.G_INCOMPAT. monkey-patching with function alert() {} might be required to get rid of the alert() for an invalid key, which would only disturb the process of setting the key.

this answer has an interesting approach concerning the alert()

there is also a documented function, one can hook into: https://developers.google.com/maps/documentation/javascript/events#auth-errors

if it really has to be PHP, you could still generate some JS and run it with PhantomJS.

see my Github: php-phantomjs ...it is not impossible.

Anarchy answered 26/1, 2018 at 12:38 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.