I am writing an app in PHP which will connect to my domains's Google Classroom. However I get the following error when I try to do anything with the Google Classroom API:
Message: Error calling GET https://www.googleapis.com/v1/courses?pageSize=100: (404) Not Found
My code so far:
$scopes = array(
'https://www.googleapis.com/auth/classroom.courses',
'https://www.googleapis.com/auth/classroom.courses.readonly',
'https://www.googleapis.com/auth/classroom.rosters',
'https://www.googleapis.com/auth/classroom.rosters.readonly'
);
$gServiceEmail = "random#developer.gserviceaccount.com";
$gServiceKey = file_get_contents("../path/to/cert.p12");
$client = new Google_Client();
$gAuth = new Google_Auth_AssertionCredentials(
$gServiceEmail,
$scopes,
$gServiceKey
);
$gAuth->sub = "user#mydomain.com";
$client->setAssertionCredentials($gAuth);
$service = new Google_Service_Classroom($client);
$results = $service->courses->listCourses();
I have enabled the scopes in the API Settings in the Google Admin Console for the service account and enabled the api in the developer console. Where am I going wrong?
I think your endpoint is wrong according to the documentation of Classroom API. Try changing it to https://classroom.googleapis.com
sample request:
GET https://classroom.googleapis.com/v1/courses?pageSize=100&key={YOUR_API_KEY}
Course with id is not found.
For a list of courses, use the courses.list(), as shown in the following sample.
$client = getClient();
$service = new Google_Service_Classroom($client);
// Print the first 10 courses the user has access to.
$optParams = array(
'pageSize' => 10
);
$results = $service->courses->listCourses($optParams);
if (count($results->getCourses()) == 0) {
print "No courses found.\n";
} else {
print "Courses:\n";
foreach ($results->getCourses() as $course) {
printf("%s (%s)\n", $course->getName(), $course->getId());
}
}
References:
https://developers.google.com/classroom/quickstart/php?hl=en
https://developers.google.com/classroom/guides/manage-courses?hl=en
Related
I am using Google MyBsiness API for fetching all business reviews.
But I am unable to familer with PHP syntax and GET, POST method use in MYBusiness.
After Oath here are code i am using to fetch review
$mybusinessService = new Google_Service_Mybusiness($client);
$accessToken = file_get_contents($credentialsPath);
$reviews = $mybusinessService->accounts_locations_reviews;
echo '<pre>';print_r($reviews->get('ArtechDev'));exit;
But i am getting error 404 (Fatal error: Uncaught exception 'Google_Service_Exception' with message)
I am sure that I don't know how to pass param and which things needed for it. I am logged in as account which having Location 'ArtechDev' also please
let me know that where can i call
https://mybusiness.googleapis.com/v3/accounts/account_name/locations/location_name/reviews
Thanks
I hope you had found the answer to your question a long time ago, anyway I'll leave this hoping help someone else.
/*$accounts previusly populate*/
/*(GMB - v4)*/
$credentials_f = "google_my_business_credentials_file.json";
$client = new Google_Client();
$client->setApplicationName($aplicattion_name);
$client->setDeveloperKey($developer_key);
$client->setAuthConfig($credentials_f);
$client->setScopes("https://www.googleapis.com/auth/plus.business.manage");
$client->setSubject($accounts->email);
$token = $client->refreshToken($accounts->refresh_token);
$client->authorize();
$locationName = "accounts/#######/locations/########";
$mybusinessService = new Google_Service_Mybusiness($client);
$reviews = $mybusinessService->accounts_locations_reviews;
do{
$listReviewsResponse = $reviews->listAccountsLocationsReviews($locationName, array('pageSize' => 100,
'pageToken' => $listReviewsResponse->nextPageToken));
$reviewsList = $listReviewsResponse->getReviews();
foreach ($reviewsList as $index => $review) {
/*Accesing $review Object
* $review->createTime;
* $review->updateTime;
* $review->starRating;
* $review->reviewer->displayName;
* $review->reviewReply->comment;
* $review->getReviewReply()->getComment();
* $review->getReviewReply()->getUpdateTime();
*/
}
}while($listReviewsResponse->nextPageToken);
$acounts comes from:
$mybusinessService = new Google_Service_MyBusiness(...);
$accounts = $mybusinessService->accounts;
I'm developing an e-commerce student project using php (laravel framework), I have found lots of tutorials about using google analytics, but very rarely about how to retrieve data to my web site using APIs. I have the following questions:
how to retrieve all data from google analytics to my web site using API.
how to retrieve all data of UserID view? because I want to get all data about a specific user to know what is he/she (browser, language, country, Os .... etc) to use it to personalize my web site.
please any idea or help will be appreciated, I'm run out of time, people help
below is my API code that I'm using :
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
class HomeController extends Controller
{
public function getAnalyticsSummary(Request $request){
$from_date = date("Y-m-d", strtotime($request->get('from_date',"7 days ago")));
$to_date = date("Y-m-d",strtotime($request->get('to_date',$request->get('from_date','today')))) ;
$gAData = $this->gASummary($from_date,$to_date) ;
return $gAData;
}
//to get the summary of google analytics.
private function gASummary($date_from,$date_to) {
$service_account_email = 'get-data-analytics#analytics-api-project-148820.iam.gserviceaccount.com';
// Create and configure a new client object.
$client = new \Google_Client();
$client->setApplicationName("any name");
$analytics = new \Google_Service_Analytics($client);
$cred = new \Google_Auth_AssertionCredentials(
$service_account_email,
array(\Google_Service_Analytics::ANALYTICS_READONLY),
"-----BEGIN PRIVATE KEY-----\nMIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQCrzw1R6ca16zYQ\n3ozuTlNVbvNWDPODW6NVrnny08V4ycd/ugvTQeU3EKno6mJ8iXNJ/3GXOz52iaRd\nGRKbfrPomK7gt6+F7EHVdpTfbc/u7TIJi5NbYzXS4jIXhIJhB4bGjzsnTGTY/6pF\nFmW/wgX2Y6n31EWyz2q5MiZDC5lEPrmNk/gOgWOyRHCVNHtBcyFdA3+w2or6ix5l\nrKlCwUkkzKAPb4OSvfDMz8o+h6r433E4+6MMHE/mf53CkX1DbDZIlZbUntYLoh19\n0oxKCufjfFEKqzxgTZxIbG5rK7jdrOFLuQwnaoKkUT0HAQTGnGoYrABo9HGjlgwg\n7rHzh+OzAgMBAAECggEBAKcRq8E41Ft4w1V6JI9jqRON1aCa7X2R8e3SwZFJL2C6\nzn28+9zN2khGswLkUSsLOgn+FYZbPO1mAWfqhragafBH8N5ioJNZX9dk/XWbQjTz\ngNHZYUzf16oe/VjzKRmTiRKym3ImjnaZfwi5s+3ZjZS/67ssNy6fFgfK5XwS3lKG\nFzAZYgCMyJIz8Cz9mHAHKmQELH29xiPNDSSCuAbScptOdNJvBB9Vvpu5b+/LtdWI\naBYLuZgMOSNgJiQFBjj/+RY5yBi9pL5aHYGHJJZnWp1CbxRQIN+xe5jBbpHZ6PWH\nUjoCfMkM+IWBNjlKOWCC/APFpGuDqYMRuHfakPvWIXECgYEA4otETO0hR00SceKt\nGXYtIX6ZfdK6K87EPTFofMXAvcH7CWU3Tr2+3pI/DWUD1pPEEfsOZpaS5Ry37IrQ\nVmhkS2j5QxYJ+NfEvjc17rdJuuwJeCeELDFNxsTvhk7yK6y75F7BFQH/dIcc7MYg\nTL11B340TpPlJtulnxLTW7G3nFkCgYEAwiXfGnpmuPE1yyGdux4mY1Eyp6ZmxC0o\nb+DIBqRRlwY23m7pv3g7a0GAqLIFaW7c/1iVlyoDg24eZ8YtSehtR0B5LEiExBaY\n7UpkqHosvCqgCH94O/Mas+DUv9Sfqy82geEagB65Cf+uLr/ixNbKiK12G29O/V7M\nCar/=========================================================================================================================================================================================================================================x/NCNpGaW7zKvAoGAffG7PqgXYNtqQ3MavgLF\nKtQFMzT65kI5AfXPpyzgBDKr84lhvdUddvK/FZg/mIuoLRLSgnYPnAv3s5yhleZ5\n7LGyo5fXXH7XUm2nNt+XZoV1rt6y+WgZi103M+fuv3GXYBdbOonPHopRzw3uzLIA\n9ovyAV95jOu9ybk4YgQXm5I=\n-----END PRIVATE KEY-----\n"
);
$client->setAssertionCredentials($cred);
if($client->getAuth()->isAccessTokenExpired()) {
$client->getAuth()->refreshTokenWithAssertion($cred);
}
$optParams = [
'dimensions' => 'ga:date',
'sort'=>'-ga:date'
] ;
$results = $analytics->data_ga->get(
'ga:133119102',
$date_from,
$date_to,
/*'ga:sessions,ga:users,ga:pageviews,ga:bounceRate,ga:hits,ga:avgSessionDuration',*/
'ga:bounceRate',
$optParams
);
$rows = $results->getRows();
$rows_re_align = [] ;
foreach($rows as $key=>$row) {
foreach($row as $k=>$d) {
$rows_re_align[$k][$key] = $d ;
}
}
$optParams = array(
'dimensions' => 'rt:medium'
);
try {
$results1 = $analytics->data_realtime->get(
'ga:132964552',
'rt:activeUsers',
$optParams);
// Success.
} catch (apiServiceException $e) {
// Handle API service exceptions.
$error = $e->getMessage();
}
$active_users = $results1->totalsForAllResults ;
return view('myGoogle.getGoogle', [
'data'=> $rows_re_align ,
/* 'summary'=>$results->getTotalsForAllResults(),*/
/* 'active_users'=>$active_users['rt:activeUsers']*/
]) ;
}
}
User id is used for internal processing of users across multiple seasons. Example you have a user who uses your website and your moblie application this would technically be two sessions. However if you pass the User id you have for this user when they are logged into there account on your system. You are telling Google analytics this is the same person.
User Id is not something however that you can extract out of the API its used mainly for internal processing. Assuming that your user id is a non user specific value you can also set it as a custom dimension which you can then extract out using the API.
I have a web app and trying to find out which users in google domain have installed my app. I've tried to use code from here: Determine if a google user's domain has my marketplace app installed, but it doesn't works. I am still getting error "(403) Not authorized to access the application ID" in response.
Code:
$private_key = file_get_contents('path_to_p.12_key');
$service_account_name = '{service_acc_name}'; // name from developers console
$cred = new Google_Auth_AssertionCredentials($service_account_name, array('https://www.googleapis.com/auth/appsmarketplace.license'), $private_key);
$client = new Google_Client();
$client->setAssertionCredentials($cred);
$url = "https://www.googleapis.com/appsmarket/v2/licenseNotification/{appID}";
$httpRequest = new Google_Http_Request($url, 'GET');
$httpRequest->setBaseComponent($client->getBasePath());
$httpRequest = $client->getAuth()->sign($httpRequest);
try
{
$result = $client->execute($httpRequest);
}
catch (Exception $e)
{
echo $e->getMessage();
}
I've also added https://www.googleapis.com/auth/appsmarketplace.license scope in project settings in developers console.
I can't get what's wrong.
OK, I've solved it. You must add all scopes to your service account object that used by your app (not just that scopes you are really want to use by service account):
$cred = new Google_Auth_AssertionCredentials($service_account_name, array('https://www.googleapis.com/auth/userinfo.email', 'https://www.googleapis.com/auth/userinfo.profile', 'https://www.googleapis.com/auth/admin.directory.user.readonly', 'https://www.googleapis.com/auth/admin.directory.user', 'https://www.googleapis.com/auth/appsmarketplace.license'), $private_key);
I'm trying to use a service account to create entries on a Google calendar. I'm really close on this, but the very last line won't work. I get a 500 Internal Service Error when I let this run. Otherwise, the program runs error free, for whatever that is worth.
The Calendar.php file contents can be found here. The insert() method that I am trying to call begins on line 1455 of that file.
<?php
function calendarize ($title, $desc, $ev_date, $cal_id) {
session_start();
/************************************************
Make an API request authenticated with a service
account.
************************************************/
set_include_path( '../google-api-php-client/src/');
require_once 'Google/Client.php';
require_once 'Google/Service/Calendar.php';
// (not real keys)
$client_id = '843319906820-jarm3f5ctbtjj9b7lp5qdcqal54p1he6.apps.googleusercontent.com';
$service_account_name = '843319906820-jarm3f5ctbtjj7b7lp5qdcqal54p1he6#developer.gserviceaccount.com';
$key_file_location = '../google-api-php-client/calendar-249226a7a27a.p12';
// echo pageHeader("Service Account Access");
if (!strlen($service_account_name) || !strlen($key_file_location))
echo missingServiceAccountDetailsWarning();
$client = new Google_Client();
$client->setApplicationName("xxxx Add Google Calendar Entries");
if (isset($_SESSION['service_token'])) {
$client->setAccessToken($_SESSION['service_token']);
}
$key = file_get_contents($key_file_location);
$cred = new Google_Auth_AssertionCredentials(
$service_account_name,
array('https://www.googleapis.com/auth/calendar'),
$key
);
$client->setAssertionCredentials($cred);
if($client->getAuth()->isAccessTokenExpired()) {
$client->getAuth()->refreshTokenWithAssertion($cred);
}
$_SESSION['service_token'] = $client->getAccessToken();
// Prior to this, the code has mostly come from Google's example
// google-api-php-client / examples / service-account.php
// and relates to getting the access tokens.
// The rest of this is about setting up the calendar entry.
//Set the Event data
$event = new Google_Service_Calendar_Event();
$event->setSummary($title);
$event->setDescription($desc);
$start = new Google_Service_Calendar_EventDateTime();
$start->setDate($ev_date);
$event->setStart($start);
$end = new Google_Service_Calendar_EventDateTime();
$end->setDate($ev_date);
$event->setEnd($end);
$calendarService = new Google_Service_Calendar($client);
$calendarList = $calendarService->calendarList;
$events = $calendarService->events;
// if I leave this line, my code won't crash (but it won't do anything, either)
//echo "here"; die();
$events.insert($cal_id, $event, false);
}
?>
I figured this out. Since I don't see any complete examples of using service accounts with API v3, I'm just going to post my complete solution for reference. There are a few of things that you need to do in addition to implementing the code, however:
1) You need to go to the Google Developer's console and mark your account as a 'service account'. This will differentiate it from a web application. The important difference is that nobody will be prompted to log in to their account before the events are added since the account will belong to your application, not an end user. For more information see this article, starting on page 5.
2) You need to create a public/private key pair. From the developer's console, click on Credentials. Under you service account, click on 'Generate new P12 key'. You'll need to store this somewhere. That file location becomes the $key_file_location variable string in the code below.
3) Also from the developer's console, you need to enable the Calendar API. From your project, on the left margin you'll see APIs. Select that and find the Calendar API. Click it, accept the terms of service, and verify that it is now displayed under Enabled APIs with a status of On
4) In Google Calendar that you want to add events to, under settings, click Calendar Settings then on 'Share this Calendar' at the top. Under 'Share with specific people' in the 'Person' field, paste in the email address from the service account credentials. Change the permission settings to 'Make changes to events'. Don't forget to save the change.
Then, implement this code somewhere.
Comment if something is confusing or omitted. Good luck!
<?php
function calendarize ($title, $desc, $ev_date, $cal_id) {
session_start();
/************************************************
Make an API request authenticated with a service
account.
************************************************/
set_include_path( '../google-api-php-client/src/');
require_once 'Google/Client.php';
require_once 'Google/Service/Calendar.php';
//obviously, insert your own credentials from the service account in the Google Developer's console
$client_id = '843319906820-xxxxxxxxxxxxxxxxxxxdcqal54p1he6.apps.googleusercontent.com';
$service_account_name = '843319906820-xxxxxxxxxxxxxxxxxxxdcqal54p1he6#developer.gserviceaccount.com';
$key_file_location = '../google-api-php-client/calendar-xxxxxxxxxxxx.p12';
if (!strlen($service_account_name) || !strlen($key_file_location))
echo missingServiceAccountDetailsWarning();
$client = new Google_Client();
$client->setApplicationName("Whatever the name of your app is");
if (isset($_SESSION['service_token'])) {
$client->setAccessToken($_SESSION['service_token']);
}
$key = file_get_contents($key_file_location);
$cred = new Google_Auth_AssertionCredentials(
$service_account_name,
array('https://www.googleapis.com/auth/calendar'),
$key
);
$client->setAssertionCredentials($cred);
if($client->getAuth()->isAccessTokenExpired()) {
$client->getAuth()->refreshTokenWithAssertion($cred);
}
$_SESSION['service_token'] = $client->getAccessToken();
$calendarService = new Google_Service_Calendar($client);
$calendarList = $calendarService->calendarList;
//Set the Event data
$event = new Google_Service_Calendar_Event();
$event->setSummary($title);
$event->setDescription($desc);
$start = new Google_Service_Calendar_EventDateTime();
$start->setDateTime($ev_date);
$event->setStart($start);
$end = new Google_Service_Calendar_EventDateTime();
$end->setDateTime($ev_date);
$event->setEnd($end);
$createdEvent = $calendarService->events->insert($cal_id, $event);
echo $createdEvent->getId();
}
?>
Some helpful resources:
Github example for service accounts
Google Developers Console for inserting events in API v3
Using OAuth 2.0 to Access Google APIs
Here is the Google API Client 2.0 way to do
Follow Alex's Answer Go Google Developer's console to create Service Account, but create credential in JSON
Follow Google API Client Upgrade Guide, install by composer and include in the way of
require_once 'vendor/autoload.php';
Follow Alex's Answer to go to Google Calendar to share the calendar with Service Account ID
xxxxx#yyyy.iam.gserviceaccount.com
Take Ref. to below coding and the most important one is the calendar id should be the email of calendar creator, but not primary
<?php
require_once __DIR__.'/vendor/autoload.php';
session_start();
$client = new Google_Client();
$application_creds = __DIR__.'/secret.json'; //the Service Account generated cred in JSON
$credentials_file = file_exists($application_creds) ? $application_creds : false;
define("APP_NAME","Google Calendar API PHP"); //whatever
$client->setAuthConfig($credentials_file);
$client->setApplicationName(APP_NAME);
$client->addScope(Google_Service_Calendar::CALENDAR);
$client->addScope(Google_Service_Calendar::CALENDAR_READONLY);
//Setting Complete
//Go Google Calendar to set "Share with ..." Created in Service Account (xxxxxxx#sustained-vine-198812.iam.gserviceaccount.com)
//Example of Use of API
$service = new Google_Service_Calendar($client);
$calendarId = 'xxxx#gmail.com'; //NOT primary!! , but the email of calendar creator that you want to view
$optParams = array(
'maxResults' => 10,
'orderBy' => 'startTime',
'singleEvents' => TRUE,
'timeMin' => date('c'),
);
$results = $service->events->listEvents($calendarId, $optParams);
if (count($results->getItems()) == 0) {
print "No upcoming events found.\n";
} else {
echo "Upcoming events:";
echo "<hr>";
echo "<table>";
foreach ($results->getItems() as $event) {
$start = $event->start->dateTime;
if (empty($start)) {
$start = $event->start->date;
}
echo "<tr>";
echo"<td>".$event->getSummary()."</td>";
echo"<td>".$start."</td>";
echo "</tr>";
}
echo "</table>";
}
I'm trying to get some info of my Google Analytics account using PHP. I already followed the steps for creating a Service Account in the Google Console API in this answer. I'm using the Google API Client for PHP.
This is the code I've got so far:
<?php
$path_to_src = 'src';
// These files are in /src, upload its contents to your web server
require_once $path_to_src . '/Google_Client.php';
require_once $path_to_src . '/contrib/Google_AnalyticsService.php';
$path_to_keyfile = '***'; //my private key
// Initialise the Google Client object
$client = new Google_Client();
// Your 'Product name'
$client->setApplicationName('My App Name');
$client->setAssertionCredentials(
new Google_AssertionCredentials(
'**', //gserviceaccount mail
array('https://www.googleapis.com/auth/analytics.readonly'),
file_get_contents($path_to_keyfile)
)
);
// Get this from the Google Console, API Access page
$client->setClientId('***'); // my cliente ID
$client->setAccessType('offline_access');
$analytics = new Google_AnalyticsService($client);
// create service and get data
$service = new Google_AnalyticsService($client);
// We have finished setting up the connection,
// now get some data and output the number of visits this week.
// Your analytics profile id. (Admin -> Profile Settings -> Profile ID)
$analytics_id = 'ga:****'; // my profile id
$lastWeek = date('Y-m-d', strtotime('-1 week'));
$today = date('Y-m-d');
try {
$results = $analytics->data_ga->get($analytics_id,
$lastWeek,
$today,'ga:visits');
echo '<b>Number of visits this week:</b> ';
echo $results['totalsForAllResults']['ga:visits'];
} catch(Exception $e) {
echo 'There was an error : - ' . $e->getMessage();
}
I've enabled the openssl extension in PHP:
When browsing to the location of the php script, I just get a almost forever loading and the following error:
I'm using PHP 5.4.7:
After debuging the Google API Client code, it looks like the script is breaking at this line:
if (!openssl_sign($data, $signature, $this->privateKey, "sha256"))
Anything below this line does not get called. Looks like the error happens in this line. Is there a incompatibility here, or something?
One thing for starters you should change:
You instantiate the AnalyticsService twice. Take out the one you're not using:
$service = new Google_AnalyticsService($client);
See if that helps your problem at all.