Update Cell SmartSheet 2.0 with PHP Script - php

I have found this piece of code to update cell in SmartSheet website. But I I don't understand what are the values in the fields variable. Is anyone has the working example of PHP code to do this?
curl https://api.smartsheet.com/2.0/sheets/{sheetId}/rows?include=objectValue \
-H "Authorization: Bearer ACCESS_TOKEN" \
-H "Content-Type: application/json" \
-X PUT \
-d '[{"id": "6572427401553796", "cells": [{"columnId": 7518312134403972,"objectValue": {"objectType": "PREDECESSOR_LIST","predecessors": [{"rowId": 567735454328708,"type": "FS","lag": {"objectType": "DURATION","days": 2,"hours": 4}}]}}]}]'
My current php code is as follow and I just want to update some value into the sheet.I don't know what to put in the field varaible. Thanks.
<?php
$baseURL = "https://api.smartsheet.com/2.0";
$getSheetURL = $baseURL. "/sheets/4925037959505xxx/rows?include=objectValue";
$accessToken = "34ouqtkxp0sutdv6tjbwtsxxxx";
$headers = array("Authorization: Bearer ". $accessToken , "Content-Type: application/json");
$fields='[????]';
$ch = curl_init($getSheetURL);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_POSTFIELDS, $fields);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PUT");
$result = curl_exec($ch);
print_r($result);
?>
Thanks

This is a function I created to update a SmartSheet
$ssID: is the Smart Sheet ID
$ssRowID: is the Smart Sheet row id I
want to update
$values: is an array of column values
$columArray: is
an array of the column IDs
$config: is an array I use to hold all
auth information
Breaking down the Json Data which is the way you communicate which columns you want to update and the values
{"id": "'.$ssRowID.'",
"cells":
[
{"columnId": '.$columnArray['go'].',"value": "'.$values['go'].'"},
{"columnId": '.$columnArray['comments'].',"value": "'.$values['comment'].'"},
{"columnId": '.$columnArray['data center'].',"value": "'.$values['datacenter'].'"}
]
}
ID represents the row you want to update
ColumnID represents each column you want to update must provide the column ID and value represents the value you want to insert
{"columnId": 'your column id here',"value": 'your value here'}
function ssUpdate($ssID, $ssRowID, $values, $columnArray, $config){
/*
* update the Smart Sheet using the passed in sheet ID, Row ID and VALUES
*
*/
$sheetID = $ssID;
$SSAPIToken = $config['smartsheets']['SSAPIToken'];
$sheetsURL = "https://api.smartsheet.com/2.0/sheets/".$sheetID."/rows";
$data_json = '[{"id": "'.$ssRowID.'", "cells": [{"columnId": '.$columnArray['go'].',"value": "'.$values['go'].'"}, {"columnId": '.$columnArray['comments'].',"value": "'.$values['comment'].'"}, {"columnId": '.$columnArray['data center'].',"value": "'.$values['datacenter'].'"}]}]';
//echo $data_json."<br />";
// Create Headers Array for Curl
$headers = array(
"Authorization: Bearer " .$SSAPIToken,
'Content-Type: application/json',
'Content-Length: ' . strlen($data_json)
);
/*
* connect to SS and update Sheet
*/
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$sheetsURL );
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT ,0);
curl_setopt($ch, CURLOPT_TIMEOUT, 400); //timeout in seconds
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_VERBOSE, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLINFO_HEADER_OUT, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'PUT');
curl_setopt($ch, CURLOPT_POSTFIELDS,$data_json);
$data = curl_exec($ch);
$status_code = curl_getinfo($ch, CURLINFO_HTTP_CODE); //get status code
$curl_errno = curl_errno($ch);
$curl_error = curl_error($ch);
$information = curl_getinfo($ch);
curl_close($ch);
$ssArray = json_decode ($data, true); // make an XML object
/*
* did connection work
*/
if ($status_code != 200) {
echo "Oh No! Update Error: (". $ssArray['errorCode'] .") ". $ssArray['message'] ."\n";
} else {
//var_dump($ssArray);
if ($ssArray['resultCode'] == 0){
echo "Updated: ".$values['store'];
}else{
echo "Oh No! Update Error: (". $ssArray['errorCode'] .") ". $ssArray['message'] ."\n";
}
}
}
More details: http://smartsheet-platform.github.io/api-docs/#add-row-s

