How to notify the tracking of the post office to the user?

Asked

Viewed 2,364 times

4

I own a eCommerce which are part of Post office, except the tracking system which only includes the tracking code in the order. I need every change in status to notify the customer via email.

With the code below, I can make a query to the Post Office and can check the return of STATUS.

$error = array();

$url = 'http://websro.correios.com.br/sro_bin/txect01$.QueryList';
$url .= '?P_LINGUA=001&P_TIPO=001&P_COD_UNI=' . $code;
try {
    $client = new Zend_Http_Client();
    $client->setUri($url);
    $content = $client->request();
    $body = $content->getBody();

} catch (Exception $e) {
    $error[] = $e;
    return false;
}

However, this way I should be doing the check periodically (12h, 24h) and consulting each code. Is there any way to be receiving just the return of the codes that there was indeed change, and have only one Observer treating them? Or the only way will be with a script of mine, configured to CRON, be consulting the code and making the proper return manipulation?

  • 2

    I already did this by converting the track’s HTML to hash, and inserting it into db for comparison, if the hash changes, I send the new status via email and save again the HMTL hash, and the scheduling in cron every 4h

  • In your case there was some problem with that?

  • 2

    Not until today, but I only read what’s inside the tag table! Ex.: preg_match( '/<table border cellpadding=1 hspace=10>.*</TABLE>/s', $this->html, $this->table ), And runs until today, but you can save the data if you want too, and do check routine for the last occurrence date. If the date is longer than this in the database, do the Insert or update, and send again.

  • @Joker can respond with his hint?

  • I’ll post a basic example, but in OPP, and you adapt to your code!!

1 answer

6


I did the basic example for you to understand the logic, of two forms, Track do HTML and of Objetos in array for database storage, and hash for DB comparison!

<?php

class Tracking {

    public $track;
    public $table;
    public $erro = false;
    public $erroMsg = false;    

    /**
    * Construtor
    *
    * @param string $track Código da encomenda
    * return void
    */
    public function setTrack($track=false){

        if ( strlen($track) !== 13) {
            $this->erro = true;
            $this->erroMsg = 'Código de encomenda Inválido!';
        }
        $this->track = $track;

    }

    public function trackHTML()
    {
        if( $this->erro === true ):
            return $this->erro;
        else:

            $url = 'http://websro.correios.com.br/sro_bin/txect01$.QueryList?P_LINGUA=001&P_TIPO=001&P_COD_UNI=' . $this->track;
            $html = utf8_encode( file_get_contents( $url ) );

            if (strpos($html, "src=../correios/") !==false) {
                $html  = str_replace('src=../correios/',
                    'src=http://websro.correios.com.br/correios/', $html );
            }

            preg_match( '/<table  border cellpadding=1 hspace=10>.*<\/TABLE>/s', $html, $table );

            // hash para monitoramento de alteração de status
            $this->hash = md5($html);           

            return ( count( $table ) == 1 ) ? $table[0] : "Objeto não encontrado";

        endif;
    }


