Table of Contents

Examples

This page is intended to provide code examples to facilitate the integration with our APIs. Here, you will find practical instructions with illustrative code snippets that will help you efficiently integrate the functionalities of our APIs into your project. Our goal is to make the integration process simpler and faster, providing you with the necessary tools for agile and seamless development.

Example - Direct API call

A complete example is shown below. The following code implements an integration flow that covers various operations, from authentication to signing a document (FT). See below for the endpoints used and their functions:

<?php
    // Turn off all error reporting
    error_reporting(0);
    /*************************************************************
    *           		   Global Variables                      *
    *************************************************************/
    $urlBase = 'XXXXXXXXXXXXXXXXXXXXXXX/phcws/';
    $usernameLogin = 'XXXXXX';
    $passwordLogin = 'XXXXXX';
    $appTypeLogin  = 'XXXXXXXXXXXXXXXXXXXXXXXXX';
    $companyLogin  = '';

    // After click "Login in PHC GO" button
    if (!empty($_POST['makeLogin'])){

        echo "<h3>You are logged in PHC GO</h3><h2>Generate Customer, Product and signed Invoice</h2>";

        /*************************************************************
         *     Called webservice to login into PHC GO               *
         *************************************************************/
        $url = $urlBase."REST/UserLoginWS/userLoginCompany";
        $params = array(
            'userCode' => $usernameLogin,
            'password' => $passwordLogin,
            'applicationType' => $appTypeLogin,
            'company' => $companyLogin
        );
        $query = http_build_query($params);
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_USERAGENT,'Mozilla/5.0 (X11; Linux x86_64)');
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $query);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_COOKIESESSION, true);
        curl_setopt($ch, CURLOPT_COOKIEJAR, '');
        curl_setopt($ch, CURLOPT_COOKIEFILE, '');
        $response = curl_exec($ch);
        $response = json_decode($response, true);
        $tokenHeader = array(
            'Authorization' => 'Engine-Auth:'.$response['result'][0]['token'],
            'Content-Type' => 'application/json'
        );

        /*************************************************************
         *  Called webservice to query invoice documents (FT, FS, FR) *
         *************************************************************/
        $url = $urlBase."REST/SearchWS/QueryAsEntities";
        $params = array('itemQuery' => '{"groupByItems":[],"lazyLoaded":false,"joinEntities":[],"orderByItems":[],"SelectItems":[],"entityName":"Td","filterItems":[{"comparison":0,"filterItem":"inactivo","valueItem":"0","groupItem":1,"checkNull":false,"skipCheckType":false,"type":"Number"}]}');
        $query = http_build_query($params);
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $tokenHeader);
        curl_setopt($ch, CURLOPT_POST, false);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
        $response = curl_exec($ch);
        $response = json_decode($response, true);
        if (!empty($response['result'])) {
            $_SESSION['typeOfInvoice'] = '';
            foreach ($response['result'] as $value) {
                if ($value['tiposaft'] == 'FT' || $value['tiposaft'] == 'FS' || $value['tiposaft'] == 'FR') {
                    $_SESSION['typeOfInvoice'] .= "<option value=" . $value['ndoc'] . ">" . $value['nmdoc'] ."</option><br>";
                }
            }
        }
        // Button for choosing the invoice type from PHC GO
        echo "<form method='post' action=''>";
        echo "Choose type of invoice document:<br><br><select id='typeOfInvoices' name='typeOfInvoices'>";
        echo "<option value='0'>Select one...</option>";
        echo $_SESSION['typeOfInvoice'];
        echo "</select>";
        echo "<br><br><br><input type='submit' name='generate_ft' value='Generate'>";
        echo "</form>";

        /*************************************************************
         *       Called webservice to logout from PHC GO            *
         *************************************************************/
        $url = $urlBase."REST/UserLoginWS/userLogout";
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_POST, false);
        $response = curl_exec($ch);

    // After click "Generate" button
    } else if (!empty($_POST['generate_ft'])){

        /*************************************************************
         *     Called webservice to login into PHC GO               *
         *************************************************************/
        $url = $urlBase."REST/UserLoginWS/userLoginCompany";
        $params = array(
            'userCode' => $usernameLogin,
            'password' => $passwordLogin,
            'applicationType' => $appTypeLogin,
            'company' => $companyLogin
        );
        $query = http_build_query($params);
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_USERAGENT,'Mozilla/5.0 (X11; Linux x86_64)');
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $query);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_COOKIESESSION, true);
        curl_setopt($ch, CURLOPT_COOKIEJAR, '');
        curl_setopt($ch, CURLOPT_COOKIEFILE, '');
        $response = curl_exec($ch);
        $response = json_decode($response, true);
        $tokenHeader = array(
            'Authorization' => 'Engine-Auth:'.$response['result'][0]['token'],
            'Content-Type' => 'application/json'
        );

        /*************************************************************
         *  Called webservice to check if the client exists         *
         *************************************************************/
        $url = $urlBase."REST/SearchWS/QueryAsEntities";
        $params = array('itemQuery' => '{"groupByItems":[],"lazyLoaded":false,"joinEntities":[],"orderByItems":[],"SelectItems":[],"entityName":"Cl","filterItems":[{"comparison":0,"filterItem":"ncont","valueItem":"235047660","groupItem":1,"checkNull":false,"skipCheckType":false,"type":"Number"}]}');
        $query = http_build_query($params);
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $tokenHeader);
        curl_setopt($ch, CURLOPT_POST, false);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
        $response = curl_exec($ch);
        $response = json_decode($response, true);
        if (is_array($response['result']) && !empty($response['result'][0])) {
            $_SESSION['number_client'] = $response['result'][0]['no'];
            echo "<h3>Client nº" . $response['result'][0]['no'] . " already exists in PHC GO</h3>";
        } else {
            /*************************************************************
             *  Called webservice to get a new instance of the client   *
             *************************************************************/
            $url = $urlBase."REST/ClWS/getNewInstance";
            $params = array('ndos' => 0);
            $query = http_build_query($params);
            curl_setopt($ch, CURLOPT_URL, $url);
            curl_setopt($ch, CURLOPT_HTTPHEADER, $tokenHeader);
            curl_setopt($ch, CURLOPT_POST, false);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
            $response = curl_exec($ch);
            $response = json_decode($response, true);
            if (!empty($response['result'])) {
                /*************************************************************
                 *  Data for creating a new customer                      *
                 *************************************************************/
                $response['result'][0]['nome']   = 'Customer Test wxy';
                $response['result'][0]['morada'] = 'Lagoas Park';
                $response['result'][0]['local']  = 'Lisboa';
                $response['result'][0]['codpost']= '1234-123';
                $response['result'][0]['email']  = 'customer3@phc.pt';
                $response['result'][0]['ncont']  = '212187449';

                /*************************************************************
                 *  Called webservice to save the client                  *
                 *************************************************************/
                $url = $urlBase."REST/ClWS/Save";
                $params = array(
                    'itemVO' => json_encode($response['result'][0]),
                    'runWarningRules' => 'false'
                );
                $query = http_build_query($params);
                curl_setopt($ch, CURLOPT_URL, $url);
                curl_setopt($ch, CURLOPT_HTTPHEADER, $tokenHeader);
                curl_setopt($ch, CURLOPT_POST, false);
                curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
                $response = curl_exec($ch);
                $response = json_decode($response, true);
                if (!empty($response['result'])) {
                    echo "<h3>Client nº" . $response['result'][0]['no'] . " is inserted in PHC GO</h3>";
                    $_SESSION['number_client'] = $response['result'][0]['no'];
                }
            }
        }

        /*************************************************************
         *  Called webservice to check if the product exists        *
         *************************************************************/
        $url = $urlBase."REST/SearchWS/QueryAsEntities";
        $params = array('itemQuery' => '{"groupByItems":[],"lazyLoaded":false,"joinEntities":[],"orderByItems":[],"SelectItems":[],"entityName":"St","filterItems":[{"comparison":0,"filterItem":"ref","valueItem":"REF_1","groupItem":1,"checkNull":false,"skipCheckType":false,"type":"Number"}]}');
        $query = http_build_query($params);
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $tokenHeader);
        curl_setopt($ch, CURLOPT_POST, false);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
        $response = curl_exec($ch);
        $response = json_decode($response, true);
        if (is_array($response['result']) && !empty($response['result'][0])) {
            $_SESSION['ref_product'] = $response['result'][0]['ref'];
            echo "<h3>Ref: " . $response['result'][0]['ref'] . " already exists in PHC GO</h3>";
        } else {
            /*************************************************************
             *  Called webservice to get a new instance of the product  *
             *************************************************************/
            $url = $urlBase."REST/StWS/getNewInstance";
            $params = array('ndos' => 0);
            $query = http_build_query($params);
            curl_setopt($ch, CURLOPT_URL, $url);
            curl_setopt($ch, CURLOPT_HTTPHEADER, $tokenHeader);
            curl_setopt($ch, CURLOPT_POST, false);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
            $response = curl_exec($ch);
            $response = json_decode($response, true);
            if (!empty($response['result'])) {
                /*************************************************************
                 *  Add new product details                                *
                 *************************************************************/
                $response['result'][0]['ref']     = 'REF_1';
                $response['result'][0]['design']  = 'Test Product W';
                $response['result'][0]['epv1']    = '9.99';
                $response['result'][0]['iva1incl'] = true;
                $response['result'][0]['inactivo'] = false;
                /*************************************************************
                 *  Called webservice to save the product                 *
                 *************************************************************/
                $url = $urlBase."REST/StWS/Save";
                $params = array(
                    'itemVO' => json_encode($response['result'][0]),
                    'runWarningRules' => 'false'
                );
                $query = http_build_query($params);
                curl_setopt($ch, CURLOPT_URL, $url);
                curl_setopt($ch, CURLOPT_HTTPHEADER, $tokenHeader);
                curl_setopt($ch, CURLOPT_POST, false);
                curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
                $response = curl_exec($ch);
                $response = json_decode($response, true);
                if (!empty($response['result'])) {
                    echo "<h3>Ref: " . $response['result'][0]['ref'] . " is inserted in PHC GO</h3>";
                    $_SESSION['ref_product'] = $response['result'][0]['ref'];
                }
            }
        }

        // Save option chosen in select box for invoice type
        $_SESSION['typeOfInvoices'] = $_POST['typeOfInvoices'];

        /*************************************************************
         *  Called webservice to get a new instance of FT (Invoice)   *
         *************************************************************/
        $url = $urlBase."REST/FtWS/getNewInstance";
        $params = array('ndos' => $_SESSION['typeOfInvoices']);
        $query = http_build_query($params);
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $tokenHeader);
        curl_setopt($ch, CURLOPT_POST, false);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
        $response = curl_exec($ch);
        $response = json_decode($response, true);
        if (!empty($response['result'])) {

            /*************************************************************
             *  Add new line to the invoice document                   *
             *************************************************************/
            $newLine = '{ "actqtt2": false,
            "amostra": false,
            "armazem": 0,
            "articleAutoCreationCode": 0,
            "avencano": 0,
            "avencastamp": "",
            "bistamp": "",
            "ccstamp": "",
            "cliref": "",
            "codigo": "",
            "codmotiseimp": "",
            "componente": false,
            "compound": false,
            "cpoc": 0,
            "davencaft": "1900-01-01 00:00:00Z",
            "desc2": 0,
            "desc3": 0,
            "desc4": 0,
            "desc5": 0,
            "desc6": 0,
            "desconto": 0,
            "design": "Caixa e tamboril",
            "ecusto": 0,
            "elucro": 0,
            "emargem": 0,
            "epv": 14.99,
            "etiliquido": 14.99,
            "ettiva": 0,
            "evalcomissao": 0,
            "facturaFt": false,
            "familia": "",
            "fechabo": false,
            "firefs": [],
            "fistamp": "",
            "ftstamp": "d08-4a6a-a07f-b6eed883678",
            "iva": 23,
            "ivadata": "1900-01-01 00:00:00Z",
            "ivaincl": true,
            "ivarec": 0,
            "litem": "",
            "litem2": "",
            "lordem": 0,
            "lrecno": "",
            "maxQttRefund": 0,
            "miseimpstamp": "",
            "motiseimp": "",
            "nvol": 0,
            "ofistamp": "",
            "ofnstamp": "",
            "oftstamp": "",
            "oref": "",
            "originalMaxQttRefund": 0,
            "pbuni": 0,
            "pluni": 0,
            "pvmoeda": 0,
            "qtt": 1,
            "rdata": "1900-01-01 00:00:00Z",
            "rdstamp": "",
            "ref": "C001",
            "stns": false,
            "sujirs": false,
            "tabiva": 0,
            "tmoeda": 0,
            "tnvol": 0,
            "tpbrut": 0,
            "tpliq": 0,
            "treestamp": "",
            "tvol": 0,
            "unidade": "",
            "usr1": "",
            "usr2": "",
            "vuni": 0 }';

            // Add the new line to the invoice (FT) data
            $response['result'][0]['fis'][0] = json_decode($newLine);

            // Update the invoice using actEntity
            $urlFt = $urlBase."REST/FtWS/actEntity";
            $paramsFt = array(
                'entity' => json_encode($response['result'][0]),
                'code' => 0,
                'newValue' => json_encode([])
            );
            $queryFt = http_build_query($paramsFt);
            curl_setopt($ch, CURLOPT_URL, $urlFt);
            curl_setopt($ch, CURLOPT_HTTPHEADER, $tokenHeader);
            curl_setopt($ch, CURLOPT_POST, false);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $queryFt);
            $response = curl_exec($ch);
            $response = json_decode($response, true);

            if (!empty($response)) {
                // Associate the client with the invoice
                $response['result'][0]['no'] = $_SESSION['number_client'];
                // Eliminate financial discount of client
                $response['result'][0]['efinv'] = 0;
                $response['result'][0]['fin'] = 0;

                /*************************************************************
                 *  Update invoice again using actEntity (if needed)      *
                 *************************************************************/
                $urlFt = $urlBase."REST/FtWS/actEntity";
                $paramsFt = array(
                    'entity' => json_encode($response['result'][0]),
                    'code' => 0,
                    'newValue' => json_encode([])
                );
                $queryFt = http_build_query($paramsFt);
                curl_setopt($ch, CURLOPT_URL, $urlFt);
                curl_setopt($ch, CURLOPT_HTTPHEADER, $tokenHeader);
                curl_setopt($ch, CURLOPT_POST, false);
                curl_setopt($ch, CURLOPT_POSTFIELDS, $queryFt);
                $response = curl_exec($ch);
                $response = json_decode($response, true);

                if (!empty($response)) {
                    /*************************************************************
                     *  Called webservice to save the invoice (FT)           *
                     *************************************************************/
                    $url = $urlBase."REST/FtWS/Save";
                    $params = array(
                        'itemVO' => json_encode($response['result'][0]),
                        'runWarningRules' => 'false'
                    );
                    $query = http_build_query($params);
                    curl_setopt($ch, CURLOPT_URL, $url);
                    curl_setopt($ch, CURLOPT_HTTPHEADER, $tokenHeader);
                    curl_setopt($ch, CURLOPT_POST, false);
                    curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
                    $response = curl_exec($ch);
                    $response = json_decode($response, true);

                    if (!empty($response['result'])) {
                        // If the invoice is still a draft, sign the document
                        if ($response['result'][0]['draftRecord'] == 1) {
                            $_SESSION['ftstamp'] = $response['result'][0]['ftstamp'];
                            /*************************************************************
                             *  Called webservice to sign the invoice document         *
                             *************************************************************/
                            $url = $urlBase."REST/FtWS/signDocument";
                            $params = array('ftstamp' => $response['result'][0]['ftstamp']);
                            $query = http_build_query($params);
                            curl_setopt($ch, CURLOPT_URL, $url);
                            curl_setopt($ch, CURLOPT_HTTPHEADER, $tokenHeader);
                            curl_setopt($ch, CURLOPT_POST, false);
                            curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
                            $response = curl_exec($ch);
                            $response = json_decode($response, true);
                            if (!empty($response['result'])) {
                                echo "<h3>" . $response['result'][0]['nmdoc'] . " nº <u>" . $response['result'][0]['fno'] . "</u> is signed and inserted in PHC GO</h3>";
                            }
                        }
                    }
                }
            }
        }

        /*************************************************************
         *       Called webservice to logout from PHC GO            *
         *************************************************************/
        $url = $urlBase."REST/UserLoginWS/userLogout";
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_POST, false);
        $response = curl_exec($ch);

    } else {
        echo "<h1>Conect to PHC GO</h1>";
        echo "<form method='post' action=''>";
        echo "<input type='submit' name='makeLogin' value='Login in PHC GO'>";
        echo "</form>";
    }
?>