Google Calendar :: Update Existing Attendee Status using PHP API - google-calendar-api

I am using google calendar API V3 . I want to update existing attendee status using PHP API. I am using following code. But it seems this code is not updating existing attendee. For example consider (shohag#test.com,enamul#test.com,test#test.com) are attendees of certain event and all of them event status are pending. After executing this code i see only test#test.com in accepted condition. Here is my code.
<?php
require_once '../../src/Google_Client.php';
require_once '../../src/contrib/Google_CalendarService.php';
session_start();
$client = new Google_Client();
$client->setApplicationName("Google Calendar PHP Starter Application");
$client->setClientId('MYCLIENT ID');
$client->setClientSecret('MY SECRET');
$client->setRedirectUri('MY RETURN URL');
$client->setDeveloperKey('MY DEV KEY');
$cal = new Google_CalendarService($client);
if (isset($_GET['logout'])) {
unset($_SESSION['token']);
}
if (isset($_GET['code'])) {
$client->authenticate($_GET['code']);
$_SESSION['token'] = $client->getAccessToken();
header('Location: http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF']);
}
if (isset($_SESSION['token'])) {
$client->setAccessToken($_SESSION['token']);
}
if ($client->getAccessToken()) {
// First retrieve the event from the API.
$event = new Google_Event($cal->events->get('primary', 'EVENT ID'));
$attendee1 = new Google_EventAttendee();
$attendee1->setEmail('test#test.com');
$attendee1->setResponseStatus('accepted');
$attendees = array($attendee1);
$event->attendees = $attendees;
$updatedEvent = $cal->events->update('primary', $event->getId(), $event);
$_SESSION['token'] = $client->getAccessToken();
} else {
$authUrl = $client->createAuthUrl();
print "<a class='login' href='$authUrl'>Connect Me!</a>";
}
How can i change status of existing attendee? Here is update API link https://developers.google.com/google-apps/calendar/v3/reference/events/update .Let me know.

Just like in the Google Calendar UI, attendee status can only be modified by the attendee their self. If all of these users are in the same Google Apps domain, you can authorize as the attendee via a service account and change their status as them.

Related

Google Analytics API using PHP with service account

I have been searching and looking this up for two days now and can't figure out where I am going wrong. I am attempting to pull data from my google analytics account using php. I have followed all the steps to set up a service account and downloaded the JSON file. Here is the code I am using:
// Load the Google API PHP Client Library
require_once ('/google-api-php-client-1-master/src/Google/autoload.php');
$KEY_FILE_LOCATION = '/inc/ac_key.json';
// Create and configure a new client object.
$client = new Google_Client();
$client->setApplicationName("Hello Analytics Reporting");
$client->setAuthConfig($KEY_FILE_LOCATION);
$client->setScopes(['https://www.googleapis.com/auth/analytics.readonly']);
$analytics = new Google_Service_Analytics($client);
function getResults($analytics, $profileId) {
// Calls the Core Reporting API and queries for the number of sessions
// for the last seven days.
return $analytics->data_ga->get(
'ga:' . $profileId,
'30daysAgo',
'today',
'ga:pageviews'
);
}
$profile = $r['google_analytics'];
$results = getResults($analytics, $profile);
$month = date('n');
$year = date('Y');
$results->setMonth($month,$year);
$visits = $results->getVisitors();
$views = $results->getPageviews();
/* build tables */
if(count($visits)) {
foreach($visits as $day=>$visit) {
$flot_datas_visits[] = '['.$day.','.$visit.']';
$flot_datas_views[] = '['.$day.','.$views[$day].']';
}
$flot_data_visits = '['.implode(',',$flot_datas_visits).']';
$flot_data_views = '['.implode(',',$flot_datas_views).']';
}
I am getting an error for an invalid client_secret.json file but I am attempting to authenticate using a service account so I am not sure what is going on here. I am then attempting to plot the data in a flot table but I am not worried about that part yet as I am still trying to get through this first hurdle. Any help would be appreciated!
I'm not quite up-to-date with the Google PHP API client, but apparently there are different versions on offer - when I cloned the repo I got the version that you app use and I did not get it to work with my credentials file. I then installed the current version of the library via composer:
composer require google/apiclient:^2.0
I was then able to access a Google Analytics with the following code:
<?php
include_once __DIR__ . '/vendor/autoload.php';
date_default_timezone_set('America/Los_Angeles');
$client = new Google_Client();
$client->setAuthConfig('/path/to/credentials.json');
$client->setApplicationName("Client_Library_Examples");
$client->setScopes(['https://www.googleapis.com/auth/analytics.readonly']);
$service = new Google_Service_Analytics($client);
function getResults($service, $profileId) {
return $service->data_ga->get(
'ga:' . $profileId,
'30daysAgo',
'today',
'ga:pageviews'
);
}
$profile= "80493610";
$results = getResults($service, $profile);
print_r($results);
With a bit of poking around I managend to get an instance of the analytics service with the old version from your example. Apparently you have to use the loadServiceAccountJson function rather than setAuthConfig
<?php
// Load the Google API PHP Client Library
require_once ('google-api-php-client/src/Google/autoload.php');
$KEY_FILE_LOCATION = '/path/to/credentials.json';
// Create and configure a new client object.
$client = new Google_Client();
$client->setApplicationName("Hello Analytics Reporting");
$scopes = ['https://www.googleapis.com/auth/analytics.readonly'];
$client->loadServiceAccountJson($KEY_FILE_LOCATION, $scopes);
$analytics = new Google_Service_Analytics($client);
print_r($analytics);

