Google API for analytics invalid grant but works sometimes - json

I've been on this problem now for 2 days and have tried looking under google code and stackoverflow but still can come up with an answer.
My problem is when I try my google analytics api I get "Error refreshing the OAuth2 token, message: '{ "error" : "invalid_grant" }'"
But the weird part is that some times it will work. rarely but if I refresh and keep trying it, it will output.
The only thing I could find is that it could be the refresh token limit has been exceeded
Attached is my code if someone could help me out or point me to the right direction.
Thanks!
<?php
session_start();
require_once 'Google_Client.php';
require_once 'Google_AnalyticsService.php';
require_once 'config.php';
$keyFile = 'key.p12';
$client = new Google_Client();
$client->setApplicationName("test");
if (isset($_SESSION['token'])) {
$client->setAccessToken($_SESSION['token']);
}
$client->setAssertionCredentials(new Google_AssertionCredentials(
GOOGLE_SERVICE_ACCOUNT,
array('https://www.googleapis.com/auth/analytics.readonly'),
file_get_contents($keyFile))
);
$client->setClientId(GOOGLE_CLIENT_ID);
$client->setAccessType('offline');
$client->setUseObjects(true);
$service = new Google_AnalyticsService($client);
try {
$results = $service->data_ga->get(
'ga:44444444',
date('Y-m-d', strtotime('-30 days '.date('Y-m-d', strtotime('-1 day '.date('Y-m- d'))))),
date('Y-m-d', strtotime('-1 day '.date('Y-m-d'))),
'ga:visits,ga:newVisits',
/*array(
'dimensions' => 'ga:source,ga:keyword',
'sort' => '-ga:visits,ga:keyword',
'filters' => 'ga:medium==organic',
'max-results' => '25'
)*/
array('dimensions' => 'ga:date')
);
} catch (Google_ServiceException $e) {
// echo $e->getMessage();
}
if ($client->getAccessToken()) {
$_SESSION['token'] = $client->getAccessToken();
}
$dateParsePattern = '/"Date.parse\(\\\"((\d{4})-(\d{2})-(\d{2})) UTC\\\"\)"/';
$dateParseReplacement = 'Date.parse("$1 UTC")';
$allVisitsItems = array();
$newVisitorsItems = array();
if ($results && count($results->getRows()) > 0) {
foreach ($results->getRows() as $row) {
$date = 'Date.parse("'.date("Y-m-d", strtotime($row[0])).' UTC")';
$allVisitsItems[] = array($date, intval(htmlspecialchars($row[1], ENT_NOQUOTES)));
$newVisitorsItems[] = array($date, intval(htmlspecialchars($row[2], ENT_NOQUOTES)));
}
}
header('Content-Type: application/json');
?>
<?php echo preg_replace($dateParsePattern, $dateParseReplacement, json_encode($allVisitsItems)) ?>
Edit - It's not the NTP, when I echoed date('l jS \of F Y h:i:s A'); it matched up.

The following works to generate output - make sure you are running PHP 5.3 or higher.
<?php
require_once './src/Google_Client.php';
require_once './src/contrib/Google_AnalyticsService.php';
$path_to_keyfile = '.p12';
$service_account_email = '7#developer.gserviceaccount.com';
$client_id = '7.apps.googleusercontent.com';
$analytics_profile_id = 'ga:IN URL OF ANALYTICS';
$client = new Google_Client();
$client->setApplicationName("API TEST");
$client->setAssertionCredentials(
new Google_AssertionCredentials(
$service_account_email,
array('https://www.googleapis.com/auth/analytics.readonly'),
file_get_contents($path_to_keyfile)
)
);
$client->setClientId($client_id);
$client->setAccessType('offline_access');
$service = new Google_AnalyticsService($client);
$from = date('Y-m-d', strtotime('-30 days '.date('Y-m-d', strtotime('-1 day '.date('Y-m-d'))))); // 30 days
$to = date('Y-m-d', strtotime('-1 day '.date('Y-m-d'))); // yesterday
$dateParsePattern = '/"Date.parse\(\\\"((\d{4})-(\d{2})-(\d{2})) UTC\\\"\)"/';
$dateParseReplacement = 'Date.parse("$1 UTC")';
$allVisitsItems = array();
$newVisitorsItems = array();
try {
$data = $service->data_ga->get(
//
$analytics_profile_id,
$from,
$to,
'ga:visits,ga:newVisits',
array('dimensions' => 'ga:date')
);
if($data && $data['totalResults'] > 0) {
foreach($data['rows'] as $row) {
$date = 'Date.parse("'.date("Y-m-d", strtotime($row[0])).' UTC")';
$allVisitsItems[] = array($date, intval(htmlspecialchars($row[1], ENT_NOQUOTES)));
$newVisitorsItems[] = array($date, intval(htmlspecialchars($row[2], ENT_NOQUOTES)));
}
}
header('Content-Type: application/json');
?>
<?php echo preg_replace($dateParsePattern, $dateParseReplacement, json_encode($allVisitsItems)) ?>
<?php echo preg_replace($dateParsePattern, $dateParseReplacement, json_encode($newVisitorsItems)) ?>
<?php
} catch(Exception $e) {
echo 'There was an error : - ' . $e->getMessage();
}

