douju1928
2018-07-19 18:59
浏览 136
已采纳

Google OAuth 2.0 PHP API身份验证失败:“使用未定义的常量STDIN”[重复]

I am trying to implement the PlaylistItems: insert YouTube Data API sample, and when I try to run it, I get the following:

Notice: Use of undefined constant STDIN - assumed 'STDIN' in /example/path/to/script.php on line 51

The function containing this line does not make it clear where STDIN gets it's value:

function getClient() {
  $client = new Google_Client();
  $client->setApplicationName('API Samples');
  $client->setScopes('https://www.googleapis.com/auth/youtube.force-ssl');
  // Set to name/location of your client_secrets.json file.
  $client->setAuthConfig('client_secrets.json');
  $client->setAccessType('offline');

  // Load previously authorized credentials from a file.
  $credentialsPath = expandHomeDirectory(CREDENTIALS_PATH);
  if (file_exists($credentialsPath)) {
    $accessToken = json_decode(file_get_contents($credentialsPath), true);
  } else {
    // Request authorization from the user.
    $authUrl = $client->createAuthUrl();
    printf("Open the following link in your browser:
%s
", $authUrl);
    print 'Enter verification code: ';
    $authCode = trim(fgets(STDIN)); // <--- Appears to be the problem

    // Exchange authorization code for an access token.
    $accessToken = $client->fetchAccessTokenWithAuthCode($authCode);

    // Store the credentials to disk.
    if(!file_exists(dirname($credentialsPath))) {
      mkdir(dirname($credentialsPath), 0700, true);
    }
    file_put_contents($credentialsPath, json_encode($accessToken));
    printf("Credentials saved to %s
", $credentialsPath);
  }
  $client->setAccessToken($accessToken);

  // Refresh the token if it's expired.
  if ($client->isAccessTokenExpired()) {
    $client->fetchAccessTokenWithRefreshToken($client->getRefreshToken());
    file_put_contents($credentialsPath, json_encode($client->getAccessToken()));
  }
  return $client;
}

Please forgive my naiveté, but how is the script supposed to supply an auth code? Why is this step not performed?

</div>
  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • doudang2817 2018-07-19 19:33
    已采纳

    Thanks, @sean-bright for pointing out the existing question. While it didn't not answer my question, it got me closer to the solution.

    It turns out Google's sample is designed to be run from a CLI and my browser-based implementation was not providing a means of prompting the user for input that is called for by that STDIN line.

    Since the auth code is provided as a parameter in the $authUrl variable that gets printed to the screen the first time the script is run, I was able to resolve my issue by replacing

    $authCode = trim(fgets(STDIN));

    with:

    $authCode = $_GET['code'];

    点赞 打赏 评论

相关推荐 更多相似问题