使用PHP的Google API调用google_client对象

时间:2016-01-22 20:48:23

标签: php codeigniter youtube-api google-api-php-client

我使用的是codeigniter 3.x和php 5.5+。我一直试图让这个没有运气。我想在我创建的youtube控制器类中调用方法,这些方法将根据与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);
}

1 个答案:

答案 0 :(得分:1)

我之前从未使用过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
        }
    }   
}