/** * Return server instance of GoogleAnalytics * @link https://developers.google.com/identity/protocols/OAuth2ServiceAccount * * @param array $account Service account parameters * * @return GoogleAnalytics * @throw Exception if $account is not valid */ public static function createFromServiceAccount($account) { if (empty($account)) { throw new Exception("Invalid account"); } if (is_string($account)) { if (!is_file($account)) { throw new Exception("Invalid account file path"); } $account = json_decode(file_get_contents($account)); } if (empty($account->client_email) || empty($account->token_uri) || empty($account->private_key)) { throw new Exception("Invalid account"); } $now = time(); $data = array('iss' => $account->client_email, 'scope' => "https://www.googleapis.com/auth/analytics.readonly", 'aud' => $account->token_uri, 'exp' => $now + 3600, 'iat' => $now); $jwt = RestClient::createJwt($data, $account->private_key); $params = array('grant_type' => "urn:ietf:params:oauth:grant-type:jwt-bearer", 'assertion' => $jwt); $restClient = new RestClient(); $token = $restClient->curl($account->token_uri, "POST", $params); $token = json_decode($token); return new self(array('authMode' => "bearer", 'token' => $token->access_token)); }