« Atrás

Making remote API calls to Liferay's JSON services from PHP

Company Blogs 12 de febrero de 2008 Por Ray Augé Staff

Liferay offers a wide variety of different remote API's.

A very useful one is JSON. It's useful because most languages have JSON processing functions. So the only dependencies are those and HTTP request handling functions.

Here is a complete example of adding a Country from a PHP script:

<?php

#
# This example uses HTTP_Request package located found here:
#
#     http://pear.php.net/package/HTTP_Request
#
# Tested with:
#     Liferay Portal - revision 13652
#     HTTP_Request - version 1.4.1
#
require_once("HTTP/Request.php");

#
# URL to the tunnle-web JSON API.
#
$a = &new HTTP_Request('http://localhost:8080/tunnel-web/secure/json');

#
# Use POST in 99% of cases, so that encoding of passed data is handled properly.
#
$a->setMethod("POST");

#
# Specify the authentication credientials.
#
$a->setBasicAuth("2","test");

#
# Specify the service class.
#
$a->addPostData(
"serviceClassName", "com.liferay.portal.service.http.CountryServiceJSON");

#
# Specify the service method.
#
$a->addPostData("serviceMethodName", "addCountry");

#
# List the method parameters.
#
$a->addPostData("serviceParameters", "name,a2,a3,number,idd,active");

#
# Give the values to use in the method.
#
$a->addPostData("name",   "AAAAAA");
$a->addPostData("a2",     "AA");
$a->addPostData("a3",     "AA");
$a->addPostData("number", "1000000");
$a->addPostData("idd",    "1000000");
$a->addPostData("active", "true");

#
# Send the request.
#
$a->sendRequest();

echo $a->getResponseBody();

#
# If the country does not exist, this will print:
#
#   {"active":true,"a2":"AA","a3":"AA","idd":"1000000","countryId":10904,"name":"AAAAAA","number":"1000000"}
#
#
# The above indicates success. Notice that "countryId" is included in the result.
#
?>

Respuestas anidadas Autor Fecha
Very Nice, thanks for sharing this Ray. This... Jorge Ferrer 13 de febrero de 2008 12:51
Just what I was looking for! Thanks soooo much! Alex Wallace 24 de abril de 2008 13:31
Here is an updated example that will work with... Dave Morris 16 de septiembre de 2009 22:19
Hi Dave! i tried your script and it works like... Dani Danielo 17 de diciembre de 2010 7:24
Hmm, I'm not a PHP expert and I can't really... Ray Augé 17 de diciembre de 2010 9:43
Hi, everyone. Could anyone tell me how can I... Anton Murauyou 11 de junio de 2010 2:34
Hi, everyone. I'm a newbie in liferay & I... Gembong Y. Pranolo 4 de julio de 2010 19:44
euh, sorry.. Whether this script can be used to... Gembong Y. Pranolo 4 de julio de 2010 20:05
[...] Hamish Campbell: BUMP - we are still... Anónimo 9 de junio de 2011 13:44
[...] Rami Grossman: Hi, I'm also a newbie. The... Anónimo 27 de octubre de 2011 0:15
[...] The past couple of years I’ve seen many... Anónimo 12 de abril de 2012 0:26
[...]... Anónimo 3 de septiembre de 2012 6:18

Very Nice, thanks for sharing this Ray. This post definitely deserves a 5 star
Publicado el día 13/02/08 12:51.
Just what I was looking for!

Thanks soooo much!
Publicado el día 24/04/08 13:31.
Here is an updated example that will work with Liferay 5.2.3

This example uses the Zend API just because it was what I had available at the time, but the concept applies to any Http client API in PHP or any other language for that matter. The main thing to notice here is that the serviceClassName is different, because ServiceBuilder no longer generates the *ServiceJSON.java files.

Also, make sure you add this line to your portal-ext.properties file to allow the json servlet to be accessible from some IP address or hostname:

json.servlet.hosts.allowed=localhost,127.0.0.1

 1
 2<?php
 3require_once ('Zend/Http/Client.php');
 4require_once ('Zend/Json.php');
 5
 6$liferay = new Zend_Http_Client();
 7
 8$liferay->setUri('http://localhost:8080/tunnel-web/secure­/json');
 9
