Getting data from Kobo Toolbox - rest

I want to get my form data back from kobo api (https://kc.kobotoolbox.org/api/v1/). I registered client application from kobo. To authorize client application, i run below url but it results in
http://localhost/kobo/o/authorize?client_id=MY_CLIENT_iD&response_type=code&state=xyz
Object not found!
The requested URL was not found on this server. If you entered the URL manually please check your spelling and try again.
If you think this is a server error, please contact the webmaster.
Error 404
localhost
Apache/2.4.27 (Win32) OpenSSL/1.0.2l PHP/7.1.9
Similarly request for access token also result in same error
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "http://localhost/o/token/");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, "grant_type=authorization_code&\ncode=PSwrMilnJESZVFfFsyEmEukNv0sGZ8&\nclient_id=MY_CLIENT_ID&\nredirect_uri=http://localhost:30000");
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_USERPWD, "USERNAME" . ":" . "PASSWORD");
$headers = array();
$headers[] = "Content-Type: application/x-www-form-urlencoded";
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$result = curl_exec($ch);
echo $result;
if (curl_errno($ch)) {
echo 'Error:' . curl_error($ch);
}
curl_close ($ch);
Object not found!
The requested URL was not found on this server. If you entered the URL manually please check your spelling and try again.
If you think this is a server error, please contact the webmaster.
Error 404
localhost
Apache/2.4.27 (Win32) OpenSSL/1.0.2l PHP/7.1.9
I am using xampp and curl is enabled.

You have to use https://kc.kobotoolbox.org/api/v1/ not https://kf.kobotoolbox.org/api/v1/
checkout docs here http://help.kobotoolbox.org/managing-your-project-s-data/rest-services
MY WORKING CODE:
$url = 'https://kc.kobotoolbox.org/api/v1/stats';
$data = array (
// 'q' => 'nokia'
);
$params = '';
foreach($data as $key=>$value)
$params .= $key.'='.$value.'&';
$params = trim($params, '&');
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url.'?'.$params ); //Url together with parameters
//curl_setopt($ch, CURLOPT_CONNECTTIMEOUT , 7); //Timeout after 7 seconds
//curl_setopt($ch, CURLOPT_HEADER , false);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$header = array();
$header[] = 'Content-length: 0';
$header[] = 'Content-type: application/json';
$header[] = 'Authorization: Token xxxxxxxx';
curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
//curl_setopt($ch, CURLOPT_USERPWD, "USERNAME" . ":" . "PASSWORD");
$result = curl_exec($ch);
if(curl_errno($ch)) //catch if curl error exists and show it
echo 'Curl error: ' . curl_error($ch);
echo $result;

Related

Magento 2 rest api Consumer is not authorized to access %resources<

I want to get the products from magento 2 that is in my localhost. but when i put /rest/V1/products? it gives me
<response>
<message>Consumer is not authorized to access %resources</message>
<parameters>
<resources>Magento_Catalog::products</resources>
</parameters>
</response>
i have made roles and also integration. i don't know how to access these resources. i have to get these products in my ionic app
That error is fairly self explanatory - you haven't authenticated.
Here's an example of how to authenticate with an admin user and fetch products using curl;
// Fetch the user auth token
$userData = array("username" => "USER", "password" => "PASS");
$ch = curl_init("http://DOMAINNAME.com/index.php/rest/V1/integration/admin/token");
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($userData));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array("Content-Type: application/json", "Content-Lenght: " . strlen(json_encode($userData))));
$token = curl_exec($ch);
// Now use the token to get all products
$ch = curl_init("http://DOMAINNAME.com/index.php/rest/default/V1/products?searchCriteria");
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "GET");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array("Content-Type: application/json", "Authorization: Bearer " . json_decode($token)));
// Here are the results
$result = curl_exec($ch);
$result = json_decode($result, 1);
echo '<pre>';
print_r($result);
echo '</pre>';

Upload a file into dropbox folder