Which PHP Script File is needed for ical() class in Google Calendar PHP API v3

I am getting an error in a PHP script I am building:
Fatal error: Class 'ical' not found in /home/abc/public_html/app/mods/googleCalendar_3.0/cache_events.php on line 74
Here is a snippet from my script file:
define('CLIENT_ID', 'ASDLJJLDSJLASDJLajdl;jdsljkASD;LKJASDLKJASD.apps.googleusercontent.com');
require_once('autoload.php'); // 2014-11-24 part of /usr/local/lib/php/google-api-php-client
require_once('/usr/local/lib/php/google-api-php-client/src/Google/Client.php'); // 2014-11-25
require_once('/usr/local/lib/php/google-api-php-client/src/Google/Service/Calendar.php'); // 2014-11-25
$ical = new ical('https://www.google.com/calendar/ical/CLIENT-ID/public/basic.ics');
$eventListArray = array_filter($ical -> events(), "locationfilter");
$eventCount = count($eventListArray);
print_r($eventListArray); echo "<br>";
echo "Event Count:" . $eventCount;echo "<br>";
exit;
I am simply trying to retrieve all events in my public calendar
Notes:
Calendar is publicly viewable
Just to make sure, I added my Auth & API's > Credentials > Service Account > Email Address to it just to be safe
If you want to use a service account your code is off quite a bit. I cant test this code my local webserver is acting up but it should be close you may have to tweek the $service->Events->list(); part it was kind of a guess. Make sure that you have the Service account email address added as a user on the calendar in question and it should work.
session_start();
require_once 'Google/Client.php';
require_once 'Google/Service/Calendar.php';
/************************************************
The following 3 values an befound in the setting
for the application you created on Google
Developers console. Developers console.
The Key file should be placed in a location
that is not accessable from the web. outside of
web root. web root.
In order to access your GA account you must
Add the Email address as a user at the
ACCOUNT Level in the GA admin.
************************************************/
$client_id = '1046123799103-nk421gjc2v8mlr2qnmmqaak04ntb1dbp.apps.googleusercontent.com';
$Email_address = '1046123799103-nk421gjc2v8mlr2qnmmqaak04ntb1dbp#developer.gserviceaccount.com';
$key_file_location = '629751513db09cd21a941399389f33e5abd633c9-privatekey.p12';
$client = new Google_Client();
$client->setApplicationName("Client_Library_Examples");
$key = file_get_contents($key_file_location);
// seproate additional scopes with a comma
$scopes ="https://www.googleapis.com/auth/calendar";
$cred = new Google_Auth_AssertionCredentials(
$Email_address,
array($scopes),
$key
);
$client->setAssertionCredentials($cred);
if($client->getAuth()->isAccessTokenExpired()) {
$client->getAuth()->refreshTokenWithAssertion($cred);
}
$service = new Google_Service_Calendar($client);
// you should only need to do this once print this and you will
// find the calendarId for the one you are looking for.
$calendars = $service->calendarList->list();
$events = $service->events->list($yourCalendarID);
Note: all you need is the Google Dir you can remove everything above that you dont really need it. Code was edited from the only tutorial i have that shows this in PHP.