Related

Using Google Open ID Connect to Access User's Gmail Account

How can I run a google apps script API on multiple gmail accounts? I currently have a script that accesses a user's gmail when it is authorized by the two files shown below. I store the refresh token for the client once the code asks for authorization. However, how can I use Open ID to get authorization for various users' accounts? Do I need to store a client id in addition to a refresh token to gain authorization for a user's gmail account? Thanks for taking the time to help in advance!
read_email.php
<?php
require_once '../google-api-php-client/src/Google/autoload.php';
function getEmails (){
session_start();
$client = new Google_Client();
$client->setAuthConfigFile('client_secrets.json');
$client->setScopes(array(
'https://mail.google.com/'
));
if (isset($_SESSION['access_token']) && $_SESSION['access_token']) {
$client->setAccessToken($_SESSION['access_token']);
if($client->isAccessTokenExpired()){
header('Location: http://' . $_SERVER['HTTP_HOST'] . '/email_database/php/oauth2callback.php');
}
// Get the API client and construct the service object.
$service = new Google_Service_Script($client);
$scriptId = '**********************';
// Create an execution request object.
$request = new Google_Service_Script_ExecutionRequest();
set_time_limit(0);
$request->setFunction('test');
$response = $service->scripts->run($scriptId, $request);
$response = $response->getResponse();
$response = $response['result'];
return ($response);
} else {
$redirect_uri = 'http://' . $_SERVER['HTTP_HOST'] . '/email_database/php/oauth2callback.php';
header('Location: ' . filter_var($redirect_uri, FILTER_SANITIZE_URL));
}
}
?>
oauth2callback.php
<?php
require_once '../google-api-php-client/src/Google/autoload.php';
include 'functions.php';
$client = new Google_Client();
$client->setAuthConfigFile('client_secrets.json');
$client->setRedirectUri('http://' . $_SERVER['HTTP_HOST'] . '/email_database/dashboard/php/oauth2callback.php');
$client->setScopes(array(
'https://mail.google.com/'
));
$client->setAccessType('offline');
$redirect_uri = 'http://' . $_SERVER['HTTP_HOST'] . '/email_database/dashboard/php/read_email.php';
$username = $_SESSION['username'];
$user = getUser($username);
if($user['refresh_token'] == null){
if (! isset($_GET['code'])) {
$auth_url = $client->createAuthUrl();
header('Location: ' . filter_var($auth_url, FILTER_SANITIZE_URL));
} else {
//echo $_GET['code'];
$client->authenticate($_GET['code']);
$_SESSION['access_token'] = $client->getAccessToken();
$google_token = json_decode($_SESSION['access_token']);
print_r($google_token);
$refresh_token = $google_token->refresh_token;
addRefreshToken($username,$refresh_token);
//header('Location: ' . filter_var($redirect_uri, FILTER_SANITIZE_URL));
}
}
else {
$refresh_token = $user['refresh_token'];
$client->refreshToken($refresh_token);
$_SESSION['access_token']= $client->getAccessToken();
// header('Location: ' . filter_var($redirect_uri, FILTER_SANITIZE_URL));
}
?>

