如何在使用PHP的Google Spreadsheet身份验证中使用JSON密钥而不是P12?

Amr*_*ngh 13 php json google-sheets

我正在使用PHP中的Google Spreadsheet.当我使用P12键时,它工作得很完美,但是当我使用Google Spread Sheet进行身份验证时,我使用JSON密钥而不是P12密钥

致命错误:未捕获的异常"Google_Auth_Exception",消息"无法加载私钥"

请告诉我如何在PHP中使用Google Spread Sheet进行身份验证时使用JSON密钥.

Amr*_*ngh 5

这是我找到的解决方案。

对于P12 Key
通常,我们使用以下代码来生成令牌。

public static function getToken()
    {
        $key = file_get_contents( APPLICATION_DIR.'/'.APPLICATION_GOOGLE_CLIENT_KEY_FILE);

        $cred = new Google_Auth_AssertionCredentials(
            APPLICATION_GOOGLE_CLIENT_EMAIL,
            array('https://spreadsheets.google.com/feeds'),
            $key
        );

        $client = new Google_Client();
        $client->setAssertionCredentials($cred);

        if (!$client->getAuth()->isAccessTokenExpired()) {
            return false;
        }
        else {
            $client->getAuth()->refreshTokenWithAssertion($cred);
        }

        $service_token = json_decode($client->getAccessToken());


        return $service_token->access_token;
    }
Run Code Online (Sandbox Code Playgroud)

对于 JSON Key
但现在我们没有 P12 key,我们有一个 JSON key,所以我只是对上面的代码做了一些更改,请看下面:

public static function getToken()
    {

        $key = APPLICATION_DIR.'/'.APPLICATION_GOOGLE_CLIENT_KEY_FILE;
        $data = json_decode(file_get_contents($key));    // here i decoded the json

         if (isset($data->type) && $data->type == 'service_account') {

            $cred = new Google_Auth_AssertionCredentials(
                APPLICATION_GOOGLE_CLIENT_EMAIL,    // it's the client email
                array('https://spreadsheets.google.com/feeds'),   // it's google spreadsheet scope
                $data->private_key         // here is the private key
            );
         }

        $client = new Google_Client();
        $client->setAssertionCredentials($cred);

        if (!$client->getAuth()->isAccessTokenExpired()) {
            return false;
        }
        else {
            $client->getAuth()->refreshTokenWithAssertion($cred);
        }

        $service_token = json_decode($client->getAccessToken());


        return $service_token->access_token;
    }
Run Code Online (Sandbox Code Playgroud)

  • 非常感谢这段代码,对我帮助很大! (2认同)