ASANA API display all tasks in PHP script - php

I am using a simple php script which generates a task's name (it is quite long, that's why I build a generator for generating it).
Right now I need to copy generated name to ASANA, while I am creating a new task but I know that using ASANA API it can be integrated with my generator (when I click on GENERATE button the project's name is generated and a new ASANA task has been created with the generated name).
I created in my dashboard a Personal access token.
I downloaded this library https://github.com/ajimix/asana-api-php-class and filled up file examples/task-creation.php (all 3 fields with capital letters are correct filled):
<?php
require_once('../asana.php');
// See class comments and Asana API for full info
$asana = new Asana(array('personalAccessToken' => 'MY PERSONAL ACCESS TOKEN')); // Create a personal access token in Asana or use OAuth
$workspaceId = 'MY WORKSPACE ID'; // The workspace where we want to create our task, take a look at getWorkspaces() method.
// First we create the task
$asana->createTask(array(
'workspace' => $workspaceId, // Workspace ID
'name' => 'Hello World!', // Name of task
'assignee' => 'HERE MY EMAIL' // Assign task to...
));
// As Asana API documentation says, when a task is created, 201 response code is sent back so...
if ($asana->hasError()) {
echo 'Error while trying to connect to Asana, response code: ' . $asana->responseCode;
return;
}
$result = $asana->getData();
if (isset($result->id)) {
echo $result->id; // Here we have the id of the task that have been created
}
?>
After running the script from my localhost directory I get following error:
Error while trying to connect to Asana, response code: 0
Any help regarding this problem will be appreciated.

Please move your file to an online host instead of localhost. It should work.

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

Calling a google apps script execution api from PHP using a service account

I'm trying to call a very simple google apps script from php using a service account so that only my server can access it, not users of the website.
Here is how I do. I create the script here https://script.google.com
function get() {
return ContentService.createTextOutput('get method');
}
and a new project is automatically associated when i save it.
Then I open File > Project Properties to get the scriptId = MM8zQqofS1OIcnFiNSlm1CGEl5qMrMVBt
I access the developer console of the associated project threw Resources > Project Developers console by clicking on the project link at the top of the popup displayed.
Then I click 'Activate and manage API' and activate the 'Google Apps Script Execution API'. I click on 'Credentials' and see that the previous operation automatically created OAuth2 credentials. But what I need is service account credentials. Then I create one Add credentials > Service account and download generated p12 file. I get the clientId = 109160023321840004240 and clientMail = account-1#project-id-uokwrcpiqeewhwvpdhb.iam.gserviceaccount.com for this service account.
I go back to my script and share it with the service account email with read&write access File > Share. First of all i get an email in my personal mailbox which notifies me that
Delivery to the following recipient failed permanently:
account-1#project-id-uokwrcpiqeewhwvpdhb.iam.gserviceaccount.com
Then I publish the script as an execution API Publish > Publish as an execution API with access to everybody.
Now lets go on the PHP server side. Using the 'Google APIs Client Library for PHP' available here https://github.com/google/google-api-php-client I try to call my script function from PHP:
$client = new Google_Client();
$client->setClientId('109160023321840004240');
$client->setApplicationName('myScript');
$cred = new Google_Auth_AssertionCredentials(
'account-1#project-id-okwrcpiqeewhwvpdhb.iam.gserviceaccount.com',
[/*no scope nedeed for this simple script*/],
file_get_contents('path_to_myScript.p12')
);
$client->setAssertionCredentials($cred);
if ($client->getAuth()->isAccessTokenExpired()) {
$client->getAuth()->refreshTokenWithAssertion($cred);
}
$service = new Google_Service_Script($client);
$scriptId = 'MM8zQqofS1OIcnFiNSlm1CGEl5qMrMVBt';
// Create an execution request object.
$request = new Google_Service_Script_ExecutionRequest();
$request->setFunction('get');
$response = $service->scripts->run($scriptId, $request);
And here is the response I get all the time
Error calling POST https://script.googleapis.com/v1/scripts/MM8zQqofS1OIcnFiNSlm1CGEl5qMrMVBt:run: (403) The caller does not have permission
If, when I deploy the script, I choose to give access to 'Me only', i get the following response.
Error calling POST https://script.googleapis.com/v1/scripts/MM8zQqofS1OIcnFiNSlm1CGEl5qMrMVBt:run: (404) Requested entity was not found.
I would be so happy if one of you have an idea to help me :)
apps script does not yet support service accounts with execution api. see https://code.google.com/p/google-apps-script-issues/issues/detail?id=5461
google said they are looking into it but apparently wont happen soon (based on google replies on google+ posts about this like https://plus.google.com/+MartinHawksey/posts/Zquix9XqzkK)

Amazon SES Error retrieving credentials from the instance profile metadata server. (Client error: 404)

Am having some issues getting AWS SES working per below; I want to send an email to users from my website. Looks like the credentials are not being validated, however I have used the correct credentials generated from an IAM (I also tried the server root keys and it gave me the same error). I have run out of ideas of how to resolved/ debug any further so any steer would be greatly appreciated.
Error Received on Execution:
Error retrieving credentials from the instance profile metadata server. (Client error: 404)
Steps Taken
I have setup SES and validated the email addresses etc
I have created a IAM profile with 'Full access to SES'
I have installed the AWS SDK for php using the phar file
I have written the php code below providing the correct security access code directly of the SES
require 'aws/aws.phar';
use Aws\Ses\SesClient;
//More code here
$client = SesClient::factory(array(
'key' => 'xxxxxxxxxxxxx',
'secret' => 'xxxxxxxxxxx',
'region' => 'us-west-2',
'version' => '2010-12-01'
));
//code to build the $msg here as array
try{
$result = $client->sendEmail($msg);
//save the MessageId which can be used to track the request
$msg_id = $result->get('MessageId');
echo("MessageId: $msg_id");
//view sample output
print_r($result);
} catch (Exception $e) {
echo($e->getMessage());
}
//view the original message passed to the SDK
print_r($msg);
Thank you for your help in advance - this is always a great community!! Please let me know if i can provide anything else
John
You can provide credentials to your SDK using multiple methods. See the documentation: Providing Credentials to SDK
1) Set the environment variables: AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY, AWS_DEFAULT_REGION with the values from the IAM profile you created.
2) Instead of 1), you can also create ~/.aws/credentials file. Here you can add the lines: [default]
aws_access_key_id = YOUR_AWS_ACCESS_KEY_ID
aws_secret_access_key = YOUR_AWS_SECRET_ACCESS_KEY
aws_default_region = the region
1) or 2) will definitely work and it is straight forward.
3) You can also create instance profile. You need to create IAM role and instance profile. Your instance needs to have instance profile assigned when it is being created. See page 183 (as indicated on bottom of page. The topic name is "Using an IAM Role to Grant Permissions to Applications
Running on Amazon EC2 Instances") of this guide: AWS IAM User Guide to understand the steps and procedure. Here, the secret key and access key are automatically picked up and you don't have to do anything. You just need to set default region using step 1) (i.e, export AWS_DEFAULT_REGION=someregion).
4) You have already tried the 4th method and may be there is some issue in your settings which I am not aware of.

