How to do simple google script api with php - php

I am trying to figure out how to call a google script via the api from php. Here is my script:
function doGet() {
return ContentService.createTextOutput("hello world!");
}
I can call it as a web app via it's URL but what I am trying to accomplish will require it be called via the API. Google's documentation is so confusing it's almost useless.
This seems like it would be such a simple task but I'm getting nowhere fast. Does anyone know where to find a simple step by step tutorial or can someone detail the steps required to accomplish this?
UPDATE: So, I've given up on the google API to access scripts. I can use all of the drive api calls but it seems it's not possible to call my own script via the API. Here is my ultimate goal:
A google script to zip files:
function doGet(e) {
var fileIds = [];
// hard code a couple of file id's just for simplicity now.
fileIds.push('0BzoYw0RgVVOvU0RqdTFrcGdSSzA');
fileIds.push('0BzoYw0RgVVOvNEJNcWpmSkNxNTA');
return ContentService.createTextOutput(zipping(fileIds));
}
function zipping(fileIds) {
var zipfilename = "sample2.zip";
var blobs = [];
var mimeInf = [];
var accesstoken = ScriptApp.getOAuthToken();
fileIds.forEach(function(e) {
try {
var file = DriveApp.getFileById(e);
var mime = file.getMimeType();
var name = file.getName();
} catch (er) {
return er
}
var blob;
blob = UrlFetchApp.fetch("https://www.googleapis.com/drive/v3/files/" + e + "?alt=media", {
method: "GET",
headers: {"Authorization": "Bearer " + accesstoken},
muteHttpExceptions: true
}).getBlob().setName(name);
blobs.push(blob);
});
var zip = Utilities.zip(blobs, zipfilename);
return DriveApp.createFile(zip).getId(); // return the file id of the new zip file.
}
Publish -> Deploy as web app...
Select "New"
Select "Me"
Select "Only Myself"
Click "Deploy" and authorize the access as requested.
Call the web app with curl from command line to test:
curl -L https://script.google.com/macros/u/0/s/### script id ###/exec
Get html containing the error: "Sorry, unable to open the file at this time."
Change permissions so anyone can execute the app.
Same error. Even entering the url in the browser as the same user gives the same error.
At this point I think I have to admit defeat and find a solution other than Google.
------------------ UPDATE 2 --------------------
Apparently the error:
"Sorry, unable to open the file at this time. Please check the address and try again."
I think this is some oddball problem with Google. The same script works in some accounts but not others. I see from searching the web, others randomly get this error and there is no definitive solution. If anyone knows one, please let me know.
----------------- UPDATE 3 --------------------
This error is an oddball problem with Google. Apparently a new script in some accounts will get this error until the next day. I have verified this several times so if this happens to you, wait a day and try executing it again. The good thing is that after Google finally is able to "open the file" you can make any changes you want, including additional script files to that project, and it updates instantly.
However, a new project will have to wait until the next day so pre create any you think you might want and a couple extra a day ahead of time.

How about this sample script? When you deploy Web Apps, please copy and paste the URL. And please use it to $url of the following script.
How to deploy Web Apps.
On the Script Editor
File
-> Manage Versions
-> Save New Version
Publish
-> Deploy as Web App
-> "Project version:" is latest one or create as New.
-> At "Execute the app as", select "your account"
-> At "Who has access to the app", select "Anyone, even anonymous"
-> Click "Deploy"
-> Copy "Current web app URL"
-> Click "OK"
Sample script :
<?php
$url = 'https://script.google.com/macros/s/#####/exec';
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, 'GET');
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl,CURLOPT_FOLLOWLOCATION, true);
$response = curl_exec($curl);
echo $response;
curl_close($curl);
?>
Result :
hello world!
References :
Web Apps
cURL Functions
If I misunderstand your question, I'm sorry.

Related

Google Sheets API with php - Find a cell value

