Tuesday 9 September 2014

Calling a REST Web service method through URL

Instead of using the soapclient library from PHP, a  REST (Representational State Transfer) webservice can be consumed by passing method and parameters directly through  the URL.
Here below, a function "Acces_REST_WS" has been defined to get the response of a web service (through the example of Chronopost webservice giving the information of a relay point from a relay idendifier)  giving the URL of  the webservice along with the applied method and parameters  :

<?php
    $sUrl ="https://www.chronopost.fr/recherchebt-ws-cxf/PointRelaisServiceWS/rechercheDetailPointChronopostInter?";
 
   $parameters = http_build_query(array(
'accountNumber' => 'XXXXXX',
'password' => 'XXXXXX',
'identifiant' => '2711R',
'countryCode' => 'FR',
'language' => 'FR'
), '&');

    $reponse = Acces_Rest_WS($sUrl,$parameters);

    function Acces_Rest_WS($sUrl, $parameters)
    {
        $aErrors = array();
        $bError = false;
     
        $url =$sUrl.$parameters;
     
        $result = URLToXml($url);
     
        // transformer le fichier XML en tableau
        $listePointRelais = json_decode(XmlToJson($result), true);

        //tester les codes erreurs
        $errorCode = $listePointRelais['soapBody']['ns1rechercheDetailPointChronopostInterResponse']['return']['errorCode'];

        if ($errorCode != '0')
        {
            // en cas d'erreur, rechercher le message d'erreur
            $bError = true;
            $errormessage = $listePointRelais['soapBody']['ns1rechercheDetailPointChronopostInterResponse']['return']['errorMessage'];
            $aErrors[] = $errorCode." : ".$errormessage ;
        }

        // absence d'erreur
        if (false === $bError)
        {
            $listePointRelais = $listePointRelais['soapBody'] ['ns1rechercheDetailPointChronopostInterResponse']['return']['listePointRelais'];
            $listePointRelais = isset($listePointRelais) ? $listePointRelais : array();
            if (!isset($listePointRelais[0]))
            {
                $listePointRelais = array(
                    0 => $listePointRelais
                );
            }
            $relays = array();

            foreach ($listePointRelais as $PointRelais)
            {
                if (!isset($PointRelais['identifiant']))
                {
                    continue;
                }
                $relay = array(
                    'label' => $PointRelais['nom'],
                    'code' => $PointRelais['identifiant'],
                    'id' => $PointRelais['identifiant'],
                    'address_line1' => $PointRelais['adresse1'],
                    'address_postal_code' => $PointRelais['codePostal'],
                    'address_city' => $PointRelais['localite'],
                    'relay_type' => 'ChronoRelais',
                    'lat' => isset($PointRelais['coordGeolocalisationLatitude']) ? $PointRelais['coordGeolocalisationLatitude'] : null,
                    'lng' => isset($PointRelais['coordGeolocalisationLongitude']) ? $PointRelais['coordGeolocalisationLongitude'] : null,
                    'country_code' => $PointRelais['codePays'],
                    'hours' => array()
                );

                $jours = array (0 =>'sun',1=>'mon',2=>'tue',3 =>'wed',4=>'thu',5=>'fri',6=>'sat');

                foreach ($PointRelais['listeHoraireOuverture'] as $day)
                {
                    $jour= $jours[$day['jour']];

                    if (isset($day['listeHoraireOuverture']))
                    {
                        $relay['hours'][$jour] = array(
                            'am' => isset($day['listeHoraireOuverture'][0]) ? array(
                                $day['listeHoraireOuverture'][0]['debut'],
                                $day['listeHoraireOuverture'][0]['fin']
                            ) : null,
                            'pm' => isset($day['listeHoraireOuverture'][1]) ? array(
                                $day['listeHoraireOuverture'][1]['debut'],
                                $day['listeHoraireOuverture'][1]['fin']
                            ) : null
                        );
                    }
                    else
                    {
                        $relay['hours'][$jour] = null;
                    }
                }
            }
        }

      return   array(
            'request' => array(
                'url' => $sUrl,
                'options' => array(),
                'parameters' => $parameters
            ),
            'response' => $relay,
            'errors' => $aErrors
        );
    }
    function XmlToJson($fileContents)
    {
        $fileContents = str_replace(array(
            "\n",
            "\r",
            "\t"
        ), '', $fileContents);
        $fileContents = trim(str_replace('"', "'", $fileContents));
        $fileContents = preg_replace("/(<\/?)(\w+):([^>]*>)/", "$1$2$3", $fileContents);
        $fileContents = preg_replace('/xmlns[^=]*="[^"]*"/i', '', $fileContents);
        $fileContents = preg_replace('/[a-zA-Z]+:([a-zA-Z]+[=>])/', '$1', $fileContents);
        $simpleXml = @simplexml_load_string($fileContents);
     
        //$tab = (array) $simpleXml;
     
        $json = json_encode($simpleXml);
        return $json;
    }
 
    function URLToXml($url)
    {
       // create curl resource
        $curl = curl_init($url);

        curl_setopt($curl, CURLOPT_FAILONERROR, true);
        curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
        $result = curl_exec($curl);
     
        //close curl resource to free up system resources
        curl_close($curl);  
        return $result;
    }
?>