10// set parameters to return a list of countries from the Liferay db
11$liferay->setParameterGet(array(
12    'serviceClassName' => 'com.liferay.portal.service.CountryServiceUtil',
13    'serviceMethodName' => 'getCountries'
14));
15
16// set authentication
17$liferay->setAuth('userid', 'password');
18
19// send the request
20$result = $liferay->request("GET");
21
22// get back a json response
23$json = Zend_Json::decode($result->getBody());
24
25// print the json object
26echo $result->getBody();
27
28?>


And if you're having trouble getting it to work, check out SecureFilter.java, JSONServiceAction.java, and JSONServlet.java to figure out what's going on.
Publicado el día 16/09/09 22:19.
Hi, everyone.

Could anyone tell me how can I access other services ( not only in com.liferay.portal.service.spring package as in example? How can I get an article through JSON (for example with com.liferay.portlet.journal.service.spring.JournalArticleServiceUtil?

Should I use ServiceBuilder to make this available through JSON?

Thanks
Publicado el día 11/06/10 2:34.
Hi, everyone.

I'm a newbie in liferay & I wonder, is there any way to get liferay's session from php ?? please help, need it.

Thanks before,
Bonks
Publicado el día 4/07/10 19:44.
euh, sorry..
Whether this script can be used to retrieve user data using input parameters ?

Thanks,
Bonks
Publicado el día 4/07/10 20:05 en respuesta a Gembong Y. Pranolo.
Hi Dave!
i tried your script and it works like a charm, but now i am trying to use the addUser method and dymply don't work.

here it is my script:

<?php
require_once ('Zend/Http/Client.php');
require_once ('Zend/Json.php');

$liferay = new Zend_Http_Client();

$liferay->setUri('http://localhost:8080/tunnel-web/secure/json');
// set parameters to return a list of countries from the Liferay db
$liferay->setParameterPost(array(
'serviceClassName' => 'com.liferay.portal.service.UserServiceUtil',
'serviceMethodName' => 'addUser',
'serviceParameters' => 'companyId, autoPassword, password1, password2,

screenName, emailAddress, firstName, lastName',
//'setFirstName' => 'Pacoooo',
'companyId' => 10112,
'autoPassword' => true,
'password1' => 'pass1',
'password2' => 'pass2',
'screenName' => 'john',
'emailAddress' => 'blah@localhost',
'firstName' => 'John',
'lastName' => 'Doe'


/*
$liferay->setParameterPost(array(
'serviceClassName' => 'com.liferay.portal.service.CountryServiceUtil',
'serviceMethodName' => 'getCountries'
*/
));

// set authentication
$liferay->setAuth('10115', 'password');
$result = $liferay->request("POST");

// get back a json response
$json = Zend_Json::decode($result->getBody());

// print the json object
var_dump($json);
?>
Publicado el día 17/12/10 7:24 en respuesta a Dave Morris.
Hmm, I'm not a PHP expert and I can't really see what the problem is. Typically I debug these by using the js console in a Firefox browser first. Then when I know the call works, then I re-code it using the specific language.

You could try that (make sure that the /html/js/liferay/service.js is loaded on the page of course and that you are logged into the portal). The calls will look something like:

console.log(Liferay.Service.Portal.Country.getCountries());

In later versions we switched to async design, so it became:

Liferay.Service.Portal.Country.getCountries({}, function(result) {console.log(result)});

Note that only methods that are found in the non-Local version of the services can be called. The Local ones are not exposed.
Publicado el día 17/12/10 9:43 en respuesta a Dani Danielo.
[...] Hamish Campbell: BUMP - we are still struggling with this. Try http://127.0.0.1:8080/tunnel-web/axis or http://test:test@127.0.0.1:8080/tunnel-web/secure/axis For testing that should work. For... [...] Read More
Publicado el día 9/06/11 13:44.
[...] Rami Grossman: Hi, I'm also a newbie. The link doesn't work. Does anyone know of a working wiki on this subject? Thanks! For future references:... [...] Read More
Publicado el día 27/10/11 0:15.
[...] The past couple of years I’ve seen many examples of using Liferay’s built-in JSON services in various ways.  The architecture and syntax of this feature has undergone several refinements in the past... [...] Read More
Publicado el día 12/04/12 0:26.
[...] ============================================= - Release date: August 3rd, 2012 - Discovered by: Danilo Massa & Enrico Cinquini - Severity: High ============================================= I.... [...] Read More
Publicado el día 3/09/12 6:18.