cakephp 3 - passing dates with json

Cakephp3, I am passing data to another page using Json, my issue seems to be on my new page where my created date is passed as a sting , and displays like '2016-05-16T17:21:10+0000' . How do i format that string to be left with '2016-05-16' ? I've tried setting it as a date, i tried using the i18nFormat with no success.
$http = new Client();
$response = $http->get('http://localhost:8383/mb-be/apis/getmaritimemessagelist.json');
$maritimes = $response->json['content'];
$cnt = count($maritimes);
for ($i=0; $i<$cnt; $i++) {
//var_dump($maritimes[$i]);
echo '<p class="brdr-bttm mrgn-lft-md ">';
echo $this->Html->link($maritimes[$i]['title'], array(
'controller' => 'messages',
'action' => 'view/'. $maritimes[$i]['id']
));
echo '<br />';
$date = $maritimes[$i]['created'];
echo $date;
echo '</p>';
}
I found a solution of this problem.
Here you can use DateTime::createFromFormat to format your created date. but it still has a problem with T inside the date '2016-05-16T17:21:10+0000', just because of timezone(I guess).
you can replace this T with space and got formatted created date as you want.
$http = new Client();
$response = $http->get('http://localhost:8383/mb-be/apis/getmaritimemessagelist.json');
$maritimes = $response->json['content'];
$cnt = count($maritimes);
for ($i=0; $i<$cnt; $i++) {
//var_dump($maritimes[$i]);
echo '<p class="brdr-bttm mrgn-lft-md ">';
echo $this->Html->link($maritimes[$i]['title'], array(
'controller' => 'messages',
'action' => 'view/'. $maritimes[$i]['id']
));
echo '<br />';
$date = $maritimes[$i]['created'];
//--------- Format created date --------
$string = str_replace("T"," ",$date);
$created_date = DateTime::createFromFormat('Y-m-d H:i:sO',$string)->format('Y-m-d');
echo $created_date;
echo '</p>';
}

How to make a json from youtube api v3 with a wp_cron

I'm doing a cron job in wordpress and it only worked once, it sent me an email but it never created the json file.
I want to save in a json file data from youtube api v3 in order not make petitions each time because youtube limit the petitions so I thought it will be convenient make a cache job with wp cron but this code is not working. I not sure where is the problem.
function isa_add_every_three_minutes( $schedules ) {
$schedules['every_three_minutes'] = array(
'interval' => 180,
'display' => __( 'Every 3 Minutes', 'textdomain' )
);
return $schedules;
}
add_filter( 'cron_schedules', 'isa_add_every_three_minutes' );
if ( !wp_next_scheduled('hook_saveVideos') ) {
wp_schedule_event( time(), 'every_three_minutes', 'hook_saveVideos' );
}
function saveVideos() {
$channel_id = "channelExample";
$user_id = "example";
$url = "https://www.googleapis.com/youtube/v3/playlistItems?part=snippet&maxResults=30&playlistId=".$cv_id."&key=".$user_id;
$data = file_get_contents($url);
$videos = json_decode($data, true);
$videos = $videos['items'];
$dVideos = array();
for ($i=0; $i < count($videos) ; $i++) {
$title = $videos[$i]['snippet']['title'];
$description = $videos[$i]['snippet']['description'];
$videoId = $videos[$i]['snippet']['resourceId']['videoId'];
$id = "v".$i;
$dVideos[$id] = array("title"=>$title, "description"=>$description, "videoId"=>$videoId);
}
$ruta = "http://localhost/example/cache";
$fp = fopen($ruta, 'w');
fwrite($fp, json_encode($dVideos ));
fclose($fp);
wp_mail('user#example.com', 'Mail mandado por el cron', 'Hola, esto es un correo enviado automáticamente');
}

Display ratio as decimal between two PHP variables