I have tried this to upload a file from a folder in my desktop to a folder in dropbox account.
but each time i have uploaded an empty file through this code.
How it is possible?
Below s my code:
$ch = curl_init();
$TOKEN = "asasasa";//token here
$url = 'https://content.dropboxapi.com/2/files/upload';
curl_setopt($ch,CURLOPT_URL,$url);
curl_setopt($ch,CURLOPT_POST, 1);
curl_setopt($ch,CURLOPT_RETURNTRANSFER, true);
$headers = array();
$headers[] = 'Accept: application/json';
$headers[] = 'Content-Type: multipart/form-data';
$headers[] = 'Dropbox-API-Arg:{"path":"/home/new/ofd","mode":{".tag":"add"},"autorename":false,"mute":false}';
$headers[] = "Authorization: Bearer ".$TOKEN;
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$response = curl_exec($ch);
$droplist = json_decode($response,true);
You don't seem to be adding the file content to the upload call anywhere, so an empty file is expected from your code.
You can find an example of using /2/files/upload with curl in PHP below. That uses CURLOPT_INFILE to add the file content itself.
<?php
$path = 'test_php_upload.txt';
$fp = fopen($path, 'rb');
$size = filesize($path);
$cheaders = array('Authorization: Bearer <ACCESS_TOKEN>',
'Content-Type: application/octet-stream',
'Dropbox-API-Arg: {"path":"/test/'.$path.'", "mode":"add"}');
$ch = curl_init('https://content.dropboxapi.com/2/files/upload');
curl_setopt($ch, CURLOPT_HTTPHEADER, $cheaders);
curl_setopt($ch, CURLOPT_PUT, true);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST');
curl_setopt($ch, CURLOPT_INFILE, $fp);
curl_setopt($ch, CURLOPT_INFILESIZE, $size);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
echo $response;
curl_close($ch);
fclose($fp);
?>
<ACCESS_TOKEN> should be replaced with the OAuth 2 access token.
Upload a file into dropbox folder dropbox api v2
$dropbox_api_url = 'https://content.dropboxapi.com/2/files/upload'; //dropbox api url
$token = 'Access token value put here'; // should be replaced with the OAuth 2 access token
$headers = array('Authorization: Bearer '. $token,
'Content-Type: application/octet-stream',
'Dropbox-API-Arg: '.
json_encode(
array(
"path"=> '/'. basename($filename),
"mode" => "add",
"autorename" => true,
"mute" => false
)
)
);
$ch = curl_init($dropbox_api_url);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_POST, true);
$path = $filename;
$fp = fopen($path, 'rb');
$filesize = filesize($path);
curl_setopt($ch, CURLOPT_POSTFIELDS, fread($fp, $filesize));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
$http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
//For display value as array object starts here
echo "<pre>";
print_r(json_decode($response));
//For display value as array object ends here
echo($response.'<br/>');
echo($http_code.'<br/>');
curl_close($ch);

Magento2; update stock by REST API