I am using the Google Sheets API with PHP and reading a sheet, I need to find a row and update its content.
I am currently iterating over the rows, looking for the value, but as the sheet grows, this seems rather inefficient. Is there a way to search for a cell, to retrieve the row, so I can then update?
My code to iterate is as follows.
$spreadsheet = (new Google\Spreadsheet\SpreadsheetService)
->getSpreadsheetFeed()
->getById("xxx sheet id xxx");
$worksheets = $spreadsheet->getWorksheetFeed()->getEntries();
$worksheet = $worksheets[0];
$CellFeed = $worksheet->getCellFeed();
foreach ($CellFeed->getEntries() as $E)
{
$r = $E->getRow();
/* ...... */
}
I believe your goal as follows.
You want to search a value from the specific column in the Spreadsheet and want to retrieve the row numbers of searched rows.
You want to achieve this using PHP.
Issue and workaround:
In that case, unfortunately, when Sheets API is used, in the current stage, it is required to do the following flow.
Retrieve all values from the sheet you want to search.
Retrieve the row and column numbers from the retrieved values.
This might be the same with your current script. Because in the current stage, there are no methods for directly searching the values in Sheets API. So in this answer, as a workaround, I would like to propose to use Web Apps created by Google Apps Script. When Google Apps Script is used, the searched row numbers can be retrieved by the TextFinder which is the built-in method. And the process cost of TextFinder is low. So I proposed it.
Usage:
Please do the following flow.
1. Create new project of Google Apps Script.
Sample script of Web Apps is a Google Apps Script. So please create a project of Google Apps Script.
If you want to directly create it, please access to https://script.new/. In this case, if you are not logged in Google, the log in screen is opened. So please log in to Google. By this, the script editor of Google Apps Script is opened.
It is required to put this Google Apps Script project to the same Google Drive of the Spreadsheet you want to use.
2. Prepare script.
Please copy and paste the following script (Google Apps Script) to the script editor. This script is for the Web Apps.
function doGet(e) {
const sheet = SpreadsheetApp.openById(e.parameter.spreadsheetId).getSheetByName(e.parameter.sheetName);
const res = sheet.getRange(1, 2, sheet.getLastRow()).createTextFinder(e.parameter.searchValue).findAll().map(r => r.getRow());
return ContentService.createTextOutput(JSON.stringify({rowNumbers: res})).setMimeType(ContentService.MimeType.JSON);
}
3. Deploy Web Apps.
On the script editor, Open a dialog box by "Publish" -> "Deploy as web app".
Select "Me" for "Execute the app as:".
By this, the script is run as the owner.
Select "Anyone, even anonymous" for "Who has access to the app:".
In this case, no access token is required to be request. I think that I recommend this setting for testing this workaround.
Of course, you can also use the access token. When you use the access token, please include one of scopes for Drive API like https://www.googleapis.com/auth/drive.readonly.
And also, I think that a key value can be used as the query parameter instead of the access token.
Click "Deploy" button as new "Project version".
Automatically open a dialog box of "Authorization required".
Click "Review Permissions".
Select own account.
Click "Advanced" at "This app isn't verified".
Click "Go to ### project name ###(unsafe)"
Click "Allow" button.
Click "OK".
Copy the URL of Web Apps. It's like https://script.google.com/macros/s/###/exec.
When you modified the Google Apps Script, please redeploy as new version. By this, the modified script is reflected to Web Apps. Please be careful this.
4. Testing Web Apps using PHP script.
Please set the URL of your Web Apps to the following script. And, please set the spreadsheet ID, sheet name. From your replying, in this sample, the search value and column number are Pj/5678 and 2, respectively. 2 of searchColumn means the column "B".
<?php
$url = 'https://script.google.com/macros/s/###/exec'; // Please set the URL of Web Apps.
$q = array(
'spreadsheetId' => '###', // Please set the Spreadsheet ID.
'sheetName' => 'Sheet1',
'searchValue' => 'Pj/5678',
'searchColumn' => 2
);
$curl = curl_init();
$option = [
CURLOPT_URL => $url . '?' . http_build_query($q),
CURLOPT_CUSTOMREQUEST => 'GET',
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_RETURNTRANSFER => true
];
curl_setopt_array($curl, $option);
$res = curl_exec($curl);
$obj = json_decode($res);
print_r($obj);
curl_close($curl);
?>
Result:
When above script is run, the following value is returned. The row numbers of searched rows are returned.
{"rowNumbers":[###, ###,,,]}
Note:
When you modified the script of Web Apps, please redeploy the Web Apps as new version. By this, the latest script is reflected to Web Apps. Please be careful this.
References:
Web Apps
Taking advantage of Web Apps with Google Apps Script
Class TextFinder

Facebook Chat Bot - How do I test the welcome message?

My chat bot is working great but I am having trouble debugging the Welcome message functionality because it only shows up when a conversation is initiated (although i'm pretty sure it's not working having tried it on a colleagues phone). How do I reset my chat so it sees me as a new user interacting with it?
This is my welcome PHP Script at the moment
<?php
function webhook() {
$challenge = $_REQUEST['hub_challenge'];
$verify_token = $_REQUEST['hub_verify_token'];
if ($verify_token === 'MYTOKEN') {
echo $challenge;
}
$input = json_decode(file_get_contents('php://input'), true);
$sender = $input['entry'][0]['messaging'][0]['sender']['id'];
$welcomejson = welcomemessage();
welcomesend($json);
function message() {
$json = '{
"setting_type":"call_to_actions",
"thread_state":"new_thread",
"call_to_actions":[
{
"message":{
"text":"Welcome to My BOT!"
}
}
]
}';
return $json;
}
function send($json) {
$url = 'https://graph.facebook.com/v2.6/MYPAGEID/thread_settings?access_token=MYTOKEN';
//Initiate cURL.
$ch = curl_init($url);
//Tell cURL that we want to send a POST request.
curl_setopt($ch, CURLOPT_POST, 1);
//Attach our encoded JSON string to the POST fields.
curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonData);
//Set the content type to application/json
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
//Execute the request
$result = curl_exec($ch);
}
Try this:
Open Facebook in a desktop browser and go to the page linked to your messenger bot
Press "Message"
Inside the message popup/discussion choose "Options" (cog icon)
Select "Delete Conversation..." and say "Delete Conversation" in the confirmation prompt
Select "Message" again
Select "Get Started"
Step 4. really deletes the chat history you are having with the page/app so beware.
On desktop, delete the conversation and message the page again.
This will allow you to see the "Get Started" button again, allowing you to test it and your welcome message's functionality.
If you're trying to test the "Messenger Greeting", it's a lot more complicated. See below.
On Desktop the "Messenger Greeting" still will not show up after deleting the conversation. Only the "get started" button reappears. I believe this is a bug that I will be opening up a ticket for most likely.
You can get a similar experience on mobile by deleting the conversation, uninstalling, and reinstalling Messenger, but once again that does not display the Messenger greeting, it only shows the get started button.
Not being able to see the Messenger Greeting again is an issue for developers who are picky about the line-by-line formatting of the Messenger greeting, or who simply need to see it again for a demo of the messenger bot once the greeting has already been seen.
Thankfully, although EXTREMELY painful, there's a workaround. Basically have to re-setup your bot.
Create a new page
NEVER OPEN A MESSAGE WITH THE PAGE/BOT UNTIL STEP 17
Click settings, Messenger, and set your messenger greeting, and press save.
Since that doesn't actually save the toggled setting for some reason, select a different thing from messenger in the sidebar
Reselect Messenger
Turn on the greeting (the message should have saved properly, just not the toggle for whether its on or off)
Change to a different thing in sidebar
Re-select Messenger and double check that the messenger greeting is enabled
Create a new app
Add Messenger as a product
Select the page and copy the page access token
Put the page access token where it is needed in your code
Run your code
Connect to the webhook url with your verify token and all the boxes checked
After webhook connection is successful, subscribe it to your new page
Run your curl command to enable the 'get started' button and your welcome message that will happen after the button is pressed
Open a message with your page, and the Messenger greeting and get started button should appear. YOU GET ONE CHANCE AND THEN YOU'LL HAVE TO REPEAT ALL OF THESE STEPS TO SEE THE GREETING AGAIN.
I believe the toggle on messenger greeting not saving right is also a bug, and I may open a ticket for it.
There is a way to get the welcome screen in Messenger on iOS (at least as of Apr 28th), although it's super annoying. Basically, in addition to deleting the convo, you have to reinstall the app on your phone.
Go to the paged linked to your bot in facebook on desktop
Archive the conversation
Open Messenger on your phone and delete the conversion by swiping right on the cell in the conversation list
Delete Messenger from your phone
Reinstall Messenger from the App Store

Podio item.update webhook to open a new link

I have setup a webhook in Podio for an item.update in hook_update_item.php file. What I want to do if an item has been updated, I want to open a link preferably in a new tab, here is the code that I have:
<?php
require ("../podio/PodioAPI.php");
Podio::setup(Client ID, Client Secret);
Podio::authenticate_with_app(App ID, App Token);
switch ($_POST['type']) {
case 'hook.verify':
// Validate the webhook
PodioHook::validate($_POST['hook_id'], array('code' => $_POST['code']));
case 'item.update':
// Do something. item_id is available in $_POST['item_id']
if ($_POST['item_id'] == '238777597'){
//open new link here
$ch = curl_init('http://www.google.com.ph');
curl_exec($ch);
}
}
?>
Podio webhook has already been validated so I am assuming when webhook is firing it goes to the 'item.update'. But so far no luck on bringing up a new tab of google page. Appreciate any tips and suggestions!
I'm assuming that your code is running on a server somewhere. You could write a webpage that asks the server every n seconds/minutes if there are any new tabs that it should open. Your server receives the request, looks to see if there are any tabs to open and sends them in an array to the webpage. From there in javascript you can open the new tabs. Your browser might block them thought if you don't change the pop-up settings.
There might be a better way to do this using push notifications, but it is a start.

PHP youtube api error

How to upload videos using youtube api from localhost web application in codeigniter or php?
I followed the steps in youtube library as follows:
api key : 'my developer key'
consumer key : 'anonymous'
consumer secret : 'anonymous'
I am using the functions as follows and my site url is : http://localhost/ci-youtube/example/request_youtube
//CALL THIS METHOD FIRST BY GOING TO
//www.your_url.com/index.php/request_youtube
public function request_youtube()
{
$params['key'] = 'anonymous';
$params['secret'] = 'anonymous';
$params['algorithm'] = 'HMAC-SHA1';
$this->load->library('google_oauth', $params);
$data = $this->google_oauth->get_request_token(site_url('example/access_youtube'));
print_r($data);
$this->session->set_userdata('token_secret', $data['token_secret']);
redirect($data['redirect']);
//$this->load->view('welcome_message');
}
//This method will be redirected to automatically
//once the user approves access of your application
public function access_youtube()
{
$params['key'] = 'anonymous';
$params['secret'] = 'anonymous';
$params['algorithm'] = 'HMAC-SHA1';
$this->load->library('google_oauth', $params);
$oauth = $this->google_oauth->get_access_token(false, $this->session->userdata('token_secret'));
$this->session->set_userdata('oauth_token', $oauth['oauth_token']);
$this->session->set_userdata('oauth_token_secret', $oauth['oauth_token_secret']);
}
But it shows the error : 'Invalid Token'
Any idea ?
Thanks in advance for quick reply.
I think you still haven't got an API key from YouTube yet. Is that so?
I haven't published this yet but I'm about to release a PHP based Youtube autouploader, that allows you to run uploads from a NAS box, spare PC etc.
https://github.com/Danack/Youtube-Autouploader
It has a complete example for how to upload videos to Youtube in there, in particular the function "uploadVideo($filename, $videoInfo)"
https://github.com/Danack/Youtube-Autouploader/blob/master/youtubeCurl.php
First make sure you are using the correct consumer key and consumer secret.
Second if you run into problems with either the Google_oauth library or the Youtube library make sure you set the DEBUG constant in those libraries to true. Doing that will dump a lot more logging information in to the PHP error log which should help you diagnose the problem.
Timestamp is too far from current time:
It seems like your server time is not correctly set. Please correct your server time, you may want to restart your web server after fixing the time. - Change Server time. Try restart Webserver first. If not work, restart your Computer ==> it work!.

Automatic Soundcloud PHP Api authentication without user interaction

In my application i want to use the Soundcloud API with my own Soundcloud user. The Soundcloud API authentication process involves a user being redirected to the Soundcloud homepage, login and authorize the application, so that the page can use the API for this user.
I want to automate the whole process, because my own user is the only user which gets authenticated. Is that possible?
Here is my code so far:
$soundcloud = new \Services_Soundcloud(
'**',
'**',
'http://**'
);
$authorizeUrl = $soundcloud->getAuthorizeUrl();
$accessToken = $soundcloud->accessToken();
try {
$me = json_decode($soundcloud->get('me'), true);
} catch (Services_Soundcloud_Invalid_Http_Response_Code_Exception $e) {
exit($e->getMessage());
}
But the line $accessToken = $soundcloud->accessToken(); throws an exception:
The requested URL responded with HTTP code 401.
500 Internal Server Error - Services_Soundcloud_Invalid_Http_Response_Code_Exception
Hi All,
Here I am going to share my experience with Soundcloud API (PHP)
See my Question: Link
Recently I started to work with Sound cloud API (PHP) and I decided to use PHP API by
https://github.com/mptre/php-soundcloud.
But When I was trying to get access token from Sound cloud server by this code:
// Get access token
try {
$accessToken = $soundcloud->accessToken($_GET['code']);
} catch (Services_Soundcloud_Invalid_Http_Response_Code_Exception $e) {
exit($e->getMessage());
}
I had check the $_GET['code'] value. But strange there is nothing in
$_GET['code'] this is blank. The Soundcloud was returning "The
requested URL responded with HTTP code 0" error. That time I was
testing Soundcloud on WAMP Localhost.
Allot of Goggling I found a solution to fix "The requested URL
responded with HTTP code 0" issue. I had download 'cacert.pem' file
and put inside our demo project folder (inside Services/Soundcloud/).
Then after I added some code in 'class Services_Soundcloud'
function protected function _request($url, $curlOptions = array()).
// My code in side function
$curlPath = realpath(getcwd().'\Services\cacert.pem');
$curlSSLSertificate = str_replace("\\", DIRECTORY_SEPARATOR, $curlPath);
curl_setopt($ch, CURLOPT_CAINFO, $curlSSLSertificate);
Saved 'class Services_Soundcloud' file and moved on live server. After
move my project from WAMP to Live server I start to check it again.
When I open my index.php it's ask me to login
I use my Facebook account to login.
after login it was asking to connect with Soundcloud
after connect everything working smooth, I got my info with
$me = json_decode($soundcloud->get('me'));
but a new problem start to occurring which was that my access token
being expire again and again. Then I use session :D
// code for access token
$code = $_GET['code'];
// Get access token
try {
if(!isset($_SESSION['token'])){
$accessToken = $soundcloud->accessToken($code);
$_SESSION['token'] = $accessToken['access_token'];
}else{
$soundcloud->setAccessToken($_SESSION['token']);
}
} catch (Services_Soundcloud_Invalid_Http_Response_Code_Exception $e) {
exit($e->getMessage());
}
And now everything working awesome. i can get all my details, tracks everything from SC server
Hope it will help you to fight with Soundcloud API Cheers!!!! :)
I'm looking for the same thing, but according to the soundcloud's api (check the Authenticating without the SoundCloud Connect Screen paragraph):
// this example is not supported by the PHP SDK
..and is not supported by the Javascript neither.
I've tryed to auth with python:
# create client object with app and user credentials
client = soundcloud.Client(client_id='YOUR_CLIENT_ID',
client_secret='YOUR_CLIENT_SECRET',
username='YOUR_USERNAME',
password='YOUR_PASSWORD')
..then the uploading python method:
# upload audio file
track = client.post('/tracks', track={
'title': 'This is my sound',
'asset_data': open('file.mp3', 'rb')
})
and it works just fine.
So, for now, you have 2 ways:
Use another language, Python or Ruby (the only 2 sdk that actually support this feature) or use a small python/ruby script as a bridge for this particular need;
Add this funcionaliy to the PHP SDK (i'm trying to do it quick'n'dirty, if i get success, i'll share ;)
There is no magic behind its implementation in Python and Ruby SDK's.
What's happening is that POST request is sent to http://api.soundcloud.com/oauth2/token with the following params:
client_id='YOUR_CLIENT_ID'
client_secret='YOUR_CLIENT_SECRET'
username='YOUR_USERNAME'
password='YOUR_PASSWORD'
And Content-Type: application/x-www-form-urlencoded
The response body contains access_token, that can be used for the further authorization of your requests. Thus, your GET request to /me endpoint will look like: /me?oauth_token=YOUR_ACCESS_TOKEN&client_id=YOUR_CLIENT_ID. (I believe, client_id is redundant here but all their apps keep adding it).
Here is the Postman Doc I created for demonstration: https://documenter.getpostman.com/view/3651572/soundcloud/7TT5oD9

Categories