如何检查Google Client API密钥是否对Google PHP API库有效?

unf*_*vio 7 php client google-api api-key

我已在PHP应用程序中正确实现了Google API客户端.我能够连接到我想要的服务.

但现在我想检查用户输入的API密钥是否有效.

我查看了Google_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;
    }
Run Code Online (Sandbox Code Playgroud)

我想制作另一种方法来判断使用的API密钥是否有效......

    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';
    }
Run Code Online (Sandbox Code Playgroud)

或者我应该连接到服务,然后检查我是否有读取访问权限?但我相信有一种更简单,更好的方法可以做到这一点......

Mar*_*ler 1

你可以用 JavaScript 检查;错误的密钥总是会设置未记录的属性window.G_INCOMPAT。可能需要进行猴子修补function alert() {}才能消除alert()无效密钥,这只会干扰设置密钥的过程。

这个答案有一个有趣的方法alert()

还有一个记录的函数,可以连接到: https://developers.google.com/maps/documentation/javascript/events#auth-errors

如果它确实必须是 PHP,您仍然可以生成一些 JS 并使用 PhantomJS 运行它。

请参阅我的 Github:php-phantomjs ...这并非不可能。