deivisonarthur / OSC-Magento-Brasil-6-Pro

One Step Checkout Brasil 6 Pro
75 stars 103 forks source link

Magento CE 1.9.2.2 + OSC6 + Oitoo = Problema com CEP #177

Closed GustavoSartori closed 8 years ago

GustavoSartori commented 8 years ago

Boa tarde pessoal, tudo bem? Tenho uma loja rodando em CE 1.8.1.1 e estou migranda para GoDaddy. Resolvi fazer upgrade e agora estou ajustando tudo para migrar o dns depois de tudo pronto, mas agora, num ambiente com CE 1.9.2.2 (na raiz) o OSC não consegue mais pegar o endereço pelo CEP.

Se eu desabilito o jQuery do módulo o erro abaixo aparece no console depois de alguns minutos com o loading:

GET http://espelhomontessoriano.com.br/onestepcheckout/ajax/busca_cep?cep=91040040&_=1449520217096 500 (Internal Server Error)send @ jquery-1.7.2.min.js:4f.extend.ajax @ jquery-1.7.2.min.js:4f.(anonymous function) @ jquery-1.7.2.min.js:4f.extend.getScript @ jquery-1.7.2.min.js:4buscaCep @ validation.js:186onblur @ (index):2031

Mas se eu habilito, ele acusa um erro de js de outro módulo, que teoricamente não deveria estar carregado nesta tela.

Uncaught TypeError: $(...).uniform is not a function(anonymous function) @ (index):916o @ jquery-1.7.2.min.js:2p.fireWith @ jquery-1.7.2.min.js:2e.extend.ready @ jquery-1.7.2.min.js:2c.addEventListener.B @ jquery-1.7.2.min.js:2 prototype.js:1530 XHR finished loading: GET "http://espelhomontessoriano.com.br//frontendcielo/ajax/getGrandTotal/".Ajax.Request.Class.create.request @ prototype.js:1530Ajax.Request.Class.create.initialize @ prototype.js:1495(anonymous function) @ prototype.js:429klass @ prototype.js:101(anonymous function) @ (index):2674

rafaelstz commented 8 years ago

Verifica se o template também está com uma versão jQuery e a versão. Tenta atualizar o OSC 6 para a última versão também.

GustavoSartori commented 8 years ago

Oi @rafaelstz Obrigado pelo retorno! Já baixei e instalei a última versão, mas nada...

Aqui a relação dos jquerys carregados no header do template: Do tema jquery-1.7.2.min.js Do módulo camera slider (vem com o tema) jquery.easing.1.3.js jquery.mobile.customized.min.js osc jquery.min.js

rafaelstz commented 8 years ago

Mesmo fazendo requisição REST cai em 500, então é independente do jQuery. image

Deveria retornar como esse http://casadois-server4you.wjcommerce.com.br/checkoutsimplificado/index/cep/numero/05586001

JuanxCursed commented 8 years ago

@rafaelstz Estava com o mesmo problema aqui! Se resolveu sozinho... estava desde as 10 da manha tentando... Aparentemente a requisição não estava chegando nos Webservices do Correios, e consequentemente, não havia resposta retornando erro 500, o que é mais estranho ainda.

GustavoSartori commented 8 years ago

@juanmonstra aqui o problema já tem uma semana... quem dera um gnomo viesse aqui arrumar pra mim hehehe. @rafaelstz o que tu acha que pode ser, se não é jQuery? Achei que o problema tinha alguma relação com oitoo, mas não vi nada que pudesse causar o conflito...

rafaelstz commented 8 years ago

@GustavoSartori @juanmonstra Troca de http://cep.correiocontrol.com.br/ para http://cep.republicavirtual.com.br/web_cep.php o webservice. Foi oque eu fiz no meu checkout, esse Webservice é mais estável.

GustavoSartori commented 8 years ago

Obrigado pela dica @rafaelstz, mas onde altero isto? Dei uma revirada aqui e não encontrei.

rafaelstz commented 8 years ago

Mudou desde quando parei de usar, mas é aqui nesse arquivo.

GustavoSartori commented 8 years ago

Feito! Troquei de $clientSoap = new SoapClient("https://apps.correios.com.br/SigepMasterJPA/AtendeClienteService/AtendeCliente?wsdl" );

para

$clientSoap = new SoapClient("http://cep.republicavirtual.com.br/web_cep.php" );

