Google API 与 PHP 调用 google_client 对象

Google API with PHP calling google_client object

我正在使用 codeigniter 3.x 和 php 5.5+。我一直在努力让这个工作没有运气。我想在我创建的 youtube 控制器 class 中调用方法,这些方法将根据与 google 或 youtube 的通信做不同的事情。我相信问题出在 Google_Client 上,或者可能出在如何存储 $client 变量上,以便您可以在第二个函数中使用它。当我尝试从另一个函数调用它时,它给出了一个不需要登录的错误,即使用户已经进行了 google 验证。我如何告诉我的第二个功能用户已经完成授权并获得了令牌。当两个函数都在同一个函数中时,一切似乎都运行良好(我的意思是只使用一个函数)。我也不想在我执行的每个函数或方法上验证用户。 因此,在完成第一个函数后,我使用 url 中的访问令牌重定向到第二个函数,但随后出现错误 Message: Error calling GET https://www.googleapis.com/youtube/analytics/v1/reports?ids=channel%3D%3DMINE&start-date=2014-01-01&end-date=2016-01-20&metrics=views&filters=video%3D%3DpC900o6JaMc: (401) Login Required

控制器 Youtubeverify 中的第一个函数:

class Youtubeverify extends CI_Controller{


public function youtube_consent(){


$this->load->library('google');

$OAUTH2_CLIENT_ID = 'MY_ID';
$OAUTH2_CLIENT_SECRET = 'MY_KEY';

$client = new Google_Client();
$client->setClientId($OAUTH2_CLIENT_ID);
$client->setClientSecret($OAUTH2_CLIENT_SECRET);

$client->setScopes(array('https://www.googleapis.com/auth/yt-analytics-monetary.readonly','https://www.googleapis.com/auth/youtube.readonly'));
$redirect = filter_var('http://' . $_SERVER['HTTP_HOST'] . "/ci/youtubeverify/display_report",
FILTER_SANITIZE_URL);
$client->setRedirectUri($redirect);

$youtubeReporting = new Google_Service_YouTubeReporting($client);
if (isset($_REQUEST['logout'])) {
$this->session->unset_userdata('youtube_token');
}

if (isset($_GET['code'])) {
if (strval($_SESSION['state']) !== strval($_GET['state'])) {
die('The session state did not match.');
}

$client->authenticate($_GET['code']);
$youtube_token = $client->getAccessToken();
//trying to store the access token in a session
$newdata = array('youtube_token'=>$youtube_token);

$this->session->set_userdata($newdata);

header('Location: ' . $redirect);
}

if ($this->session->userdata('youtube_token')) {
$client->setAccessToken($this->session->userdata('youtube_token'));
}

if ($client->getAccessToken()) {

$client->getAccessToken();
}
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();

 redirect($authUrl);
}
}

控制器 Youtubeverify 中的第二个函数:

public function display_report(){

$this->load->library('google');

$client = new Google_Client();

$client->getAccessToken();

$youtubeAnalytics = new Google_Service_YouTubeAnalytics($client);

$id = 'channel==MINE';
$start_date = '2014-01-01';
$end_date = '2016-01-20';
$optparams = array('filters' => 'video==*********');

$metrics = array('views');

$api_response = $metrics;


$api = $youtubeAnalytics->reports->query($id, $start_date, $end_date, $metric,$optparams);

$data['api_response'] = $api_response['views'];
$this->load->view('layouts/mainlay',$data);
}

我以前从未使用过 YouTube API,但这是朝着正确方向迈出的一步。

class Youtubeverify extends CI_Controller {
    // Google API Keys
    const CLIENT_ID         = '';
    const CLIENT_SECRET     = '';

    // We'll store the client in a class property so we can access it between methods.
    protected $Client;

    public function __construct () {
        parent::__construct();
        // setup google client.
        $this->Client = new Google_Client();
        $this->Client->setClientId(self::CLIENT_ID);
        $this->Client->setClientSecret(self::CLIENT_SECRET);
        // we call the authenication method for each request
        $this->_authenticate_client();
    }

    // Authentication method
    protected function _authenticate_client () {
        //if we already have a token then we just set it in the client 
        //without going through authentication process again
        if( $accessToken = $this->session->userdata('youtube_token') ) {
            $this->Client->setAccessToken($accessToken);
        }else{
            // preform authentication as usual with a redirect ...etc
        }
    }   
}