$fields is the JSON payload for the PUT request. Details are documented here: http://smartsheet-platform.github.io/api-docs/#update-row-s
I suggest you test using Postman or the Advanced Rest Client before you begin coding.
Also, include=objectValue only makes sense for a GET so there is no point including it for a PUT request.

Related

slack: Delete all messages with php

I'm trying to delete all message of a slack channel
i tried to add the required scopes to the app but this two scopes aren't available
chat:write:user
chat:write:bot
i tried with the bot and the user token after reinstall the workspace
the function getAllMessagesFromChannel() i wrote works and i get all the timestamps correctly
public function clearChannel()
{
$jsonData = $this->getAllMessagesFromChannel();
foreach ($jsonData->messages as $message) {
$this->deleteMessage($message->ts);
}
}
private function deleteMessage($ts)
{
$data = json_encode(array("channel" => $this->channel, "ts" => $ts));
$ch = curl_init("https://slack.com/api/chat.delete");
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json; charset=utf-8', "Authorization: Bearer " . $this->token));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($ch);
echo $result . "\n";
curl_close($ch);
}
i get this error for every message:
{"ok":false,"error":"cant_delete_message"}
enter image description here
any idea how to fix this?

How To get a Custom field Value of a client using FollowUpBoss Api

I am trying to get the value of a custom date field from followupboss trough the APi,
Here is my code which is get all custom fields informations, but I want to specify the response to a specific client (By ID, Name or Email)
<?php
const FUB_API_KEY = '?????????????????????????????';
$headers = array(
'Authorization: Basic '. base64_encode(FUB_API_KEY . ":"),
"Content-Type: application/x-www-form-urlencoded; charset=utf-8",
"X-System: ??????????",
"X-System-Key: ?????????????????????????",
);
//$data = array(
//"person" => array(
// "" => "" ,
//),
//);
$ch = curl_init('https://api.followupboss.com/v1/customFields');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
// curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
$response = curl_exec($ch);
if ($response === false) {
exit('cURL error: ' . curl_error($ch) . "\n");
}
$code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
if ($response) { echo json_encode(json_decode($response));}
?>
To return lead information including their custom field values i used the following:
https://api.followupboss.com/v1/people/ID?fields=allFields
(ID) is replaced by user profile ID (e.g. 70114)

Php cURL with calling an API with GRAPHQL

