php - 如何使 google oauth2 的访问 token 根本不会过期?

标签 php google-api google-oauth youtube-data-api google-api-php-client

我正在编写以下代码,它是使用 Youtube Data API 列出用户广播的示例代码

它对我有用,我修改了一些部分,但 token 过期了,我必须清除我的 session 并重新进行身份验证才能再次工作,我搜索了很多,发现一些帖子说 token 过期了1小时后

如何使 token 根本不会过期?

<?php
include 'oauth.php';

/**
 * Library Requirements
 *
 * 1. Install composer (https://getcomposer.org)
 * 2. On the command line, change to this directory (api-samples/php)
 * 3. Require the google/apiclient library
 *    $ composer require google/apiclient:~2.0
 */
if (!file_exists(__DIR__ . '/vendor/autoload.php')) {
  throw new \Exception('please run "composer require google/apiclient:~2.0" in "' . __DIR__ .'"');
}

require_once __DIR__ . '/vendor/autoload.php';
session_start();

/*
 * You can acquire an OAuth 2.0 client ID and client secret from the
 * {{ Google Cloud Console }} <{{ https://cloud.google.com/console }}>
 * For more information about using OAuth 2.0 to access Google APIs, please see:
 * <https://developers.google.com/youtube/v3/guides/authentication>
 * Please ensure that you have enabled the YouTube Data API for your project.
 */
$OAUTH2_CLIENT_ID = $clientid;
$OAUTH2_CLIENT_SECRET = $clientsecret;

$client = new Google_Client();
$client->setClientId($OAUTH2_CLIENT_ID);
$client->setClientSecret($OAUTH2_CLIENT_SECRET);
$client->setScopes('https://www.googleapis.com/auth/youtube');
$redirect = filter_var('http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'],
    FILTER_SANITIZE_URL);
$client->setRedirectUri($redirect);

// Define an object that will be used to make all API requests.
$youtube = new Google_Service_YouTube($client);

// Check if an auth token exists for the required scopes
$tokenSessionKey = 'token-' . $client->prepareScopes();
if (isset($_GET['code'])) {
  if (strval($_SESSION['state']) !== strval($_GET['state'])) {
    die('The session state did not match.');
  }

  $client->authenticate($_GET['code']);
  $_SESSION[$tokenSessionKey] = $client->getAccessToken();
  header('Location: ' . $redirect);
}

if (isset($_SESSION[$tokenSessionKey])) {
  $client->setAccessToken($_SESSION[$tokenSessionKey]);
}

// Check to ensure that the access token was successfully acquired.
if ($client->getAccessToken()) {
  try {
    // Execute an API request that lists broadcasts owned by the user who
    // authorized the request.
    $broadcastsResponse = $youtube->liveBroadcasts->listLiveBroadcasts(
        'id,snippet,contentDetails',
        array(
            'mine' => 'true',
        ));

    $htmlBody = "<h3>Live Broadcasts</h3>";
    foreach ($broadcastsResponse['items'] as $broadcastItem) {
      //$htmlBody .= sprintf('<li>%s (%s) (%s)</li>', $broadcastItem['snippet']['title'],
          //$broadcastItem['id'], $broadcastItem['snippet']['description']);
    $htmlBody .= "<div><ul>";  
    $htmlBody .= "<li><b>Title:</b> ".$broadcastItem['snippet']['title']."</li>";
    $htmlBody .= "<li><b>ID:</b> ".$broadcastItem['id']."</li>";
    $htmlBody .= "<li><b>Description:</b> ".$broadcastItem['snippet']['description']."</li>";
    $htmlBody .= "<li><b>Thumbnail</b> <img src='".$broadcastItem['snippet']['thumbnails']['default']['url']."' width='100px'/></li>";
    $htmlBody .= "<li><b>Embed:</b><iframe width='560' height='315' src='https://www.youtube.com/embed/".$broadcastItem['id']."' title='YouTube video player' frameborder='0' allow='accelerometer; clipboard-write; encrypted-media; gyroscope; picture-in-picture' allowfullscreen></iframe></li>";
    
    
    $htmlBody .= "</ul></div>"; 
    }
    $htmlBody .= '';

  } catch (Google_Service_Exception $e) {
    $htmlBody = sprintf('<p>A service error occurred: <code>%s</code></p>',
        htmlspecialchars($e->getMessage()));
  } catch (Google_Exception $e) {
    $htmlBody = sprintf('<p>An client error occurred: <code>%s</code></p>',
        htmlspecialchars($e->getMessage()));
  }

  $_SESSION[$tokenSessionKey] = $client->getAccessToken();
} elseif ($OAUTH2_CLIENT_ID == 'REPLACE_ME') {
  $htmlBody = <<<END
  <h3>Client Credentials Required</h3>
  <p>
    You need to set <code>\$OAUTH2_CLIENT_ID</code> and
    <code>\$OAUTH2_CLIENT_ID</code> before proceeding.
  <p>
END;
} else {
  // If the user hasn't authorized the app, initiate the OAuth flow
  $state = mt_rand();
  $client->setState($state);
  $_SESSION['state'] = $state;

  $authUrl = $client->createAuthUrl();
  $htmlBody = <<<END
  <h3>Authorization Required</h3>
  <p>You need to <a href="$authUrl">authorize access</a> before proceeding.<p>
END;
}
?>