    public function trackObject(){

        $html = utf8_encode( file_get_contents('http://websro.correios.com.br/sro_bin/txect01$.QueryList?P_LINGUA=001&P_TIPO=001&P_COD_UNI=' . $this->track ));

        // Verifica se o objeto ainda não foi postado, caso seja o caso, retorna erro e mensagem
        if (strstr($html, '<table') === false){
            $this->erro = true;
            $this->erroMsg = 'Objeto ainda não foi adicionado no sistema';
            return;
        }

        // hash para monitoramento de alteração de status
        $this->hash = md5($html);

        // Limpa o codigo html
        $html = preg_replace("@\r|\t|\n| +@", ' ', $html);
        $html = str_replace('</tr>', "</tr>\n", $html);

        // Pega as linhas com o rastreamento
        if (preg_match_all('@<tr>(.*)</tr>@', $html, $mat,PREG_SET_ORDER)){
            $track = array();
            $mat = array_reverse($mat);
            $temp = null;
            // Formata as linhas e gera um vetor
            foreach($mat as $item){
                if (preg_match("@<td rowspan=[12]>(.*)</td><td>(.*)</td><td><FONT COLOR=\"[0-9A-F]{6}\">(.*)</font></td>@", $item[0], $d)){
                    // Cria uma linha de track
                    $tmp = array(
                        'date' => $d[1],
                        'DateSql' => preg_replace('@([0-9]{2})/([0-9]{2})/([0-9]{4}) ([0-9]{2}):([0-9]{2})@', '$3-$2-$1 $4:$5:00',$d[1] ),
                        'local' => $d[2],
                        'action' => strtolower($d[3]),
                        'details' => ''
                    );

                    // Se tiver um encaminhamento armazenado
                    if ($temp){
                        $tmp['details'] = $temp;
                        $temp = null;
                    }

                    // Adiciona o item na lista de rastreamento
                    $track[] = (object)$tmp;
                }else if (preg_match("@<td colspan=2>(.*)</td>@", $item[0], $d)){
                    // Se for um encaminhamento, armazena para o proximo item
                    $temp = $d[1];
                }
                $this->status = $tmp['action'];
            }
            $this->track = $track;
            return $this->track;
        }

        // Caso retorne um html desconhecido ou falhe, retorna erro de comunicação
        $this->erro = true;
        $this->erroMsg = 'Falha de Comunicação com os correios';

    }   

}

Instantiating the class

$track = new Tracking();
$track->setTrack('PI205094504BR');

if($track->erro !== true){

    echo $track->trackHTML();

    echo '<br />';
    echo 'Hash para monitoramento de alteração de status: ';
    echo $track->hash;

} else {
    echo $track->erroMsg;
}

In this Example the result is this: inserir a descrição da imagem aqui

In the second example, returns the data in array

if($track->erro !== true){

    echo '<pre>';
    print_r( $track->trackObject() );
    echo '</pre>';

    echo '<br />';
    echo 'Hash para monitoramento de alteração de status: ';
    echo $track->hash;

} else {
    echo $track->erroMsg;
}

Exit:

Array
(
    [0] => stdClass Object
        (
            [date] => 20/07/2015 14:04
            [DateSql] => 2015-07-20 14:04:00
            [local] => CTCE VITORIA/GCCAP - Viana/ES
            [action] => postado
            [details] => 
        )

    [1] => stdClass Object
        (
            [date] => 20/07/2015 22:00
            [DateSql] => 2015-07-20 22:00:00
            [local] => CTCE VITORIA/GCCAP - Viana/ES
            [action] => encaminhado
            [details] => Encaminhado para CTE BENFICA - Rio De Janeiro/RJ
        )

    [2] => stdClass Object
        (
            [date] => 21/07/2015 16:55
            [DateSql] => 2015-07-21 16:55:00
            [local] => CTE BENFICA - Rio De Janeiro/RJ
            [action] => encaminhado
            [details] => Encaminhado para CTCE CUIABA - Varzea Grande/MT
        )

    [3] => stdClass Object
        (
            [date] => 24/07/2015 15:35
            [DateSql] => 2015-07-24 15:35:00
            [local] => CTCE CUIABA - Varzea Grande/MT
            [action] => encaminhado
            [details] => Em trânsito para AC DIAMANTINO - Diamantino/MT
        )

    [4] => stdClass Object
        (
            [date] => 28/07/2015 09:48
            [DateSql] => 2015-07-28 09:48:00
            [local] => Diamantino/MT
            [action] => saiu para entrega ao destinat��rio
            [details] => 
        )

    [5] => stdClass Object
        (
            [date] => 28/07/2015 16:59
            [DateSql] => 2015-07-28 16:59:00
            [local] => AC DIAMANTINO - Diamantino/MT
            [action] => entrega efetuada
            [details] => 
        )

)

Hash para monitoramento de alteração de status: ccebc8ce6343aea4692500bae90a49d3

In this example I used file_get_contents, but I usually use cURL

  • all right? What is the possibility of me asking you for help by email, about this code.If it has cost we can negotiate. .rs.. Actually I would like a lesson to teach me how to do and understand how it was done, because I’m learning to develop in PHP. Thanks so much for your attention. Rodrigo Pais

Browser other questions tagged

You are not signed in. Login or sign up in order to post.