SugarmCRM REST API always returns "null" - php

I'm trying to test out the SugarCRM REST API, running latest version of CE (6.0.1). It seems that whenever I do a query, the API returns "null", nothing else. If I omit the parameters, then the API returns the API description (which the documentation says it should).
I'm trying to perform a login, passing as parameter the method (login), input_type and response_type (json) and rest_data (JSON encoded parameters). The following code does the query:
$api_target = "http://example.com/sugarcrm/service/v2/rest.php";
$parameters = json_encode(array(
"user_auth" => array(
"user_name" => "admin",
"password" => md5("adminpassword"),
),
"application_name" => "Test",
"name_value_list" => array(),
));
$postData = http_build_query(array(
"method" => "login",
"input_type" => "json",
"response_type" => "json",
"rest_data" => $parameters
));
echo $parameters . "\n";
echo $postData . "\n";
echo file_get_contents($api_target, false,
stream_context_create(array(
"http" => array(
"method" => "POST",
"header" => "Content-Type: application/x-www-form-urlencoded\r\n",
"content" => $postData
)
))) . "\n";
I've tried different variations of parameters and using username instead of user_name, and all provide the same result, just a response "null" and that's it.

Try setting input_type and response_type to JSON (capitals). If it doesn't work, go to Sugar installation, edit config.php entry under logger => level and make it debug instead of fatal and see if it says about any errors.

Related

Empty Payload. JSON content expected (guzzle, php, azur active directory and outlook)

I am a student in programming and I have difficulties with my projects, little documentation meets my expectations and I would need help.
in this project I have to send from my application the token, the json flow on outlook to schedule a meeting
about Project : the principle is on a page to create a meeting which will then be linked to the outlook calendar this document helped me a lot https://learn.microsoft.com/fr-fr/graph/api/calendar-post-events?view=graph-rest-1.0&tabs=http https://youtu.be/orVsKsRs2Us
(data is on another page)
the whole function
public function Postcalendrier($ID,$data) {
$token=$_SESSION['token'];
$ID=$_SESSION["ID"];
$calendarGroup="/calendarGroups/{myID}/";
$calendar="calendars/{myID}/events";
$urlcalendar="https://graph.microsoft.com/v1.0/users/".$ID;
$url=$urlcalendar.$calendarGroup.$calendar;
$headers = [
'Authorization' => 'Bearer '.$token->access_token,
'Accept' => 'application/json',
'Content-Type' => 'application/json',
];
$json = json_encode([$data])
$reponse = $this->guzzle->request('POST', $url,['headers' =>
$headers,'json' => $json],['debug' => true]);
return $response->getStatusCode();
}
$data = array(
"subject" => $Subject,
"body" => array(
"contentType" => "HTML",
"content" => $Content
),
"start" => array(
"dateTime" => $StartDateTime."T".$StartHourTime.":00",
"timeZone" => "$localDatetime"
),
"end" => array(
"dateTime" => $StartDateTime."T".$EndHourTime.":00",
"timeZone" => "$localDatetime"
),
"location" => array(
"displayName" => $Location
),
"attendees"=> [array(
"emailAddress"=> array(
"address"=> $addressmail,
"name"=>$prenom
),
"type"=> "required"
)]
);
I get this error message
Empty Payload. JSON content expected
so I tried with a different JSON but
I got this message instead and I don't really understand it
code UnableToDeserializePostBody message were unable to deserialize
this is my new json
$json = [
'json' => json_encode([$data])
];
thank you for your attention

Dropbox API - Error: expected list got dict

I am currently building a routine that needs to download files from one specific Dropbox folder , send them to another server and then move them to another folder on Dropbox.
I am using the /files/move_batch API endpoint for Dropbox to do so.
Here are the params sent to the API to move multiples files (well I'm only trying to move one file right now as it's still not working) :
$params = array(
'headers' => array(
'method' => 'POST',
'content-type' => 'application/json; charset=utf-8',
),
'body' => json_encode(array(
'entries' => array(
'from_path' => self::$files[0],
'to_path' => '/Applications/Archives/' . substr(self::$files[0], strrpos(self::$files[0], '/') + 1),
),
'autorename' => true,
)),
);
But I keep getting the same error message :
Error in call to API function "files/move_batch": request body: entries: expected list, got dict
I don't know what the API means by a list or how it should be formated.
The entries value should be a list of dict, one per file you want to move, each one containing both a from_path and a to_path. Your code is supplying the entries value to be a single dict though. (In PHP you can make both lists and dicts using the array keyword.)
It's easier to see and work with when you break it into pieces. Here's a working sample that does that.
<?php
$fileop1 = array(
'from_path' => "/test_39995261/a/1.txt",
'to_path' => "/test_39995261/b/1.txt"
);
$fileop2 = array(
'from_path' => "/test_39995261/a/2.txt",
'to_path' => "/test_39995261/b/2.txt"
);
$parameters = array(
'entries' => array($fileop1, $fileop2),
'autorename' => true,
);
$headers = array('Authorization: Bearer <ACCESS_TOKEN>',
'Content-Type: application/json');
$curlOptions = array(
CURLOPT_HTTPHEADER => $headers,
CURLOPT_POST => true,
CURLOPT_POSTFIELDS => json_encode($parameters),
CURLOPT_RETURNTRANSFER => true,
CURLOPT_VERBOSE => true
);
$ch = curl_init('https://api.dropboxapi.com/2/files/move_batch');
curl_setopt_array($ch, $curlOptions);
$response = curl_exec($ch);
echo $response;
curl_close($ch);
?>
To move just one file using this batch endpoint, you would change that line to something like:
'entries' => array($fileop1),