I've set up a local Magento 2.1.2 environment with sample data. I'm trying to find the correct code for updating stocks through the REST api (catalogInventoryStockRegistryV1 - Put).
This is what i've got so far:
<?php
$adminUrl = 'http://www.localurl.pro/rest/V1/integration/admin/token/';
$ch = curl_init();
$data = array("username" => "admin", "password" => "66sRz97CZt7N[GdqFU");
$data_string = json_encode($data);
$ch = curl_init($adminUrl);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json',
'Content-Length: ' . strlen($data_string))
);
$token = curl_exec($ch);
$token= json_decode($token);
$headers = array("Authorization: Bearer $token");
$requestUrl='http://www.localurl.pro/rest/V1/products/24-MB01/stockItems/1';
// Sample SKU
$sampleProductData = array(
"qty" => 100
);
$productData = json_encode(array('stockItem' => $sampleProductData));
// Prints: {"stockItem":{"qty":100}}
$ch = curl_init();
curl_setopt($ch,CURLOPT_URL, $requestUrl);
curl_setopt($ch,CURLOPT_POSTFIELDS, $productData);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PUT");
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
curl_close($ch);
var_dump($response);
This script gives the following error:
string(122) "{"message":"Server cannot understand Content-Type HTTP header media type application\/x-www-form-urlencoded","trace":null}"
I'm not sure what the message exactly means. Some help would be greatly appreciated.
Solution
Solution given by Mohan Gopal. 'Content-Type: application/json' was missing in the curl header.
<?php
$adminUrl = 'http://www.localhost.pro/rest/V1/integration/admin/token/';
$ch = curl_init();
$data = array("username" => "admin", "password" => "66sRz97CZt7N[GdqFU");
$data_string = json_encode($data);
$ch = curl_init($adminUrl);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json',
'Content-Length: ' . strlen($data_string))
);
$token = curl_exec($ch);
$token= json_decode($token);
//Use above token into header
$headers = array("Authorization: Bearer $token","Content-Type: application/json");
$skus = array(
'24-MB04' => 10,
'24-MB03' => 5
);
foreach ($skus as $sku => $stock) {
$requestUrl='http://www.localurl.pro/rest/V1/products/' . $sku . '/stockItems/1';
$sampleProductData = array(
"qty" => $stock
);
$productData = json_encode(array('stockItem' => $sampleProductData));
$ch = curl_init();
curl_setopt($ch,CURLOPT_URL, $requestUrl);
curl_setopt($ch,CURLOPT_POSTFIELDS, $productData);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PUT");
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
curl_close($ch);
var_dump($response);
unset($productData);
unset($sampleProductData);
}
Add the content type to header and change the header from
$headers = array("Authorization: Bearer $token");
to
$headers = array("Authorization: Bearer $token","Content-Type:
application/json");
after getting the token id on line 53.

PUT request to REST api using cURL

I am trying to do a put request to a RESTapi using cURL. I was able to do post request. But PUT is not working
I used following code
public function callTeamworkPutApi($secretApiKey, $apiCallString,$param)
{
//cURL
$password = "xxx";
$channel = curl_init();
//options
curl_setopt($channel, CURLOPT_URL, "http://projects.abounde.com/".$apiCallString); // projects.json?status=LATE gets all late projects
$headers = array();
$headers[] = "Authorization: Basic " . base64_encode($secretApiKey . ":" . $password);
$headers[] = "Content-Type: application/json";
curl_setopt($channel, CURLOPT_HTTPHEADER, $headers);
curl_setopt($channel, CURLOPT_PUT, true);
//curl_setopt($channel, CURLOPT_POSTFIELDS, $comment);
curl_setopt($channel, CURLOPT_PUTFIELDS, $param);
// curl_setopt($channel, CURLOPT_RETURNTRANSFER, true);
$msg = curl_exec($channel);
$tester =var_dump(curl_getinfo($channel));
curl_close($channel);
//var_dump($msg);
return response()->json(['res'=>$tester]);
}
Error:
Any Idea?
Just been doing that myself today. here is example code.
$data = array("a" => $a);
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PUT");
curl_setopt($ch, CURLOPT_POSTFIELDS,http_build_query($data));
$response = curl_exec($ch);
if (!$response)
{
return false;
}
src: http://www.lornajane.net/posts/2009/putting-data-fields-with-php-curl

PayPal - Invalid caller, requires client_id & secret

I'm trying to make a request to Paypal to get a new access token, but when trying a simple curl call, it's returning with this error -
"Invalid_request - Invalid caller, requires client_id & secret"
Not quite sure what's wrong with this. The client id and secret are correct and are included.
Here is what I've tried -
$clientId = "XXX";
$secret = "XXX";
$url = "https://api.sandbox.paypal.com/v1/oauth2/token";
$method = 'POST';
$postvals = sprintf("client_id=%s&client_secret=%s&grant_type=%s&refresh_token=%s",
$clientId,
$secret,
'refresh_token',
$refreshToken);
$ch = curl_init($url);
if ($method == 'POST'){
$options = array(
CURLOPT_POST => 1,
CURLOPT_POSTFIELDS => $postvals,
);
curl_setopt_array($ch, $options);
}
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLINFO_HEADER_OUT, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 1);
curl_setopt($ch, CURLOPT_SSLVERSION, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_USERPWD, $clientId.":".$secret);
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
curl_setopt($ch, CURLOPT_TIMEOUT, 60);
curl_setopt($ch, CURLOPT_VERBOSE, true);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
"Accept: application/json",
"Accept-Language: en_US",
"Content-Type: application/x-www-form-urlencoded",
'Authorization: Bearer '.$old_accessToken,
"Host: www.paypal.com",
"Connection: close"
)
);
$result = curl_exec($ch);
// Get Request and Response Headers
$requestHeaders = curl_getinfo($ch, CURLINFO_HEADER_OUT);
$responseHeaderSize = strlen($result) - curl_getinfo($ch, CURLINFO_SIZE_DOWNLOAD);
$responseHeaders = substr($result, 0, $responseHeaderSize);
//only use body and not header, otherwise return is NULL
$result = substr($result, $responseHeaderSize);
if(!$result || empty($result)){
echo 'Curl error or response is empty: ' . curl_error($ch);
curl_close($ch);
} else {
curl_close($ch);
$response =json_decode($result);
var_dump($response);
}
This solution worked instead -
$clientId = "XXXX";
$clientSecret = "XXXX";
$url = "https://api.sandbox.paypal.com/v1/oauth2/token";
$method = 'POST';
$postdata = sprintf("client_id=%s&client_secret=%s&grant_type=%s&refresh_token=%s",
$clientId,
$secret,
'refresh_token',
$refreshToken);
$curl = curl_init($url);
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($curl, CURLOPT_USERPWD, $clientId . ":" . $clientSecret);
curl_setopt($curl, CURLOPT_HEADER, false);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, $postdata);
# curl_setopt($curl, CURLOPT_VERBOSE, TRUE);
$response = curl_exec( $curl );
if (empty($response)) {
// some kind of an error happened
die(curl_error($curl));
curl_close($curl); // close cURL handler
} else {
$info = curl_getinfo($curl);
echo "Time took: " . $info['total_time']*1000 . "ms\n";
curl_close($curl); // close cURL handler
if($info['http_code'] != 200 && $info['http_code'] != 201 ) {
echo "Received error: " . $info['http_code']. "\n";
echo "Raw response:".$response."\n";
die();
}
}
// Convert the result from JSON format to a PHP array
$jsonResponse = json_decode( $response );