Agora, de fato, ele não trava mais, mas em compensação mostra o erro: Endereço não encontrado para este CEP. O mesmo acontece com CEP de SP, RS ou RJ, etc...

rafaelstz commented 8 years ago

Agora tem que tratar os dados recebidos, por que desse webservice você vai receber em JSON.

GustavoSartori commented 8 years ago

Puts... Conhece algum tutorial pra isso? Apesar de me meter bastante em desenv, derivados de js não são minha praia.

rafaelstz commented 8 years ago

Cara estou completamente sem tempo, caso contrário até faria em meu blog. Não conheço nenhum. Boa sorte! :+1:

rafaelstz commented 8 years ago

@GustavoSartori A minha url que você pode checar é:

http://casadois-server4you.wjcommerce.com.br/checkoutsimplificado/index/cep/numero/05586001

Meu JS ajax padrão é mais ou menos assim:

   ajax = new Ajax.Request(url, {
            method : 'get',
            asynchronous: false,
            onSuccess: function(transport){
                obj = transport.responseJSON;
                resultado = obj.result;
                tipo = obj.value;
                txt = obj.txt;

                console.log(obj);

            },
            onComplete: function () {

            }
        });

Meu Controller fica assim:

public function cepAction()
    {
        $numero = $this->getRequest()->getParam('numero');
        $numero = str_replace('-', '', $numero);

        if (preg_match('/^\d{8}$/', $numero)) {
            $CEP_URL = @file_get_contents("http://cep.republicavirtual.com.br/web_cep.php?cep=".urlencode($numero)."&formato=json");
            echo $CEP_URL;
        }
    }
GustavoSartori commented 8 years ago

@rafaelstz, tentei mas não consegui sair do lugar. Obrigado pela tentativa!! Pedi para um parceiro meu dar uma olhada... vou esperar pra ver o que dá.

Abração!!

patrickperes commented 8 years ago

Alguem conseguiu algo ?

andremerlo commented 8 years ago

@patrickperes, também estava tendo esse problema nos última dias.

Resolvi utilizando o webservice da ViaCEP, da seguinte maneira:

No arquivo app\code\community\Inovarti\Onestepcheckout\controllers\AjaxController.php , localize o método busca_cepAction e substitua isso:

try {

    $clientSoap = new SoapClient("https://apps.correios.com.br/SigepMasterJPA/AtendeClienteService/AtendeCliente?wsdl");
    $result = $clientSoap->consultaCep($soapArgs);
    $dados = $result->return;

    if (is_soap_fault($result)) {
        $return = "var resultadoCEP = { 'uf' : '', 'cidade' : '', 'bairro' : '', 'tipo_logradouro' : '', 'logradouro' : '', 'resultado' : '0', 'resultado_txt' : 'cep nao encontrado' }";
    } else {
        $return = "var resultadoCEP = { 'uf' : '" . $dados->uf . "', 'cidade' : '" . $dados->cidade . "', 'bairro' : '" . $dados->bairro . "', 'tipo_logradouro' : '', 'logradouro' : '" . $dados->end . "', 'resultado' : '1', 'resultado_txt' : 'sucesso%20-%20cep%20completo' }";
    }
} catch (SoapFault $e) {
    $return = "var resultadoCEP = { 'uf' : '', 'cidade' : '', 'bairro' : '', 'tipo_logradouro' : '', 'logradouro' : '', 'resultado' : '0', 'resultado_txt' : 'cep nao encontrado' }";
} catch (Exception $e) {
    $return = "var resultadoCEP = { 'uf' : '', 'cidade' : '', 'bairro' : '', 'tipo_logradouro' : '', 'logradouro' : '', 'resultado' : '0', 'resultado_txt' : 'cep nao encontrado' }";
}

por isso:

$urlviacep = 'https://viacep.com.br/ws/' . $cep . '/xml/';
$xml = simplexml_load_string(file_get_contents($urlviacep));

if (false == $xml || $xml->erro == 'true') {
    $return = "var resultadoCEP = { 'uf' : '', 'cidade' : '', 'bairro' : '', 'tipo_logradouro' : '', 'logradouro' : '', 'resultado' : '0', 'resultado_txt' : 'cep nao encontrado' }";
} else {
    $return = "var resultadoCEP = { 'uf' : '" . $xml->uf . "', 'cidade' : '" . $xml->localidade . "', 'bairro' : '" . $xml->bairro . "', 'tipo_logradouro' : '', 'logradouro' : '" . $xml->logradouro . "', 'resultado' : '1', 'resultado_txt' : 'sucesso%20-%20cep%20completo' }";
}

