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...
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With