I want to copy Google Doc spreadsheet file.This code I am using
function copyFile($service, $originFileId, $copyTitle) {
$copiedFile = new Google_DriveFile();
$copiedFile->setTitle($copyTitle);
try {
return $service->files->copy($originFileId, $copiedFile);
} catch (Exception $e) {
print "An error occurred: " . $e->getMessage();
}
return NULL;
}
require_once 'google-api-php-client/src/Google_Client.php';
require_once 'google-api-php-client/src/contrib/Google_DriveService.php';
$client = new Google_Client();
// Get your credentials from the console
$client->setClientId('myclientid');
$client->setClientSecret('myclient secret');
$client->setRedirectUri('urn:ietf:wg:oauth:2.0:oob');
$client->setScopes(array('https://www.googleapis.com/auth/drive'));
$service = new Google_DriveService($client);
copyFile($service,'my schema id','Copy Of Schema');
I am not able to get $service instance. SO I searched and get the above way to do but now it is giving 401 login required error.
Please help me
You need to check for sufficient authorization from the user
you need to generate authorization URL:
$authUrl = $client->createAuthUrl();
Redirect user to the authUrl
Make user paste the authorization code:
$authCode = trim(fgets(STDIN));
Authenticate
$accessToken = $client->authenticate($authCode);
$client->setAccessToken($accessToken);
Once above it done, you have now authenticated the user with OAuth to access drive.
Reference: Click here
Related
Google removed urn:ietf:wg:oauth:2.0:oob flow for installed / desktop / native applications. Making Google OAuth interactions safer by using more secure OAuth flows
This flow allowed for the redirect uri to return the authorization code back to an application that did not have a web server running.
The python samples for google-api-python-client compensate for this by spawning a local server.
flow = InstalledAppFlow.from_client_secrets_file(
'C:\YouTube\dev\credentials.json', SCOPES)
creds = flow.run_local_server(port=0)
This works as would be expected the authorization code is returned properly to the application.
My issue is with PHP, and the Google-api-php-client library
The current samples I have found created by google look as follows
// Request authorization from the user.
$authUrl = $client->createAuthUrl();
printf("Open the following link in your browser:\n%s\n", $authUrl);
print 'Enter verification code: ';
$authCode = trim(fgets(STDIN));
The user is prompted to copy the authorization code from the web browser themselves and paste it into the console window. In the past this was fine because urn:ietf:wg:oauth:2.0:oob would put the code in the web browser page. Now that is not happening. with the removal of oob we must use '"http://127.0.0.1"' when the authorization completes. a 404 error is displayed to the user in the browser window
However the url bar of the browser window displays the code
https://127.0.0.1/?state=xxxxxxx&code=xxxxxxxxxxxxxx&scope=googleapis.com/auth/youtube.readonly googleapis.com/auth/youtube.force-ssl googleapis.com/auth/yt-analytics.readonly
A user must then copy the code from the URL browser window. This is confusing for non-tenchincal users who see the 404 error and assume that something has gone wrong.
The issue is that the sample code does not spawn a web server as Python does in order to display the redirect uri properly.
My question: Is there a way to spawn a local server like python does with php? or is there an alternative to get this working again properly with php?
Full sample code
For anyone willing to test. Here is a full example.
create installed credentials on google cloud console
enable the google drive api.
Lots of code:
<?php
require __DIR__ . '/vendor/autoload.php';
if (php_sapi_name() != 'cli') {
throw new Exception('This application must be run on the command line.');
}
use Google\Client;
use Google\Service\Drive;
/**
* Returns an authorized API client.
* #return Client the authorized client object
*/
function getClient()
{
$client = new Client();
$client->setApplicationName('Google Drive API PHP Quickstart');
$client->setScopes('https://www.googleapis.com/auth/drive.readonly');
$client->setAuthConfig('C:\Development\FreeLance\GoogleSamples\Credentials\credentials.json');
$client->setAccessType('offline');
$client->setRedirectUri("http://127.0.0.1");
$client->setPrompt('select_account consent');
// Load previously authorized token from a file, if it exists.
// The file token.json stores the user's access and refresh tokens, and is
// created automatically when the authorization flow completes for the first
// time.
$tokenPath = 'token.json';
if (file_exists($tokenPath)) {
$accessToken = json_decode(file_get_contents($tokenPath), true);
$client->fetchAccessTokenWithRefreshToken($client->getRefreshToken());
$client->setAccessToken($accessToken);
}
// If there is no previous token, or it's expired.
if ($client->isAccessTokenExpired()) {
// Refresh the token if possible, else fetch a new one.
if ($client->getRefreshToken()) {
$client->fetchAccessTokenWithRefreshToken($client->getRefreshToken());
} else {
// Request authorization from the user.
$authUrl = $client->createAuthUrl();
printf("Open the following link in your browser:\n%s\n", $authUrl);
print 'Enter verification code: ';
$authCode = trim(fgets(STDIN));
// Exchange authorization code for an access token.
$accessToken = $client->fetchAccessTokenWithAuthCode($authCode);
$client->setAccessToken($accessToken);
// Check to see if there was an error.
if (array_key_exists('error', $accessToken)) {
throw new Exception(join(', ', $accessToken));
}
}
// Save the token to a file.
if (!file_exists(dirname($tokenPath))) {
mkdir(dirname($tokenPath), 0700, true);
}
file_put_contents($tokenPath, json_encode($client->getAccessToken()));
}
return $client;
}
// Get the API client and construct the service object.
try {
$client = getClient();
}
catch(Exception $e) {
unlink("token.json");
$client = getClient();
}
$service = new Drive($client);
// Print the next 10 events on the user's calendar.
try{
$optParams = array(
'pageSize' => 10,
'fields' => 'files(id,name,mimeType)',
'q' => 'mimeType = "application/vnd.google-apps.folder" and "root" in parents',
'orderBy' => 'name'
);
$results = $service->files->listFiles($optParams);
$files = $results->getFiles();
if (empty($files)) {
print "No files found.\n";
} else {
print "Files:\n";
foreach ($files as $file) {
$id = $file->id;
printf("%s - (%s) - (%s)\n", $file->getId(), $file->getName(), $file->getMimeType());
}
}
}
catch(Exception $e) {
// TODO(developer) - handle error appropriately
echo 'Message: ' .$e->getMessage();
}
I've been trying to set up the sample PHP Quickstart.
When I try running it as is I get the following error :
PHP Fatal error: Uncaught InvalidArgumentException: missing the required redirect URI in /opt/lampp/htdocs/rev_wip/vendor/google/auth/src/OAuth2.php:685
Stack trace:
#0 /opt/lampp/htdocs/rev_wip/vendor/google/apiclient/src/Client.php(406): Google\Auth\OAuth2->buildFullAuthorizationUri(Array)
#1 /opt/lampp/htdocs/rev_wip/quickstart.php(40): Google\Client->createAuthUrl()
#2 /opt/lampp/htdocs/rev_wip/quickstart.php(64): getClient()
#3 {main}
thrown in /opt/lampp/htdocs/rev_wip/vendor/google/auth/src/OAuth2.php on line 685
So I add a URI :
// $redirect_uri = 'http://localhost/rev_wip/' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'];
$redirect_uri = 'http://localhost/rev_wip/' . $_SERVER['PHP_SELF'];
$client->setRedirectUri($redirect_uri);
Now I get (when I run it on the browser) :
Authorization Error
Error 400: redirect_uri_mismatch
You can't sign in to this app because it doesn't comply with Google's OAuth 2.0 policy.
If you're the app developer, register the redirect URI in the Google Cloud Console.
Learn more
The content in this section has been provided by the app developer. This content has not been reviewed or verified by Google.
If you’re the app developer, make sure that these request details comply with Google policies.
redirect_uri: http://localhost/rev_wip/quickstart.php
I am thinking that this example is a Desktop APP and so there should be no Redirect URI. I, however get the common redirect URI error when I run it on the CLI.
How should I go about it?
Thank you all in advance.
Here is the code that I am working with:
<?php
require __DIR__ . '/vendor/autoload.php';
if (php_sapi_name() != 'cli') {
throw new Exception('This application must be run on the command line.');
}
/**
* Returns an authorized API client.
* #return Google_Client the authorized client object
*/
function getClient() {
$client = new Google_Client();
$client->setApplicationName('People API PHP Quickstart');
$client->setScopes(Google_Service_PeopleService::CONTACTS_READONLY);
$client->setAuthConfig(__DIR__ . '/credentials.json');
$client->setAccessType('offline');
$client->setPrompt('select_account consent');
// Load previously authorized token from a file, if it exists.
// The file token.json stores the user's access and refresh tokens, and is
// created automatically when the authorization flow completes for the first
// time.
$tokenPath = __DIR__ . '/token.json';
if (file_exists($tokenPath)) {
$accessToken = json_decode(file_get_contents($tokenPath) , true);
$client->setAccessToken($accessToken);
}
// If there is no previous token or it's expired.
if ($client->isAccessTokenExpired()) {
// Refresh the token if possible, else fetch a new one.
if ($client->getRefreshToken()) {
$client->fetchAccessTokenWithRefreshToken($client->getRefreshToken());
}
else {
// Request authorization from the user.
$authUrl = $client->createAuthUrl();
printf("Open the following link in your browser:\n%s\n", $authUrl);
print 'Enter verification code: ';
$authCode = trim(fgets(STDIN));
// Exchange authorization code for an access token.
$accessToken = $client->fetchAccessTokenWithAuthCode($authCode);
$client->setAccessToken($accessToken);
// Check to see if there was an error.
if (array_key_exists('error', $accessToken)) {
throw new Exception(join(', ', $accessToken));
}
}
// Save the token to a file.
if (!file_exists(dirname($tokenPath))) {
mkdir(dirname($tokenPath) , 0700, true);
}
file_put_contents($tokenPath, json_encode($client->getAccessToken()));
}
return $client;
}
// Get the API client and construct the service object.
$client = getClient();
$service = new Google_Service_PeopleService($client);
// Print the names for up to 10 connections.
$optParams = array(
'pageSize' => 10,
'personFields' => 'names,emailAddresses',
);
$results = $service
->people_connections
->listPeopleConnections('people/me', $optParams);
if (count($results->getConnections()) == 0) {
print "No connections found.\n";
}
else {
print "People:\n";
foreach ($results->getConnections() as $person) {
if (count($person->getNames()) == 0) {
print "No names found for this connection\n";
}
else {
$names = $person->getNames();
$name = $names[0];
printf("%s\n", $name->getDisplayName());
}
}
}
?>
In the tutorial you're linking to there's a section called "Troubleshooting" under which there's a section about the exact error you're facing:
https://developers.google.com/people/quickstart/php#uncaught_invalidargumentexception_missing_the_required_redirect_uri
Uncaught InvalidArgumentException: missing the required redirect URI
This error occurs when the credentials.json file used contains a client ID of the wrong type.
This code requires an OAuth client ID of type Other, which will be
created for you when using the button in Step 1. If creating your own
client ID please ensure you select the correct type.
This suggests you didn't complete step 1 properly or that you have supplied your own client ID of the wrong type.
I am trying to setup a push notification as documented in Gmail API Users: watch, but always getting 403 error i.e
Error sending test message to Cloud PubSub .... User not authorized to
perform this action
. I am using Google PHP library and follow the quickstart.php to initiate this action. Here is my script as follows:
require __DIR__ . '/vendor/autoload.php';
if (php_sapi_name() != 'cli') {
throw new Exception('This application must be run on the command line.');
}
function getClient()
{
$client = new Google_Client();
$client->setApplicationName('Gmail API PHP Quickstart');
$client->setScopes(array("https://mail.google.com/", "https://www.googleapis.com/auth/gmail.compose", "https://www.googleapis.com/auth/gmail.modify", "https://www.googleapis.com/auth/gmail.readonly", "https://www.googleapis.com/auth/cloud-platform", "https://www.googleapis.com/auth/pubsub"));
$client->setAuthConfig('credentials.json');
$client->setIncludeGrantedScopes(true);
$client->setAccessType('offline');
$client->setPrompt('select_account consent');
$tokenPath = 'token.json';
if (file_exists($tokenPath)) {
$accessToken = json_decode(file_get_contents($tokenPath), true);
$client->setAccessToken($accessToken);
}
if ($client->isAccessTokenExpired()) {
if ($client->getRefreshToken()) {
$client->fetchAccessTokenWithRefreshToken($client->getRefreshToken());
} else {
$authUrl = $client->createAuthUrl();
printf("Open the following link in your browser:\n%s\n", $authUrl);
print 'Enter verification code: ';
$authCode = trim(fgets(STDIN));
$accessToken = $client->fetchAccessTokenWithAuthCode($authCode);
$client->setAccessToken($accessToken);
if (array_key_exists('error', $accessToken)) {
throw new Exception(join(', ', $accessToken));
}
}
if (!file_exists(dirname($tokenPath))) {
mkdir(dirname($tokenPath), 0700, true);
}
file_put_contents($tokenPath, json_encode($client->getAccessToken()));
}
return $client;
}
$client = getClient();
$service = new Google_Service_Gmail($client);
$watchreq = new Google_Service_Gmail_WatchRequest();
$watchreq->setLabelIds(array('INBOX'));
$watchreq->setlabelFilterAction('include');
$watchreq->setTopicName('projects/gcl-gmail-2020/topics/php-example-topic');
$msg = $service->users->watch('me', $watchreq);
Any help in this regard will be appreciated.
You can use this sample code to test permissions for a topic, because the error message states that the service account does not have the necessary permissions to perform this action:
Testing permissions
use Google\Cloud\PubSub\PubSubClient;
/**
* Prints the permissions of a topic.
*
* #param string $projectId The Google project ID.
* #param string $topicName The Pub/Sub topic name.
*/
function test_topic_permissions($projectId, $topicName)
{
$pubsub = new PubSubClient([
'projectId' => $projectId,
]);
$topic = $pubsub->topic($topicName);
$permissions = $topic->iam()->testPermissions([
'pubsub.topics.attachSubscription',
'pubsub.topics.publish',
'pubsub.topics.update'
]);
foreach ($permissions as $permission) {
printf('Permission: %s' . PHP_EOL, $permission);
}
}
Then, just grant to the service account the necessary permissions:
Granting roles to service accounts
I have used imap for fetching gmail using php. Is there any other way to fetch gmails using php without using imap?
You can use the gmail api to access a users gmail account. You will need to authenticate the user using Oauth2 rather than using the login and password you are probably using on the imap server.
Google has a quick start which can be found here
<?php
require __DIR__ . '/vendor/autoload.php';
if (php_sapi_name() != 'cli') {
throw new Exception('This application must be run on the command line.');
}
/**
* Returns an authorized API client.
* #return Google_Client the authorized client object
*/
function getClient()
{
$client = new Google_Client();
$client->setApplicationName('Gmail API PHP Quickstart');
$client->setScopes(Google_Service_Gmail::GMAIL_READONLY);
$client->setAuthConfig('credentials.json');
$client->setAccessType('offline');
$client->setPrompt('select_account consent');
// Load previously authorized token from a file, if it exists.
// The file token.json stores the user's access and refresh tokens, and is
// created automatically when the authorization flow completes for the first
// time.
$tokenPath = 'token.json';
if (file_exists($tokenPath)) {
$accessToken = json_decode(file_get_contents($tokenPath), true);
$client->setAccessToken($accessToken);
}
// If there is no previous token or it's expired.
if ($client->isAccessTokenExpired()) {
// Refresh the token if possible, else fetch a new one.
if ($client->getRefreshToken()) {
$client->fetchAccessTokenWithRefreshToken($client->getRefreshToken());
} else {
// Request authorization from the user.
$authUrl = $client->createAuthUrl();
printf("Open the following link in your browser:\n%s\n", $authUrl);
print 'Enter verification code: ';
$authCode = trim(fgets(STDIN));
// Exchange authorization code for an access token.
$accessToken = $client->fetchAccessTokenWithAuthCode($authCode);
$client->setAccessToken($accessToken);
// Check to see if there was an error.
if (array_key_exists('error', $accessToken)) {
throw new Exception(join(', ', $accessToken));
}
}
// Save the token to a file.
if (!file_exists(dirname($tokenPath))) {
mkdir(dirname($tokenPath), 0700, true);
}
file_put_contents($tokenPath, json_encode($client->getAccessToken()));
}
return $client;
}
// Get the API client and construct the service object.
$client = getClient();
$service = new Google_Service_Gmail($client);
// Print the labels in the user's account.
$user = 'me';
$results = $service->users_labels->listUsersLabels($user);
if (count($results->getLabels()) == 0) {
print "No labels found.\n";
} else {
print "Labels:\n";
foreach ($results->getLabels() as $label) {
printf("- %s\n", $label->getName());
}
}
I am new to google client auth. I am trying to upload a file to my google drive using this php google client downloaded from here https://github.com/google/google-api-php-client
public function oauth2callback(){
set_include_path(get_include_path() . PATH_SEPARATOR . ROOT .DS. "vendors");
require_once 'Google/Client.php';
$client = new Google_Client();
$client->setClientId('xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx');
$client->setClientSecret('xxxxxxxxxxxxxxxxx');
$client->setRedirectUri('http://example.com/auth/oauth2callback');
$client->setScopes(array('https://www.googleapis.com/auth/drive'));
$client->setState('offline');
$authUrl = $client->createAuthUrl();
if (isset($_GET['code'])) {
$authCode = trim($_GET['code']);
$accessToken = $client->authenticate($authCode);
print_r($accessToken);
$client->setAccessToken($accessToken);
}
if ($client->getAccessToken()) {
// To do
}else{
$authUrl = $client->createAuthUrl();
echo "<a href='$authUrl'>Login Now</a>";
}
}
In the response, i only recieve this
{"access_token":"ya29.eQAeXvi4c5CAGRwAAAAKr55Tljr6z_GpdfjyY0xbrD15XGikNRL-D724Hx1L_g","token_type":"Bearer","expires_in":3600,"created":1410085058}
without any refresh token.
I just want to get the refresh token from the response for later use.
I also followed this question
Set the state to offline, revoked all the previous access that belonged to this app,
even tried with fresh new account/apps.. but never received refresh token..
Please guys help me out...
I was missing the access_type=offline..
So, adding
$client->setAccessType('offline');
fixed the problem.