I am trying to call an api called Wave I have used cURL before but never with GRAPHQL queries. I am wondering what is wrong with the below when using cURL. I get an error Bad Request Below is an exmple of my code.
This is what the API cURL is
curl -X POST "https://reef.waveapps.com/graphql/public" \
-H "Authorization: Bearer <ACCESS_TOKEN>" \
-H "Content-Type: application/json" \
-d '{ "query": "query { user { id defaultEmail } }" }'
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://reef.waveapps.com/graphql/public');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 0);
curl_setopt($ch, CURLOPT_POSTFIELDS, '{ "query": "query { user { id defaultEmail } }');
curl_setopt($ch, CURLOPT_POST, 1);
$headers = array();
$headers[] = 'Content-Type: application/json';
$headers[] = 'Authorization: Bearer 1212121';
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$result = curl_exec($ch);
var_dump($result);
if (curl_errno($ch)) {
echo 'Error:' . curl_error($ch);
}
Any help would be helpful.
For those wanting to query a GraphQL service WITHOUT a third party library, I basically took Brian's code and tested against a GraphCMS service I had already written Node.js code for. So I knew the url, authorization token, and query all worked.
<?php
$endpoint = "https://api-euwest.graphcms.com/v1/[[your id number here]]/master";//this is provided by graphcms
$authToken = "[[your auth token]]";//this is provided by graphcms
$qry = '{"query":"query {products(where:{status:PUBLISHED}){title,img,description,costPrice,sellPrice,quantity,sku,categories {name},brand {name}}}"}';
$headers = array();
$headers[] = 'Content-Type: application/json';
$headers[] = 'Authorization: Bearer '.$authToken;
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $endpoint);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 0);
curl_setopt($ch, CURLOPT_POSTFIELDS, $qry);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$result = curl_exec($ch);
var_dump($result);
if (curl_errno($ch)) {
echo 'Error:' . curl_error($ch);
}
?>
All worked fine.
The auth token is a big long character string provided by GraphCMS and only needs to be passed in the header. So no real tricky authentication process - as long as you have the token.
I can recommend using https://github.com/softonic/graphql-client, it has worked great for us.
A way easier way to go about doing this is by using an API platform. I often use Postman, the platform have the functionality to give you the PHP cURL code for a GraphQL request in the GraphQl tools part of the application.
You can create your own client passing whatever middleware you'd like:
$clientWithMiddleware = \MyGuzzleClientWithMiddlware::build();
$graphQLClient = new \Softonic\GraphQL\Client(
$clientWithMiddleware,
new \Softonic\GraphQL\ResponseBuilder()
);
For an example how to build a Guzzle client with middleware you can check this out:
https://github.com/softonic/guzzle-oauth2-middleware/blob/master/src/ClientBuilder.php
If there is no authentication
You can use file_get_contents instead of curl
$url = http://myapi/graphql?query={me{name}}
$html =file_get_contents($url);
echo $html;
use json in query paramter for graphql;
Bit late but I made this code
$endpoint = "https://gql.waveapps.com/graphql/public";
$authToken = ""; //Your Bearer code
$qry = '{"query": "query {user {id firstName lastName defaultEmail createdAt modifiedAt}}"}';
$headers = array();
$headers[] = 'Content-Type: application/json';
$headers[] = 'Authorization: Bearer '.$authToken;
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $endpoint);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $qry);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$result = curl_exec($ch);
var_dump($result);
if (curl_errno($ch)) {
echo 'Error:' . curl_error($ch);
}

Passing JSON to PHP CURL [duplicate]

