How to access Smartsheet from PHP API? - php

It is my first time trying to connect Sheet from Smartsheet using API with PHP.
I cannot seem to connect and give me this error
Notice: Trying to get property of non-object in C:\xampp\htdocs\smartsheet\test.php on line 22
The variable $sheetObj is empty.
And in Authorization: Bearer, what does Bearer means? Is it a token name or it is always Bearer?
My future plan is to write into the row of smartsheet using PHP. Can anyone give me advice what went wrong with my code?
$baseURL = "https://api.smartsheet.com/1.1";
$sheetsURL = $baseURL . "/sheets/";
$getSheetURL = $baseURL . "/sheet/xxxxxxxxxxx";
$rowsURL = $baseURL . "/sheet/xxxxxxxxxxx/rows";
$accessToken = "xxxxxxxxxxxxxxxxxx";
// Create Headers array for cURL
$headers = array(
"Authorization: Bearer " . $accessToken,
"Content-Type: application/json"
);
$curlSession = curl_init($getSheetURL);
curl_setopt($curlSession, CURLOPT_HTTPHEADER, $headers);
curl_setopt($curlSession, CURLOPT_RETURNTRANSFER, TRUE);
$getSheetResponseData = curl_exec($curlSession);
$sheetObj = json_decode($getSheetResponseData);
echo "<h1>Sheet name: ". $sheetObj->name ."</h1>";

Both stmcallister and Kim provided good information on how to troubleshoot your issue and some likely causes.
There were actually two issues with the code you provided.
As Scott mentioned you must point to the 2.0 version of the API.
$baseURL = "https://api.smartsheet.com/2.0";
You have a typo in your $getSheetURL. As is documented here the url is /sheets/{sheetId}. So your code should have the following:
$getSheetURL = $baseURL. "/sheets/xxxxxxxxxxx";
Here is your code in a working state. Make sure to replace YOUR_TOKEN and also take a look at the output from var_dump (which I added to your code) to see what message it gives you.
<?php
$baseURL = "https://api.smartsheet.com/2.0";
$getSheetURL = $baseURL. "/sheets/4925037959505796";
$accessToken = "YOUR_TOKEN";
$headers = array("Authorization: Bearer ". $accessToken);
$curlSession = curl_init($getSheetURL);
curl_setopt($curlSession, CURLOPT_HTTPHEADER, $headers);
curl_setopt($curlSession, CURLOPT_RETURNTRANSFER, TRUE);
$getSheetResponseData = curl_exec($curlSession);
// Remove this line when done debugging
var_dump($getSheetResponseData);
$sheetObj = json_decode($getSheetResponseData);
echo "<h1>Sheet name: ". $sheetObj->name ."</h1>";
?>