<!doctype html>
<html>
<head>
<title>My Live Broadcasts</title>
</head>
<body>
  <?=$htmlBody?>
</body>
</html>

最佳答案

Access tokens by design expire 。这就是他们的工作方式。 Google 的访问 token 将在一小时后过期。

如果您请求离线访问,您将获得刷新 token 。然后,您可以在需要时使用刷新 token 来请求新的访问 token 。

Oauth2Authentication.php

function buildClient(){
    
    $client = new Google_Client();
    $client->setAccessType("offline");        // offline access.  Will result in a refresh token
    $client->setIncludeGrantedScopes(true);   // incremental auth
    $client->setAuthConfig(__DIR__ . '/client_secrets.json');
    $client->addScope([YOUR SCOPES HERE]);
    $client->setRedirectUri(getRedirectUri());  
    return $client;
}

那么只需测试访问 token 是否已过期并请求新的访问 token 即可

$client = buildClient();
    
    // Set the refresh token on the client. 
    if (isset($_SESSION['refresh_token']) && $_SESSION['refresh_token']) {
        $client->refreshToken($_SESSION['refresh_token']);
    }
    
    // If the user has already authorized this app then get an access token
    // else redirect to ask the user to authorize access to Google Analytics.
    if (isset($_SESSION['access_token']) && $_SESSION['access_token']) {
        
        // Set the access token on the client.
        $client->setAccessToken($_SESSION['access_token']);                 
        
        // Refresh the access token if it's expired.
        if ($client->isAccessTokenExpired()) {              
            $client->fetchAccessTokenWithRefreshToken($client->getRefreshToken());
            $client->setAccessToken($client->getAccessToken()); 
            $_SESSION['access_token'] = $client->getAccessToken();              
        }           
        return $client; 
    } else {
        // We do not have access request access.
        header('Location: ' . filter_var( $client->getRedirectUri(), FILTER_SANITIZE_URL));
    }
} catch (Exception $e) {
    print "An error occurred: " . $e->getMessage();
}

关于php - 如何使 google oauth2 的访问 token 根本不会过期?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70582521/

相关文章:

php - 仅将 div 设置为小部件的内容 | WordPress的

javascript - 为什么Argon模板中有这么多相同的路线?

php - Magento 实例指向错误的数据库

java - Android AdMob - NoSuchMethodError : No static method zzand()

powershell - 使用 Powershell v2.0 通过 Google API 删除 Gmail 电子邮件

php - 如何进行登录尝试失败的系统

javascript - 在 PHP 中使用时间轴 Google Chart API - 日期/时间格式问题

delphi - 如何在没有用户交互的情况下验证 Google Calendar API v3?

firebase - 错误: Could not load the default credentials (Firebase function to firestore)

c# - 如何以编程方式从 Google 云端硬盘中的 "share with me"中删除文件