I log stats for my Minecraft server and display player's in-game stats on my site. I log kills and deaths already, but now I'm trying to get a functioning kill/death ratio.
I am trying to display the kills/deaths in a decimal ratio format (Example: 3789 kills - 5711 deaths would give you a K/DR of 0.663)
elseif ($_GET['task'] == 'stats') {
$get_player = $_GET['player'];
$get_db = 'engine';
$result = mysql_query("SELECT * FROM $get_db WHERE name = '" . mysql_real_escape_string($get_player) . "'", $link);
while($data = mysql_fetch_array($result)) {
echo '{"task":"viewstats","kills":"'; echo $data['kills'];
echo '","deaths":"'; echo $data['deaths'];
echo '","joins":"'; echo $data['joins'];
echo '","quits":"'; echo $data['quits'];
echo '","kicked":"'; echo $data['kicked'];
echo '"}';
}
}
I call upon them in a table like this:
<td><?php echo empty($stats) ? "--" : substr($stats->kills, 0, 50); ?></td>
<td><?php echo empty($stats) ? "--" : substr($stats->deaths, 0, 50); ?></td>
The above PHP code is an API file and the MySQL is already enabled in it - I only posted a snippet of the API though.
You can do this:
echo json_encode(array(
'task' => 'viewstats',
'kills' => $data['kills'],
'deaths' => $data['deaths'],
'joins'=> $data['joins'],
'quits' => $data['quits'],
'kicked' => $data['kicked'],
// then ratio
'ratio' => $data['kills'] / $data['deaths'],
));
//**Make sure this Function is declared at the top of your script.**
function MySQLi_quickConnect()
{
$host = 'somewebsite.db.120327161.hostedresource.com'; //or 'http://localhost'
$username = '<YOUR USERNAME>';
$password = '<YOUR PASSWORD>';
$database = '<YOUR DATABASES NAME>';
$db = new MySQLi($host,$username,$password,$database);
$error_message = $db->connect_error;
if($error_message != NULL){die("Error:" . $error_message . "<br>" . "Occured in function
MySQLi_quickConnect");}
return $db;
}
//Replace your code with this:
elseif($_GET['task'] == 'stats') {
$get_player = $_GET['player'];
$get_db = 'engine';
$mysqli = MySQLi_quickConnect();
$query = ('SELECT kills, deaths, FROM ? WHERE name = ? ');
if ($stmt = $mysqli->prepare($query)) {
$stmt->bind_param("ss", $get_db, $get_player);
$stmt->execute();
$stmt->bind_result($kills, $deaths);
}
while ($stmt->fetch()) {
$kdr = $kills/$deaths;
echo "You have a K/DR of " . $kdr . "<br>";
}
$stmt->close();
}
Note: Verify your Database connection, table names, and $_Get variables.

How to show data using codeigniter or mysql query from my example

My Example Tables are below,
$hdn_roll[0] =0;
$i =0;
foreach($results as $row):
$i++;
$roll = $row->roll;
$questions = $row->questions;
$hdn_roll[$i] = $roll;
$count_ad = array_count_values($hdn_roll);
$count_sp = $count_ad[$hdn_roll[$i]];
$j = 0;
if($hdn_roll[$i] != $hdn_roll[($i-1)]):
if($count_sp ==1):
create_row_after_balloting($roll,$questions);
endif;
else:
$j++;
$data['roll'.$j] = $roll;
$data['questions'.$j] = $questions;
endif;
endforeach;
Actually, I want to display Like Table:B from Table:A(MySQL Database).
Above Code, I can display 1001 to 1009 but Remain 1003,1006,1008,1006 are not display.
On the other hand, Same Roll Can't stay another(1003) after one(1003)
How can i solve it in PHP code or MySQL Query.
Try this may be its help you.
First create function in model file:
<?php
function getstudentinfo()
{
//return $this->db->get_where('studnet_info', array('status' => 3));
return $this->db->distinct('roll')->select('roll,questions')->where(array('status' => 3));
}
Then call in controller file:
function index()
{
$data['student_detail'] = $this->yourmodeelname->getstudentinfo();
$this->load->view('your view file name');
}
Then get in view file:
if(isset($student_detail)) {
foreach($student_detail as $student)
{
echo $student['roll'];
echo '</br>';
echo $student['questions'];
}
}
?>