Google Directory API 请求的身份验证范围不足

问题描述

我已按照 here 中 Google Directory API 的说明进行操作,并成功获得了完全相同的结果。但是,当我尝试使用此 API 插入用户时,我收到一条消息,指出我的请求没有足够的身份验证。

这是我的 getClient() 代码


    function getClient()
    {
        $client = new \Google_Client();
        $client->setApplicationName('G Suite Directory API PHP Quickstart');
        $client->setScopes(
            \Google_Service_Directory::ADMIN_DIRECTORY_USER,);
        $client->setAuthConfig(Yii::getAlias('@webroot').'/credentials/credentials.json');
        $client->setAccesstype('offline');
        $client->setPrompt('select_account consent');
    
        $tokenPath = Yii::getAlias('@webroot').'/credentials/token.json';
        if (file_exists($tokenPath)) {
            $accesstoken = json_decode(file_get_contents($tokenPath),true);
            $client->setAccesstoken($accesstoken);
        }
    
        if ($client->isAccesstokenExpired()) {
            // Refresh the token if possible,else fetch a new one.
            if ($client->getRefreshToken()) {
                $client->fetchAccesstokenWithRefreshToken($client->getRefreshToken());
            } else {
                // Request authorization from the user.
                $authUrl = $client->createAuthUrl();
                printf("Open the following link in your browser:\n%s\n",$authUrl);
                print 'Enter verification code: ';
                $authCode = trim(fgets(STDIN));
    
                // Exchange authorization code for an access token.
                $accesstoken = $client->fetchAccesstokenWithAuthCode($authCode);
                $client->setAccesstoken($accesstoken);
    
                // Check to see if there was an error.
                if (array_key_exists('error',$accesstoken)) {
                    throw new Exception(join(',',$accesstoken));
                }
            }
            // Save the token to a file.
            if (!file_exists(dirname($tokenPath))) {
                mkdir(dirname($tokenPath),0700,true);
            }
            file_put_contents($tokenPath,json_encode($client->getAccesstoken()));
        }
        return $client;
    }

这是我从这个 API 插入用户代码


    $pwd = "testing";
    $user_mail = "[email protected]";
    $first_name = "Uji";
    $last_name = "Coba";
    
    $client = $this->getClient();
    $service = new \Google_Service_Directory($client);
    $postBody = new \Google_Service_Directory_User;
    $postBody->setPrimaryEmail($user_mail);
    $postBody->setPassword($pwd);
    $postBody->setorgUnitPath('myuniversity.ac.id');
    $googleUserName = new \Google_Service_Directory_UserName;
    $googleUserName->setGivenname($first_name);
    $googleUserName->setFamilyName($last_name);
    $postBody->setName($googleUserName);
    
    $results = $service->users->insert($postBody);
    print_r($results);
    exit;

这是我运行上面的代码后得到的: Result from API Request

有什么建议吗?

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)