zeidanbm
zeidanbm

Reputation: 532

Google API with PHP calling google_client object

I'm using codeigniter 3.x and php 5.5+. I've been trying to get this to work with no luck. I want to call methods inside a youtube controller class I created that will do different things based on communicating with the google or youtube. The problem is with the Google_Client I believe or it's with how to store $client variable maybe so you can use it in second function. When I try calling this from another function it gives a not login required error even thought the user already did the google verification. How can I tell my second function that the user has already done the authorization and got the token. Everything seems to work very well when both functions are in the same function(I mean just using one function). Also I don't want to verify user on every function or method I execute. So after first function is done, I get redirected with an access token in the url to the second function but then I get an error 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

First function in the controller 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);
}
}

Second function in the controller 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);
}

Upvotes: 0

Views: 1239

Answers (1)

ahmad
ahmad

Reputation: 2729

I have never worked with YouTube API before, but here's a step in the right direction.

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
        }
    }   
}

Upvotes: 1

Related Questions