Dropbox integration in custom PHP app

I am working on a PHP app in which I need to use Dropbox web service. The requirement is that when user clicks on 'Integrate with Dropbox' link, Dropbox login popup should be shown and after successful login, it should show an other popup in which user can select Dropbox folder. Then when user uploads file from my custom PHP app, that file should get stored in selected Dropbox folder.
In all this process, user should not be redirected away from my custom PHP app.
How can I achieve this?
Do I need to create login popup for dropbox, or drop box provides one?
I believe you can find all the info about logging a user and uploading data here:
Dropbox - Using the Core API in PHP
As you can see you should create an app, get an access token (trough OAuth2 flow) and use this one to make API requests on behalf of the user. If you need to keep your user on your site you can involve Ajax to build a structure to make the calls for login, authorization, etc..
Basically these are the steps:
// Include Dropbox PHP Sdk and create a new AuthBase instance (WebAuthNoRedirect is a subclass of).
$dropboxAppAuth = new dbx\WebAuth($yourAppInfo, "examples-authorize", new dbx\ArrayEntryStore($_SESSION, 'dropbox-auth-csrf-token'););
// Get an authorize url
$authorizeUrl = $dropboxAppAuth->start();
// Invite the user to authorize your app via this url
echo "1. Go to: " . $authorizeUrl . "\n";
echo "2. Click \"Allow\" (you might have to log in first).\n";
...
// and get an access token from the GET array.
list($accessToken, $userId, $urlState) = $webAuth->finish($_GET);
// Now you need a Client instance to make you call using the API interface
$dropboxClient = new dbx\Client($accessToken, "examples-authorize");
$accountInfo = $dropboxClient->getAccountInfo();
// Get a file pointer resource from the resource you want to upload and send it using the `uploadFile()` method from the Dropbox API
$resourceFilename = 'my-data.txt';
$f = fopen($resourceFilename, "rb");
$result = $dropboxClient->uploadFile("/".$resourceFilename, dbx\WriteMode::add(), $f);
However at the end of that page you can find this basic example, complete and ready to start to play with it.
Did you research the Dropbox API?
https://www.dropbox.com/developers/dropins/saver
You can't do it using PHP alone, you need AJAX to save data to Dropbox.