I have been working on building an Rest API for the hell of it and I have been testing it out as I go along by using curl from the command line which is very easy for CRUD
I can successfully make these call from the command line
curl -u username:pass -X GET http://api.mysite.com/pet/1
curl -d '{"dog":"tall"}' -u username:pass -X GET http://api.mysite.com/pet
curl -d '{"dog":"short"}' -u username:pass -X POST http://api.mysite.com/pet
curl -d '{"dog":"tall"}' -u username:pass -X PUT http://api.mysite.com/pet/1
The above calls are easy to make from the command line and work fine with my api, but now I want to use PHP to create the curl. As you can see, I pass data as a json string. I have read around and I think I can probably do the POST and include the POST fields, but I have not been able to find out how to pass http body data with GET. Everything I see says you must attached it to the url, but it doesn't look that way on the command line form. Any way, I would love it if someone could write the correct way to do these four operations in PHP here on one page. I would like to see the simplest way to do it with curl and php. I think I need to pass everything through the http body because my php api catching everything with php://input
PUT
$data = array('username'=>'dog','password'=>'tall');
$data_json = json_encode($data);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json','Content-Length: ' . strlen($data_json)));
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'PUT');
curl_setopt($ch, CURLOPT_POSTFIELDS,$data_json);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
curl_close($ch);
POST
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS,$data_json);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
curl_close($ch);
GET
See #Dan H answer
DELETE
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "DELETE");
curl_setopt($ch, CURLOPT_POSTFIELDS,$data_json);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
curl_close($ch);
You can use this small library: https://github.com/ledfusion/php-rest-curl
Making a call is as simple as:
// GET
$result = RestCurl::get($URL, array('id' => 12345678));
// POST
$result = RestCurl::post($URL, array('name' => 'John'));
// PUT
$result = RestCurl::put($URL, array('$set' => array('lastName' => "Smith")));
// DELETE
$result = RestCurl::delete($URL);
And for the $result variable:
$result['status'] is the HTTP response code
$result['data'] an array with the JSON response parsed
$result['header'] a string with the response headers
Hope it helps
For myself, I just encode it in the url and use $_GET on the destination page. Here's a line as an example.
$ch = curl_init();
$this->json->p->method = "whatever";
curl_setopt($ch, CURLOPT_URL, "http://" . $_SERVER['SERVER_NAME'] . $this->json->path . '?json=' . urlencode(json_encode($this->json->p)));
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$output = curl_exec($ch);
curl_close($ch);
EDIT: Adding the destination snippet... (EDIT 2 added more above at OPs request)
<?php
if(!isset($_GET['json']))
die("FAILURE");
$json = json_decode($_GET['json']);
$method = $json->method;
...
?>
I was Working with Elastic SQL plugin.
Query is done with GET method using cURL as below:
curl -XGET http://localhost:9200/_sql/_explain -H 'Content-Type: application/json' \
-d 'SELECT city.keyword as city FROM routes group by city.keyword order by city'
I exposed a custom port at public server, doing a reverse proxy with Basic Auth set.
This code, works fine plus Basic Auth Header:
$host = 'http://myhost.com:9200';
$uri = "/_sql/_explain";
$auth = "john:doe";
$data = "SELECT city.keyword as city FROM routes group by city.keyword order by city";
function restCurl($host, $uri, $data = null, $auth = null, $method = 'DELETE'){
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $host.$uri);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $method);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
if ($method == 'POST')
curl_setopt($ch, CURLOPT_POST, 1);
if ($auth)
curl_setopt($ch, CURLOPT_USERPWD, $auth);
if (strlen($data) > 0)
curl_setopt($ch, CURLOPT_POSTFIELDS,$data);
$resp = curl_exec($ch);
if(!$resp){
$resp = (json_encode(array(array("error" => curl_error($ch), "code" => curl_errno($ch)))));
}
curl_close($ch);
return $resp;
}
$resp = restCurl($host, $uri); //DELETE
$resp = restCurl($host, $uri, $data, $auth, 'GET'); //GET
$resp = restCurl($host, $uri, $data, $auth, 'POST'); //POST
$resp = restCurl($host, $uri, $data, $auth, 'PUT'); //PUT
set one more property curl_setopt($ch, CURLOPT_SSL_VERIFYPEER , false);

CURL x-www-form-urlencoded request - PHP

I'm trying to write simple CURL request from server. Script looks like:
$ch = curl_init();
$url = 'http://URL/';
curl_setopt($ch, CURLOPT_URL, $url);
// ADD URL
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/x-www-form-urlencoded',
'Accept: application/json',
'Authorization: Basic Y291bn54adsASD78asd5LWFkbWlu'));
// ADD HEADER
curl_setopt($ch, CURLOPT_POST, 1);
// SAY IT'S POST
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
if($response === false){
echo 'Curl error: ' . curl_error($ch);
}
else{
$sessionID = json_decode($response, true);
print_r($sessionID);
}
curl_close($ch);
Problem is that I need to add some x-www-form-urlencoded like: grant_type = value, login = value2, password=value3. But I just can't make it work.
Can somebody help please?
The values must be like they would be in an URL (hence the urlencoded), so:
grant_type=value&login=value2&password=value3
If values are not numbers, you will probably need to enclose them between quotes.

Categories