Lembrando que para utilizar file_get_contents com uma URL externa, é necessário ter o allow_url_fopen habilitado.

Caso contrário você precisará obter o conteúdo do XML pelo cURL e depois carregá-lo com o simplexml_load_string

GustavoSartori commented 8 years ago

Veeelho, funcionou! Muito obrigado @andremerlo

philspbr commented 8 years ago

Eu tive o mesmo problema, no meu caso não precisava trocar o webservice mas apenas carregar o XML do WS do meu servidor em vez do servidor dos Correios.

rtorresjunior commented 8 years ago

@philspbr como você fez isso? qual modificação deve ser feito?

juanloayte commented 8 years ago

@philspbr poderia explicar como executou essa modificação? testei e não funcionou. Obrigado

philspbr commented 8 years ago

No arquivo AjaxController.php tem a linha $clientSoap = new SoapClient("https://apps.correios.com.br/SigepMasterJPA/AtendeClienteService/AtendeCliente?wsdl" );

Nessa linha você troca o URL para o arquivo local, eu coloquei p.ex. na pasta lib/Correios/ Mage::getBaseDir('lib') . DS . 'Correios' . DS . 'sigep-ws.xml'

Abs

GustavoSartori commented 8 years ago

@juanloayte, dá uma olhada no procedimento que @andremerlo postou acima. Funcionou perfeito pra mim, sem demora ou erro!

jillesmc commented 8 years ago

Meus amigos, eu não fiz mudança nenhuma na url do webservice a ser consultado e está super rápido aqui, entretanto dentro do meu contexto eu percebi que a chamada da URI /saveAddress era efetuada com muita frequência mesmo com pequenas mudanças no endereço. Porém o cálculo de frete mesmo só acontece por meio do CEP né?

Sendo assim no arquivo address.js eu removi as instruções:

LINHA 141

Form.getElements(this.container).each(function(element){
            var elementId = element.getAttribute('id');
            if (element === me.useBillingAsShippingCheckbox) {
                return;
            }
            if (me.billing.addressChangeTriggerElementsIds.indexOf(elementId) !== -1) {
                return;
            }
            if (me.shipping.addressChangeTriggerElementsIds.indexOf(elementId) !== -1) {
                return;
            }
            element.observe('change', me.requestToValuesSave.bind(me));
        });

LINHA 157

requestToValuesSave: function(e) {
        new Ajax.Request(this.saveAddressUrl, {
            method: 'post',
            parameters: Form.serialize(this.container, true)
        });
    },

E como eu não utilizo os blocos de comentários e newsletter diretamente no checkout eu também removi a declaração prototype deles no arquivo review.js

LINHA 220