Google Analytics API Automated Login

I have this panel that i'm developing at my company where i will show the user's information from Google Analytics but i don't want the user to authorize or log in with his account every time he comes to the panel.
What i would like to do is: on the first time using my panel he would connect his Google account and i would save some info and on the next time he connects at my panel i would use this saved info to log on his account so i can list the Analytics info without ask for his permission or list that info even if he's not connected on is Google account right now.
Basically i would log in his account automatically and permit the 'app' to show the information.
I already have some code that connects on the API if he is connected on is Google account, but when he's not i get the login screen where he has to provide his email e password.
What i have so far is this:
<?php
require_once 'Google/Client.php';
require_once 'Google/Service/Analytics.php';
session_start();
$client = new Google_Client();
$client->setApplicationName("Google Analytics PHP Starter Application");
$client->setClientId('KEY');
$client->setClientSecret('SECRET');
$client->setRedirectUri('RETURN URI');
$client->setScopes('https://www.googleapis.com/auth/analytics.readonly');
$client->setAccessType('offline');
$service = new Google_Service_Analytics($client);
if(isset($_GET['logout']))
{
unset($_SESSION['token']);
}
if(isset($_GET['code']))
{
$client->authenticate($_GET['code']);
$_SESSION['token'] = $client->getAccessToken();
$redirect = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'];
header('Location: ' . filter_var($redirect, FILTER_SANITIZE_URL));
}
if(isset($_SESSION['token']))
{
$client->setAccessToken($_SESSION['token']);
}
if($client->getAccessToken())
{
$props = $service->management_webproperties->listManagementWebproperties("12008145");//~all
print "<h1>Web Properties</h1><pre>" . print_r($props, true) . "</pre>";
$accounts = $service->management_accounts->listManagementAccounts();
//print "<h1>Accounts</h1><pre>" . print_r($accounts, true) . "</pre>";
$segments = $service->management_segments->listManagementSegments();
//print "<h1>Segments</h1><pre>" . print_r($segments, true) . "</pre>";
$goals = $service->management_goals->listManagementGoals("~all", "~all", "~all");
//print "<h1>Goals</h1><pre>" . print_r($goals, true) . "</pre>";
$_SESSION['token'] = $client->getAccessToken();
}
else
{
$authUrl = $client->createAuthUrl();
header("Location: " . $authUrl);
}
?>
Is there any way to do that ? I have looked for it around everywhere and couldn't find something near it.
In google Api's, when user authenticate the first time, you receive a CODE (which you are already getting i suppose). Use this code to get refresh token (lifetime is (always), until and unless, user revokes the permissions). Save this refresh token in Database for further use. Refresh token is used to get access token(lifetime is a short time, returned in the expires in argument). Access token is to give you access to your user's data for some time. You can keep using refresh token to get access token whenever you need to access your user's data.
Whenever you want to access user's data, use refresh token to get access token and then use that access token to get user's data.
In your case, you are using google api php client, you can use Methods in Client.php like:
getAccessToken()---to get refresh token the first time. When you call this method, you get back a json in a form: let this json name be $accessToken
$accessToken = {"access_token":"TOKEN", "refresh_token":"TOKEN", "token_type":"Bearer",
"expires_in":3600,"id_token":"TOKEN", "created":1320790426}
parse json to take refresh_token($refreshToken = $accessToken.refresh_token) and save it for later use.
setAccessToken($accessToken)---call this to set the OAuth access token.
refreshToken($refreshToken)---Fetches a fresh OAuth access token with the given refresh token.
For further clearity, look at Client.php and also read:
https://developers.google.com/accounts/docs/OAuth2WebServer