Update video using youtube api

I want to update a video using google api v3 and i get the error 400 Bad Request.
This is my code.
$url = 'https://www.googleapis.com/youtube/v3/videos?part=snippet&videoId='.$_GET['videoId'].'&access_token='.Session::get('access_token');
$params = array(
"id"=> $_GET['videoId'],
"kind"=> "youtube#video",
'snippet' => array(
"title"=> "I'm being changed.",
"categoryId"=> "10",
"tags"=> array(
"humanities",
"Harpham",
"BYU"
),
'description' => 'test!'
)
);
$options = array(
'http' => array(
'header' => "Content-type: application/x-www-form-urlencoded\r\n",
'method' => 'PUT',
'content' => http_build_query($params),
),
);
$context = stream_context_create($options);
$result = json_decode(file_get_contents($url, false, $context));
I think since you don't set all parameters inside snippet, that's giving an error. What you can do is, first getting that video with videos->list, then updating the field you are interested in and sending back the update request with the whole object back.
Here's an example also utilizing php client library: https://github.com/youtube/api-samples/blob/master/php/update_video.php

Linkedin Invitation API Internal server error

Yo!
I'm trying to use the linkedin invitation api to allow users to conncect on linkedin from my application using email-addresses. I am able to find people, access the api and so on. I can't get the invites to work though. I am using php (Laravel).
I based myself on the example from the linkedin documentation ( Linkedin Invite API ). I send my data in a post using JSON (that contains the same info as their example).
I ask permission to use w_messages, the post works and my variables contain the correct information. I get a Internal Server error as a result.
$data = array(
"recipients" => array(
"values" => array(
"person" => array(
"_path" => "/people/email=".$email,
"first-name" => $firstname,
"last-name" => $lastname
)
)
),
"subject" => "Bla",
"body"=> "BlaBLa",
"item-content" => array(
"invitation-request" => array(
"connect-type" => "friend"
)
)
);
$dataString = json_encode($data);
$opts = array('http' =>
array(
'method' => 'POST',
'header' => "Content-type: application/json\r\n".
"Connection: close\r\n" .
"Content-length: " . strlen($dataString) . "\r\n",
'content' => $dataString
)
);
$params = array('oauth2_access_token' => Session::get('access_token'),
'format' => 'json'
);
$url = "https://api.linkedin.com/v1/people/~/mailbox".'?' . http_build_query($params);
$context = stream_context_create($opts);
$result = file_get_contents($url, false, $context);
Log::info($result);
return Response::json(array("invite" => "sent"));
I assume I'm doing something wrong but don't really know where to look.
Looks like you doing this manually, have you tried using a tried & tested third party library like simple-linkedinphp - A PHP-based wrapper for the LinkedIn API.
https://code.google.com/p/simple-linkedinphp/wiki/Reference
Usage:
// Connect
$API_CONFIG = array(
'appKey' => '<your application key here>',
'appSecret' => '<your application secret here>',
'callbackUrl' => NULL
);
$linkedin = new LinkedIn($API_CONFIG);
// Send Invite
$linkedin->invite($method, $recipient, $subject, $body, $type = 'friend');
Doc: https://code.google.com/p/simple-linkedinphp/wiki/Reference

How to construct an AJAX JSON string with PHP to send with POST

I have a simple xmlhttprequest with AJAX and want to rebuild this with PHP.
var data = {};
var payload = {
"flags" : true,
"codes" : true,
"units" : true
};
data.payload = JSON.stringify(payload);
$.ajax({
type : 'POST',
url : 'http://httpbin.org/post',
data : data,
success : function(response) {
var arr = JSON.stringify(response);
document.getElementById('placeholder').innerHTML = arr;
}
});
This works fine!
Now my Version with PHP:
$data = array(
'payload' => array(
'flags' => true,
'codes' => true,
'units' => true
)
);
$options = array(
"http" => array(
"method" => "POST",
"header" => "Content-Type: application/json\r\n",
"content" => json_encode($data)
)
);
$url = "http://httpbin.org/post";
$context = stream_context_create($options);
$response = file_get_contents($url, false, $context);
var_dump($response);
When I compare the results there is a difference in the structure.
Ajax looks like this:
{"form":{"payload":"{\"flags\":\"true\",
and PHP looks like this:
{"form": {},..."data": "{\"payload\":{\"flags\":\"true\",
Why is in PHP the "form" empty?
I've tried it an extra Array "form", but when I look at the result there is a second "form" in the string.
You use improper way of building POST data.
Try this:
$payload = array(
'flags' => true,
'codes' => true,
'units' => true
);
$data = array(
'payload' => json_encode($payload)
);
$options = array(
"http" => array(
"method" => "POST",
"header" => "Content-Type: application/x-www-form-urlencoded\r\n",
"content" => http_build_query($data)
)
);
Explanation
In your JS code POST data is an object containing one key-value pair {"payload": json} where json is json-encoded string representing payload object. This POST data object finally results (in $.ajax implementation) in a url-encoded string which look like this: payload=%7B%22flags%22%3Atrue%2C%22codes%22%3Atrue%2C%22units%22%3Atrue%7D.
Described process is exactly reproduced by my php code.
Have you tried to trigger json_last_error() right after encoding your array ?
$options = array(
"http" => array(
"method" => "POST",
"header" => "Content-Type: application/json\r\n",
"content" => json_encode($data)
)
);
$error = json_last_error();
echo $error;
In case of a silent json error, maybe it could give you a clue.
Let us know :)

Categories