I've been creating a little script to grab YouTube monthly views from a user's YouTube channel. This script works fine but every time they refresh the page they have to reconsent access. I'd prefer for this to go away but i can't find a solution online.
I've had a look at refresh tokens but even when i add them on a refresh the users still has to re-request to get the data again, maybe it's something to do with creating a user session or storing a cookie?
Here's my current working script
if(isset($_GET['code'])) {
// try to get an access token
$code = $_GET['code'];
$url = 'https://accounts.google.com/o/oauth2/token';
// this will be our POST data to send back to the OAuth server in exchange
// for an access token
$params = array(
"code" => $code,
"client_id" => $oauth2_client_id,
"client_secret" => $oauth2_secret,
"redirect_uri" => $oauth2_redirect,
"grant_type" => "authorization_code"
);
// build a new HTTP POST request
$request = new HttpPost($url);
$request->setPostData($params);
$request->send();
// decode the incoming string as JSON
$responseObj = json_decode($request->getHttpResponse());
$currentDate = date("Y-m-d");
$monthBefore = date('Y-m-d', strtotime(date('Y-m')." -1 month"));
$views = file_get_contents('https://www.googleapis.com/youtube/analytics/v1/reports?ids=channel%3D%3DMINE&start-date='.$monthBefore.'&end-date='.$currentDate.'&metrics=views&access_token='.$responseObj->access_token);
$json = json_decode($views);
}
$monthlyViews = $json->rows[0][0];
var_dump($monthlyViews);