Sending a message by the WhatsApp API using PHP

I am trying to send a message by the WhatsApp API using PHP. I have the WhatsApp password and am getting by WART using the following code:
<?php
require "whatsapp.class.php";
// DEMO OF USAGE
$wa = new WhatsApp("91XXXXXXXXXX", "XXX-XXX", "Nick Name");
$wa->Connect();
$t = $wa->Login();
$wa->Message("5","91XXXXXXXXXX","Good code");
echo "Message sent";
?>
I did not change anything in the whatsapp.class.php file.
My files are:
http://vvsindia.com/stackoverflow/whatsapp.class.txt
http://vvsindia.com/stackoverflow/func.txt
http://vvsindia.com/stackoverflow/decode.txt
For your convenience to view while browsing, I just uploaded them as a txt file, but originally these are PHP files.
Using the above code I was not able to send any message. What could the issue be?
You can use the below script to send a message from WhatsApp in PHP.
https://github.com/venomous0x/WhatsAPI/tree/master/examples
Configure the source code in Apache and run examples/whatsapp.php file.
You have to change the below configurations.
// Simple password to view this script
$config['webpassword'] = 'MakeUpPassword';
and
$config['YOURNAME'] = array(
'id' => 'e807f1fcf82d132f9bb018ca6738a19f',
'fromNumber' => '441234567890',
'nick' => "YOURNICKNAME",
'waPassword' => "EsdfsawS+/ffdskjsdhwebdgxbs=",
'email' => 'testemail#gmail.com',
'emailPassword' => 'gmailpassword'
);
You should rather try this quick and easy interface API:
https://www.mashape.com/motp/whatsapp-pusher
As given in the documentation, sending a text message to a WhatsApp user would be a one-step process. Below is a sample cURL call to send a text message to a WhatsApp user.
curl -XPOST 'http://api.dial2verify.com/WHAPP/SEND/<API_KEY>/<Phone_ISD>' \
-d 'Msg=Text to image URL here'
To get the API key, you are required to drop a request to hello#dial2verify.in, and they would provide you a free API key.
Phone_ISD: should be a complete phone number including ISD code (for example, 919922003300).

Categories