Adding a wordpress user to Salesforce Contact

I'm trying to do a relatively simple task by hooking into the Wordpress registration and adding the user that's being registered to a Salesforce db. When I run the Salesforce db code outside of Wordpress it works flawlessly, but when I test this by registering on my wordpress website, I get an error stating: INVALID_LOGIN: Invalid username, password, security token; or user locked out.
Additionally, I receive this error from Wordpress "Cannot modify header information - headers already sent" which doesn't allow me to view the entire object data that's being sent to Salesforce.
This is my code:
$SF_USERNAME = 'test';
$SF_PASSWORD = 'test';
define( 'CD_PLUGIN_PATH', plugin_dir_path( __FILE__ ) );
require_once (CD_PLUGIN_PATH . 'Toolkit/soapclient/SforceEnterpriseClient.php');
require_once (CD_PLUGIN_PATH . 'Toolkit/soapclient/SforceHeaderOptions.php');
function add_user_to_SF($user_id) {
$user = get_userdata($user_id);
try {
$mySforceConnection = new SforceEnterpriseClient();
$mySoapClient = $mySforceConnection->createConnection(CD_PLUGIN_PATH . 'Toolkit/soapclient/enterprise.wsdl.xml');
$mylogin = $mySforceConnection->login($SF_USERNAME, $SF_PASSWORD);
print '<pre>';
print_r($mylogin);
print '</pre>';
print '<br/><br/>';
$sObject = new stdclass();
$sObject->FirstName = $user->first_name;
$sObject->LastName = $user->last_name;
$sObject->Email = $user->user_email;
//echo "**** Creating the following:\r\n";
$createResponse = $mySforceConnection->create(array($sObject), 'Contact');
$ids = array();
foreach ($createResponse as $createResult) {
print_r($createResult);
array_push($ids, $createResult->id);
}
} catch (Exception $e) {
$errors->add( 'demo_error', __(print_r($_POST),'mydomain') );
$errors->add( 'demo_error', __($mySforceConnection->getLastRequest(),'mydomain') );
$errors->add( 'demo_error', __($e->faultstring,'mydomain') );
return $errors;
}
}
add_filter( 'registration_errors', 'add_user_to_SF', 10, 3 );
This is a php scope issue.
Adding:
global $SF_USERNAME;
global $SF_PASSWORD;
inside the function fixed the problem.
It looks like you might be missing the security token. It's appended to the end of the password.
This link explains how to generate the token
https://login.salesforce.com/help/doc/en/user_security_token.htm
You need to add your salesforce account security token with password
eg. Password - "testing"
Security Token - "2321njjn32j32"
You need to pass as - "testing2321njjn32j32"
This will work properly.

application loaded in iframe on facebook

I have an app loaded in iframe on facebook.
But after allow and redirected to my facekooksite from facebook authorization i cant fetch the "code" from the querrystring from within my code (because loaded in an iframe on facebook)
How will i be able to fetch the "code" parameter?
I guess you are following the server-side authentication flow. But since you are using Apps on Facebook, this flow will change since Facebook is sending a signed_request to your canvas iframe:
<?php
$app_id = "YOUR_APP_ID";
$canvas_page = "YOUR_CANVAS_PAGE_URL";
$auth_url = "https://www.facebook.com/dialog/oauth?client_id="
. $app_id . "&redirect_uri=" . urlencode($canvas_page);
$signed_request = $_REQUEST["signed_request"];
list($encoded_sig, $payload) = explode('.', $signed_request, 2);
$data = json_decode(base64_decode(strtr($payload, '-_', '+/')), true);
if (empty($data["user_id"])) {
echo("<script> top.location.href='" . $auth_url . "'</script>");
} else {
echo ("Welcome User: " . $data["user_id"]);
}
?>
Obviously when you are on Facebook, the user is either connected to your app or not so if he/she is not connected then you redirect them to the authentication URL.

Resources