Search here on SO for the (partial) error message "Trying to get property of non-object" and you'll see lots of related posts. Essentially, this error means that your code is treating something as an object that's not actually an object. This would happen, for instance, when you try to access the name property of $sheetObj if the API request had previously failed for some reason and the contents of $sheetObj is therefore not actually an object.
I'm not very familiar with PHP, but I'd suspect (based on the error message, combined with the fact that you say "var_dump($getSheetResponseData) is Bool(false)) that the "Get Sheet" request may not be returning a successful response. To troubleshoot, I'd suggest that you try running the exact same "Get Sheet" request (i.e., with identical URI, including sheet Id) using a tool like Postman (https://www.getpostman.com/) or via the commandline with cURL, and see if you get a successful response. If you can get your request working via Postman or cURL, it should be straightforward to update your code to send the same request, resulting in a successful response. See this section of the Smartsheet API docs for info about API Troubleshooting techniques using Postman or cURL: http://smartsheet-platform.github.io/api-docs/#api-troubleshooting.

Version 1.1 of the Smartsheet API is no longer supported. You'll want to use version 2.
To do this just change $baseURL to this:
$baseURL = "https://api.smartsheet.com/2.0";
Also, each of the objects in the API will be represented by plural endpoints. So, to get a sheet you'll use:
$getSheetURL = $baseURL. "/sheets/xxxxxxxxxxx";
To get the rows you'll use:
$rowsURL = $baseURL. "/sheets/xxxxxxxxxxx/rows";
Bearer is the type of Authorization header that you're passing to the API, and the type that is required by the Smartsheet API.

Hello to use the smartsheet API connection to PHP, the API version 2.0 is used, because the older version is obsolete, the code for the connection is as follows:
$baseURL = "https://api.smartsheet.com/2.0/sheets";
// Insertar access token generado en SmartSheet
$accessToken = "YOUR_TOKEN";
// Creación del Headers Array para el Curl
$headers = array(
"Authorization: Bearer $accessToken",
"Content-Type: application/json");
//Conexión de la API de SmartSheet
$curlSession = curl_init($baseURL);
curl_setopt($curlSession, CURLOPT_HTTPHEADER, $headers);
curl_setopt($curlSession, CURLOPT_RETURNTRANSFER, true);
//Establece la sesión del Curl
$smartsheetData = curl_exec($curlSession);
// Asignar respuesta a un objeto PHP
$createObj = json_decode($smartsheetData);

Related

How to pass GET parameters in curl PHP

I am new to PHP development. I am working on CURL to call my WEB API. As a newbie I found very hard to understand things.
How my API is working
API_URL is http://localhost:14909/api/meters/GetByMsn/002999000077/2017-10-11T12:16:20
It takes a meter serial number and a data time and gives the response by authorizing the URL. The response I get is
{
"data": {
"Response": "No"
}
}
What I want to do
Now In PHP I am using CURL to make the request. The request is simple as it takes the current selected meter serial number and a current date time also it should take authorization key.
What I have done till now
Below is the code so far i have done
if( isset($_REQUEST['selected_meters']))
{
$m = MetersInventoryStore::findOne($_REQUEST['selected_meters']);
$msn = $m->meter_serial; // current selected meter serial number is saved
$date_time = str_replace(' ','T',date('Y-m-d H:i:s')); // current date time
$api_url = 'http://116.xx.xx.xx:xxxx/api/meters/GetByMsn/'; // my base URL
$curl = curl_init($api_url);
curl_setopt($curl,CURLOPT_RETURNTRANSFER, CURLOPT_HTTPHEADER, array('Authorization: MY_KEY')); // setting the authorization key in header.
exit();
}
Now I want to send the meter serial number and date time parameters. For this I have searched many articles but all I found a way to pass parameters as query and related link.
One method I am thinking of is passing parameters direct to the URL Like:
$api_url = 'http://116.xx.xx.xx:xxxx/api/meters/GetByMsn/[$msn]/[$date_time]';
OR
$api_url = 'http://116.xx.xx.xx:xxxx/api/meters/GetByMsn/' + $msn + '/'+$date_time;
But I don't know will it works or not
Any help would be highly appreciated.
Try this out and see if it works:
$api_url = 'http://116.xx.xx.xx:xxxx/api/meters/GetByMsn/${msn}/${date_time}';
or
$api_url = 'http://116.xx.xx.xx:xxxx/api/meters/GetByMsn/{$msn}/{$date_time}';
So after a lot of searching I manage to get a response. Concatenate both of the parameters in the URL and changing the curl_setopt.
Changes:
From
$api_url = 'http://116.xx.xx.xx:xxxx/api/meters/GetByMsn/'; // my base URL
To
$api_url = 'http://116.xx.xx.xx:xxxx/api/meters/GetByMsn/'.$msn . '/' . $date_time; // my base URL
And
curl_setopt($curl,CURLOPT_RETURNTRANSFER, CURLOPT_HTTPHEADER, array('Authorization: MY_KEY')); // setting the authorization key in header.
To
curl_setopt($curl CURLOPT_HTTPHEADER, array('Authorization: MY_KEY')); // Removed the CURLOPT_RETURNTRANSFER
And then
$curl_response = curl_exec($curl);
print_r($curl_response);
/* print_r($msn);
echo $date_time;*/
//echo date('Y-m-d H:i:s');
exit();

VIMEO (Pro) get JSON response help (PHP/CURL)

I have a Vimeo PRO account.
I have protected videos uploaded.
Videos are also set to ONLY be embeddable on my domains (set in the video settings)
I am -not- grasping how to use their examples (sorry, for me the examples do not include real working samples for me,..or at least how to implement them to understand.. so I'm hoping to get some help)
Not clear on all the OAuth2, Oembed... authentication stuff either.. which I believe is where my problem lies.
I was following this gitHub example:
https://github.com/vimeo/vimeo-api-examples/blob/master/oembed/php-example.php
(looks to be pretty old?)
I'm looking to get JSON data returned for a video when an ID is passed along.
I was/am under the impression that I need to 'authenticate' before I can get my response/return data?
Is this best done in the CURL header or something?
Can someone guide me a bit more? (shouldnt be this hard!) haha..
Here is my code:
$video_endpoint = 'https://api.vimeo.com/videos/';
$video_url = '171811266';
//JSON url
//$json_url = $video_endpoint . '.json?url=' . rawurlencode($video_url);
//this fixes the cURL approach
$json_url = $video_endpoint . rawurlencode($video_url);
// Curl helper function
function curl_get($url) {
$curl = curl_init($url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_TIMEOUT, 30);
curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1);
//curl_setopt($curl, CURLOPT_HTTPHEADER, array('Authorization : bearer xxxxxx'));
$return = curl_exec($curl);
curl_close($curl);
return $return;
}
$vimeoJSON = json_decode((curl_get($json_url)));
var_dump($vimeoJSON);
And I get this response:
object(stdClass)#1 (1) { ["error"]=> string(52) "You must provide a valid authenticated access token." }
questions are:
1.) Is this even a valid approach? (assuming I just need to append some lines of code to the CURL header to send my auth over before getting a response?)
2.) How do I update my CURL snippet to work with VIEMO authentication?
I'm trying to keep this as CLEAN/SIMPLE as I can (for the JSON call/return portion)..
Any guidance is appreciated.
Thanks
update:
this code does NOT work:
$access_token = 'xxx';
$video_endpoint = 'https://api.vimeo.com/videos/';
$video_url = '171811266';
$json_url = $video_endpoint . '.json?url=' . rawurlencode($video_url);
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => $json_url,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "GET",
CURLOPT_HTTPHEADER => array(
"authorization: Bearer ".$access_token
),
));
$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
if ($err) {
echo "cURL Error #:" . $err;
} else {
echo $response;
}
The video I want to use is located here:
https://vimeo.com/171811266/5822169b48
IT IS A PRIVATE VIDEO. (not sure you'll be able to see it)..
When I use the latest version of the code posted above.. I get this response:
{"error":"The requested video could not be found"}
Is this because its a PRIVATE video?
(actually I just set the video to be able to be viewed by anyone.. and I still got the same error/response) (not found)
If so.. what is the fix to use MY videos.. that are set to private... but use them on my site/domain still?
===========================================================================
FINAL UPDATE:
Trying to use the code in the readme example:
https://github.com/vimeo/vimeo.php
Trying to use (un-successfully) the LIB #Dashron pointed me too.. I cant even seem to get the basics to work from the GIT Page:
Code:
//project vars
$client_id = 'xxxx';
$client_secret = 'xxx';
$access_token = 'xxx';
$redirect_uri = 'http://domain.com/file.php'; //where do I redirect them back to? the page where I have the embeded video at?
// scope is an array of permissions your token needs to access. You can read more at https://developer.vimeo.com/api/authentication#scopes
$scopes = Array('public', 'private');
$state = 'Ldhg0478y';
require("Vimeo/autoload.php");
$lib = new Vimeo\Vimeo($client_id, $client_secret);
// build a link to Vimeo so your users can authorize your app. //whatever that means and is for?
$url = $lib->buildAuthorizationEndpoint($redirect_uri, $scopes, $state);
// redirect_uri must be provided, and must match your configured uri
$token = $lib->accessToken(code, redirect_uri);
// usable access token
var_dump($token['body']['access_token']);
// accepted scopes
var_dump($token['body']['scope']);
// use the token
$lib->setToken($token['body']['access_token']);
I get this error message:
Parse error: syntax error, unexpected Fatal error: Class 'Vimeo\Vimeo' not found in /usr/www/users/aaemorg/aaem.org/video/vimeo_lib.php
Seems like its not creating instantiating my $lib object/class??
(I know I'm not great at high level PHP class/code... but this absurdly hard just to get a JSON response for video I own to embed (again) on a site I own as well)
Any direction would be appreciated?
======================================================================
Update: "what worked for me"..
I am appreciate the link to the 'official' library.. but the readme examples just didnt work for me...
To keep things nice and easy for others who may be new to the Vimeo API stuff as well.. here is a quick and dirty, simple code sample to get you up and running:
<?
//include offifial library
require("Vimeo/autoload.php");
$client_id = 'xxx';
$client_secret = 'xxx';
$access_token = 'xxx';
$video_id = 'xxx';
$lib = new Vimeo\Vimeo($client_id, $client_secret, $access_token);
$video_response = $lib->request('/videos/'.$video_id);
//dont really need this, but included in case there is some data you need to display
$token_response = $lib->clientCredentials();
//example of parsing out specific data from the array returned
//name/title
echo $video_response['body']['name'] . '<br><br>';
?>
The link you provided is very, very old. It is actually part of a different API, and no longer relevant.
The Library you should be using is located here: https://github.com/vimeo/vimeo.php with many examples in the readme, and the examples directory!
Below code works for me
Please follow this step before
Under video settings : General->privacy, Change Who can watch select box to Anyone.
$url = 'https://api.vimeo.com/videos/388591356';
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
$headers = array();
$headers[] = "Content-Type: application/x-www-form-urlencoded";
$headers[] = "Accept: application/json";
$headers[] = "Authorization: Bearer 969329f9b5b3882d74d1b39297528242";
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
$result = curl_exec($ch);
curl_close($ch);
$final_result = json_decode( preg_replace('/[\x00-\x1F\x80-\xFF]/', '', $result), true );
echo "<pre>";
print_r($final_result);

How to use GET in PHP with OneNote API?

I've got the OneNote API PHP Sample (thanks jamescro!) working with all the POST examples, but there's no GET example and I haven't managed to put together code of my own that works. Here's what I've tried without success:
// Use page ID returned by POST
$pageID = '/0-1bf269c43a694dd3aaa7229631469712!93-240BD74C83900C17!600';
$initUrl = URL . $pageID;
$cookieValues = parseQueryString(#$_COOKIE['wl_auth']);
$encodedAccessToken = rawurlencode(#$cookieValues['access_token']);
$ch = curl_init($initUrl);
curl_setopt($ch, CURLOPT_URL, $initUrl); // Set URL to download
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
if (! $response === false) {
curl_close($ch);
echo '<i>Response</i>: '. htmlspecialchars($response);
}
else {
$info = curl_getinfo($ch);
curl_close($ch);
echo '<i>Error</i>: ';
echo var_export($info);
}
It just returns 'Error' with an info dump. What am I doing wrong?
without information on the specific error I'm not sure what issue you are hitting. Try looking at the PHP Wordpress plugin here: https://github.com/wp-plugins/onenote-publisher/blob/master/api-proxy.php
look at what is sent to wp_remote_get - there are necessary headers that are needed.
Also make sure you have the scope "office.onenote" when you request the access token.
If you need more help, please add information about the specific URL you are attempting to call, as well as the contents of your headers. If you have any errors, please include the output.
Solved:
As Jay Ongg pointed out, "there are necessary headers that are needed".
After adding more detailed error checking and getting a 401 response code, I added:
curl_setopt($ch, CURLOPT_HTTPHEADER, array("Content-Type:text/html\r\n".
"Authorization: Bearer ".$encodedAccessToken));
... and could access the requested page.

Docusign REST call from CodeIgniter

I'm trying to call the DocuSign REST login information within a CodeIgniter application. The Docusign sample code shows:
// Input your info here:
$integratorKey = '...';
$email = '...#....com';
$password = '...';
$name = 'John Doe';
// construct the authentication header:
$header = "<DocuSignCredentials><Username>" . $email . "</Username><Password>" . $password . "</Password><IntegratorKey>" . $integratorKey . "</IntegratorKey></DocuSignCredentials>";
/////////////////////////////////////////////////////////////////////////////////////////////////
// STEP 1 - Login (to retrieve baseUrl and accountId)
/////////////////////////////////////////////////////////////////////////////////////////////////
$url = "https://demo.docusign.net/restapi/v2/login_information";
$curl = curl_init($url);
curl_setopt($curl, CURLOPT_HEADER, false);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_HTTPHEADER, array("X-DocuSign-Authentication: $header"));
$json_response = curl_exec($curl);
$status = curl_getinfo($curl, CURLINFO_HTTP_CODE);
if ( $status != 200 ) {
echo "error calling webservice, status is:" . $status;
exit(-1);
}
I keep getting a status response of 0. When I echo out the curl all the xml tags have been converted to lowercase (which won't work with Docusign). Has anyone done this call within CodeIgniter? How did you accomplish it? I know my credentials are good because I can do a command line curl and get a response.
I'm not sure what CodeIgniter is doing and why the tags would be converted to lower case but you're right in that DocuSign expects xml tags to begin with a capital letter so that might not work. What you can do, though, is use JSON headers and request bodies instead.
For instance, instead of an XML formatted authentication header like
<DocuSignCredentials>
<Username>username</Username>
<Password>password</Password>
<IntegratorKey>integrator_key</IntegratorKey>
</DocuSignCredentials>
You could use the corresponding JSON auth header like
{
"Username": "username",
"Password": "password",
"IntegratorKey": "integrator_key"
}
The "nodes" still start with a capital but since it's not xml I'm wondering if CodeIgniter maybe leaves it alone. Examples of this can be found at the DocuSign Developer Center on this page.

PHP GCM error message MismatchSenderId

I am facing the problem with GCM push notification. I am getting the following error.
{
"multicast_id":4630467710672911593,
"success":0,
"failure":1,
"canonical_ids":0,
"results":[{
"error":"MismatchSenderId"
}]
}
Following is the code. Any help would be really appreciated. Thanks in Advance.
public function gcmPush()
{
$regId = "APA91bHFcgOssQZEqtdUk3EC1ojwC5-LVG3NPV2bMqKyC9rPymR6StmAbz-N7Ss8fnvruZhWWNrR3lmBqpjQItlu00AKHPbltBclUJF-EfC5qG4CF2xiuYYC0NCf8u5rbiYFk8ARhIT4lY2AEPWzGpl1OtTvQEC0gA";
$registatoin_ids = array($regId);
$message = array("msg" => 12345);
$this->send_notification($registatoin_ids, $message);
}
public function send_notification($registatoin_ids, $message)
{
// Set POST variables
$url = 'https://android.googleapis.com/gcm/send';
define('GOOGLE_API_KEY', 'AIzaSyBavsIgQKo1Nf9wKZ5o_fGvE_6MI52LFR0');
$fields = array(
'registration_ids' => $registatoin_ids,
'data' => $message,
);
$headers = array(
'Authorization: key=' . GOOGLE_API_KEY,
'Content-Type: application/json'
);
// Open connection
$ch = curl_init();
// Set the url, number of POST vars, POST data
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
// Disabling SSL Certificate support temporarly
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fields));
// Execute post
$result = curl_exec($ch)
if ($result === FALSE) {
die('Curl failed: ' . curl_error($ch));
}
// Close connection
curl_close($ch);
echo $result;
}
"MismatchSenderId" is the obvious problem that we are getting nowadays.
Here are the possible cases that cause this problem.
Case 1: Mismatching Sender ID ->
Please check the Project number which you are using. If it's is correct or not.
Case 2: Wrong API Key ->
Please be sure that you are using the same API_Key or not. And in most of the cases, we need to generate Server_Key instead of Android_Key.
Case 3: Wrong Device's ID ->
Most of the time the problem is due to the wrong Device ID(Registration ID generated by GCM).
Please be ensure that that Whenever you generate new API key, the device id's of your device gets changed. Then it will take almost 5 five minutes to get an effect.
Note : Your device id is bound with the API KEY.
So....
--New Key created.
--GCM for Android Turned "on" in Google Dev. Console.
--Device registered with backend fine (Android Project is doing its job). Device key on the server.
--Send to device. Fail! The same message is returned from GCM everytime.
To Recap. This is NOT an Android Studio, Android OS, or Device issue. The GCM servers are not even trying to send the message to the device. My server sends to GCM, it returns the message...
{"multicast_id":6047824495557336291,"success":0,"failure":1,"canonical_ids":0,"results":[{"error":"MismatchSenderId"}]}
to the server. As far as I can tell this means the Device's ID (the one returned to the device when it registered for a push, and the one saved on the backend (in the control panel) does not match, or is somehow not associated with the API Key used when sending the message.
Sending, of course, starts on my server, goes to GCM, then goes to the device.
This is what's not happening. The message goes from my server to GCM and back to my server - with the error.
Super frustrating as all of you can imagine - we've all been through this nightmarish stuff before :-)
Reference : https://www.buzztouch.com/forum/thread.php?tid=C3CED924C86828C2172E924
Hope it will solve your problem.

Categories