/* COMMENTS */
OnestepcheckoutReviewComments = Class.create();
OnestepcheckoutReviewComments.prototype = {
    initialize: function(config) {
        this.container = $$(config.containerSelector).first();
        this.newRowCount = config.newRowCount||5;
        this.saveValuesUrl = config.saveValuesUrl;

        var me = this;
        this.container.select('textarea').each(function(textarea) {
            textarea.setStyle({
                'overflow-y': 'hidden'
            });
            me.initShowEffectObserver(textarea);
        });
        Form.getElements(this.container).each(function(element){
            element.observe('change', me.requestToValuesSave.bind(me));
        });
    },

    requestToValuesSave: function(e) {
        new Ajax.Request(this.saveValuesUrl, {
            method: 'post',
            parameters: Form.serialize(this.container, true)
        });
    },

    initShowEffectObserver: function(textarea) {
        var originalScrollHeight = textarea.scrollHeight;
        var originalRowCount = parseInt(textarea.getAttribute('rows'));
        var originalHeight = parseInt(textarea.getStyle('height'));

        var me = this;
        textarea.observe('focus', function(e){
            var currentRowCount = originalRowCount +
                (((textarea.scrollHeight - originalScrollHeight) * originalRowCount) /  originalHeight);
            if (currentRowCount < me.newRowCount) {
                currentRowCount = me.newRowCount;
            } else {
                currentRowCount++; //add on empty line
            }
            var currentHeight = (originalHeight/originalRowCount)*currentRowCount;
            me.doChangeRowsAttributeEffect(textarea, currentRowCount, currentHeight, function(){
                textarea.setStyle({
                    'overflow-y': 'auto'
                });
            });
        });
        textarea.observe('blur', function(e){
            var lengthOfValue = textarea.getValue().strip().length;
            if (lengthOfValue === 0) {
                me.doChangeScrollOfTextareaEffect(textarea, function(){
                    textarea.setStyle({
                        'overflow-y': 'hidden'
                    });
                    me.doChangeRowsAttributeEffect(textarea, originalRowCount, originalHeight);
                });
            } else {
                var newHeight = (originalHeight/originalRowCount)*me.newRowCount;
                me.doChangeScrollOfTextareaEffect(textarea, function(){
                    textarea.setStyle({
                        'overflow-y': 'hidden'
                    });
                    me.doChangeRowsAttributeEffect(textarea, me.newRowCount, newHeight);
                });
            }
        });
    },

    doChangeRowsAttributeEffect: function(textarea, newRows, newHeight, afterFinish) {
        if (textarea.effect) {
            textarea.effect.cancel();
        }
        var afterFinish = afterFinish||new Function();
        textarea.effect = new Effect.Morph(textarea, {
            style: {
                height: newHeight + "px"
            },
            duration: 0.5,
            afterFinish:function() {
                textarea.setAttribute('rows', newRows);
                delete textarea.effect;
                afterFinish();
            }
        });
    },

    doChangeScrollOfTextareaEffect: function(textarea, afterFinish) {
        if (textarea.effect) {
            textarea.effect.cancel();
        }
        var afterFinish = afterFinish||new Function();
        if (textarea.scrollTop === 0) {
            afterFinish();
            return;
        }
        new Effect.Tween(textarea, textarea.scrollTop, 0, {
            duration: 0.5,
            afterFinish:function() {
                afterFinish();
            }
        }, 'scrollTop');
    }
};

/* NEWSLETTER */
OnestepcheckoutReviewNewsletter = Class.create();
OnestepcheckoutReviewNewsletter.prototype = {
    initialize: function(config) {
        this.container = $$(config.containerSelector).first();
        this.generalInput = $$(config.generalInputSelector).first();
        this.segmentsContainer = $$(config.segmentsContainerSelector).first();
        this.saveValuesUrl = config.saveValuesUrl;

        if (this.generalInput) {
            this.generalInput.observe('click', this.onSubscriptionChecked.bind(this));
        }
        var me = this;
        Form.getElements(this.container).each(function(element){
            element.observe('click', me.requestToSaveValues.bind(me));
        });
    },

    requestToSaveValues: function(e) {
        new Ajax.Request(this.saveValuesUrl, {
            method: 'post',
            parameters: Form.serialize(this.container, true)
        })
    },

    onSubscriptionChecked: function(e) {
        var me = this;
        if (this.segmentsContainer) {
            if (this.generalInput.getValue()) {
                this.showSegments();
            } else {
                this.hideSegments();
            }
        }
    },

    showSegments: function() {
        this._changeHeightToWithEffect(this._collectRealSegmentsHeight());
    },

    hideSegments: function() {
        this._changeHeightToWithEffect(0);
    },

    _changeHeightToWithEffect: function (height) {
        var me = this;
        if (this.effect) {
            this.effect.cancel();
        }
        this.effect = new Effect.Morph(this.segmentsContainer, {
            style: {'height': height + "px"},
            duration: 0.5,
            afterEffect: function(){
                delete me.effect;
            }
        });
    },

    _collectRealSegmentsHeight: function() {
        var originalHeightStyle = this.segmentsContainer.getStyle('height');
        this.segmentsContainer.setStyle({'height': 'auto'});
        var realHeight = this.segmentsContainer.getHeight();
        this.segmentsContainer.setStyle({'height': originalHeightStyle});
        return realHeight;
    }
};

Decidi fazer dessa forma, pois já existe um bind para o evento onblur no campo de CEP e não achei necessário mais do que essa chamada para o /saveAddress

Espero que ajude outras pessoas no mesmo contexto.

[ ]'s

amagen commented 7 years ago

Funcionou! Muito obrigado @andremerlo !

Alguém sabe como usar o Webservice: http://cep.republicavirtual.com.br/web_cep.php ou dos Correios em erro 500 ao invés de usar o: https://viacep.com.br/ws/

Obrigado pessoal, bom trabalho!