I am trying to create a google sheet with public access enabled using PHP. At this moment, I am generating the google sheet for the newly inserted code. User can download the google sheet.
But now I want to give a default permission public to dynamically created google sheet via code. Is it possible in google sheet?
Here is a code
// Creating new spreadsheet
$spreadsheet = new Google_Service_Sheets_Spreadsheet([
'properties' => [
'title' => "$sheet_name"
]
]);
$spreadsheet = $service->spreadsheets->create($spreadsheet, [
'fields' => 'spreadsheetId'
]);
$sheet_id = $spreadsheet->spreadsheetId;
//End Creating new spreadsheet
For creating permissions programmatically you need the method Permissions: create
Once you have the sheet_id, create a permission with permissions->insert()
Specify the role as desired (e.g. reader, writer,...)
For pulib availability of the file - specify the type as anyone
Sample how to implement it in php:
$newPermission= new Google_Service_Drive_Permission();
$newPermission->setType('anyone');
$newPermission->setRole('reader');
$service->permissions->insert($sheet_id,$newPermission);
If your intention is to use an API key to make changes to a sheet. The answer is you cant.
You need to have authenticated access either though Oauth2 or a service account. using one of the below scopes to make any changes with an API.
https://www.googleapis.com/auth/drive
https://www.googleapis.com/auth/drive.file
https://www.googleapis.com/auth/spreadsheets
Public sheet just means anyone can download and see it and probably make changes via the Sheets web applicaition. Changing it with the API requires access.
You can create a sheet then use the google drive api to update the permissions on the sheet to make it public but again thats not going to enable you to write to it.
Here is the code to set/change permissions of the file. This code can update the permissions of the google spreadsheet too.
I have spent a lot of time. So, anyone who is finding it hard to get any solution to make the google spreadsheet public/any_permission, you can refer to this code.
You can further refer to Google Drive API v3 permissions.
$service = new Google_Service_Drive($client);
$permission = new Google_Service_Drive_Permission();
$permission->setRole( 'reader' );
$permission->setType( 'anyone' );
$service->permissions->create( $spreadsheetId, $permission );
Related
I'm working on an application that sends SMS to the customers we got.
I'm currently looking the doc (https://docs.ovh.com/fr/sms/envoyer_des_sms_avec_lapi_ovh_en_php/) => it's in french.
They're using a PHP Wrapper, but I really don't know how I can integrate the API to my Laravel Project.
Does someone know how it's working ?
First of all, install the package
composer require ovh/php-ovh-sms
Then, on the controller, you can use the API easily as stated in the documentation.
use \Ovh\Sms\SmsApi;
// Informations about your application
// You may set them to 'NULL' if you are using
// a configuraton file
$applicationKey = "your_app_key";
$applicationSecret = "your_app_secret";
$consumerKey = "your_consumer_key";
$endpoint = 'ovh-eu';
// Init SmsApi object
$Sms = new SmsApi( $applicationKey, $applicationSecret, $endpoint, $consumerKey );
// Get available SMS accounts
$accounts = $Sms->getAccounts();
dd($accounts);
There is a Laravel notification channel specifically for this provider, this will make the whole process much easier, it will allow you to use Laravel's built in notifications functionality without having to write provider specific code.
http://laravel-notification-channels.com/ovh-sms/
I put my php code in GCE and wanna to modify google sheets.
Google told me that i don't have to apply a extra credential by using GCP>API because there's a strategy called Application Default Credentials (ADC) will find application's credentials.
I first check the environment variable "GOOGLE_APPLICATION_CREDENTIALS" in GCE server but it's empty.
Then i follow this tutorial https://cloud.google.com/docs/authentication/production?hl=zh_TW#auth-cloud-implicit-php and install this:
composer require google/cloud-storage
I tried the code under and got some error.
namespace Google\Cloud\Samples\Auth;
// Imports GCECredentials and the Cloud Storage client library.
use Google\Auth\Credentials\GCECredentials;
use Google\Cloud\Storage\StorageClient;
function auth_cloud_explicit_compute_engine($projectId)
{
$gceCredentials = new GCECredentials();
$config = [
'projectId' => $projectId,
'credentialsFetcher' => $gceCredentials,
];
$storage = new StorageClient($config);
# Make an authenticated API request (listing storage buckets)
foreach ($storage->buckets() as $bucket) {
printf('Bucket: %s' . PHP_EOL, $bucket->name());
}
}
PHP Fatal error: Uncaught Error: Class 'GCECredentials' not found in /var/www/html/google_sheets/t2.php:5
More question:
Will this code create a json file as credential for me to access google sheets?
$gceCredentials = new GCECredentials();
Or where can i find the service account key??
Please tell me what should i do, thanks a lot.
I want to write a server php script which will access my google drive and copy a file there.
The server has to save credentials for my google drive and not ask for authorisation.
All the examples I saw describe web applications there various users can perform actions on their drives. For example here https://developers.google.com/drive/v3/web/quickstart/php
How can I save all the needed credentials on my server.
After a long research and reading google documentation and examples I found a way that works for me.
You need a service account. This account will access the google drive data.
I work with google domain, therefore I needed to grant domain wide authority to this service account.
Here you can find how to create a service account and grant it domain wide authority however this link does not has PHP examples
Here you can find the same instructions with PHP examples
Please pay attention that you need JSON type key file when you create a service account.
I used Google Application Default Credentials.
Finally this is working code snippet:
<?php
require_once '/path/to/google-api-php-client/vendor/autoload.php';
putenv('GOOGLE_APPLICATION_CREDENTIALS=/path/to/service-account.json');
$client = new Google_Client();
$client->useApplicationDefaultCredentials();
$client->setScopes(['https://www.googleapis.com/auth/drive']);
$client->setSubject('email_of_account#you_want_to_work.for');
$service = new Google_Service_Drive($client);
//Create a new folder
$fileMetadata = new Google_Service_Drive_DriveFile(
array('name' => 'Invoices',
'mimeType' => 'application/vnd.google-apps.folder'));
$file = $service->files->create($fileMetadata, array('fields' => 'id'));
echo $file->id;
?>
I recommend you look into using a service account. A service account is like a dummy user which is pre authenticated. This means that you can share a folder on your google drive account with the service account and the service account will be able to upload to it. I have an article on how Service accounts work. Google Developers console Service account
There are a few things you need to remember when working with service accounts though. Mainly permissions when the service account uploads a file by default it owns the file so you will need to grant your personal account permissions to the file after it is uploaded. Its just an extra step.
The PHP client library has a sample for using service account authentication but it doesn't have drive you will have to alter the books part to be google drive. Service-account.php
require_once __DIR__ . '/vendor/autoload.php';
// Use the developers console and download your service account
// credentials in JSON format. Place the file in this directory or
// change the key file location if necessary.
putenv('GOOGLE_APPLICATION_CREDENTIALS='.__DIR__.'/service-account.json');
/**
* Gets the Google client refreshing auth if needed.
* Documentation: https://developers.google.com/identity/protocols/OAuth2ServiceAccount
* Initializes a client object.
* #return A google client object.
*/
function getGoogleClient() {
return getServiceAccountClient();
}
/**
* Builds the Google client object.
* Documentation: https://developers.google.com/api-client-library/php/auth/service-accounts
* Scopes will need to be changed depending upon the API's being accessed.
* array(Google_Service_Analytics::ANALYTICS_READONLY, Google_Service_Analytics::ANALYTICS)
* List of Google Scopes: https://developers.google.com/identity/protocols/googlescopes
* #return A google client object.
*/
function getServiceAccountClient() {
try {
// Create and configure a new client object.
$client = new Google_Client();
$client->useApplicationDefaultCredentials();
$client->addScope([YOUR SCOPES HERE]);
return $client;
} catch (Exception $e) {
print "An error occurred: " . $e->getMessage();
}
}
This may also help my google drive samples
I need to get some automated ad insights using the Marketing Api. For this purpose I have created a System User via the Business Manager, and generated a System User access token with the ads_read permission.
Using this token then to make api calls and get a specific Campaign's Insights, with the FacebookAds php v2.6 sdk, I get the following error:
Uncaught exception 'FacebookAds\Http\Exception\PermissionException'
with message '(#275) Cannot determine the target object for this
request. Currently supported objects include ad account, business
account and associated objects.'
Does my app need to be whitelisted or am I missing something else? I noticed that next to the 'ads_read' permission there was this note that stated '(your App must be whitelisted)'.
Here is the sample code I'm using
<?php
define('VENDOR_DIR', 'vendor/'); // Path to the Vendor directory
$loader = require VENDOR_DIR.'autoload.php';
use FacebookAds\Api;
use FacebookAds\Object\Campaign;
// Initialize a new Session and instantiate an Api object
Api::init(
'xxxxxxxxxxxxxxxx', // App ID
'xxxxxxxxxxxxxxxxx',
'xxxxxxxxxxxxxxxxxx' // System User Access Token
);
$api = Api::instance();
use FacebookAds\Object\Values\InsightsLevels;
$campaign = new Campaign('xxxxxxxxxxxxx');
$params = array(
'level' => InsightsLevels::CAMPAIGN,
);
$async_job = $campaign->getInsightsAsync(array(), $params);
$async_job->read();
while (!$async_job->isComplete()) {
sleep(1);
$async_job->read();
}
$async_job->getResult();
?>
It seems like your app doesn't have ads_read permission. Here you can find more information on how to ask for it: https://developers.facebook.com/docs/marketing-api/access
I have read the examples here:
http://framework.zend.com/manual/en/zend.gdata.spreadsheets.html
But those examples assume the spreadsheet to be read needs authentication:
$service = Zend_Gdata_Spreadsheets::AUTH_SERVICE_NAME;
$client = Zend_Gdata_ClientLogin::getHttpClient($user, $pass, $service);
$spreadsheetService = new Zend_Gdata_Spreadsheets($client);
$feed = $spreadsheetService->getSpreadsheetFeed();
The spreadsheet I am going to read from is a public one, so I don't really need to provide any authentication right? And what I need to provide is just the url of the spreadsheet.
I tried to read the class description here but still have no idea how it can be done:
http://framework.zend.com/apidoc/core/Zend_Gdata/Spreadsheets/Zend_Gdata_Spreadsheets.html
You CAN see a google public spreadsheet without being logged on. What does authentication mean if not logging on with name and password? You don't need authentication for public documents. So the question above remains.
As far as I'm concerned, access to any Google spreadsheet requires a Google account, even if the document is public (did you try to access it in the browser without being logged in to your Google account?). So yes, you need to provide Zend_Gdata with authentication credentials.