EDUTEK Posted September 29, 2017 Report Share Posted September 29, 2017 BOA TARDE Precio buscar a averbação do Seguro para emisaão do MDFE via WEBService da Porto Seguro. Alguém ja desenvoiveu isso ? ou teria como com motar um exemplo para eu converter as fucnçoes PHP do exemplo para xharbour segue exemplo "... Exemplo em PHP (cURL) <?php/*** Open an url on https using curl and return content* @author hatem <info@phptunisie.net>* @param string url The url to open* @param string refer Referer (optional)* @param mixed usecookie If true, cookie.txt will be used as default, or the usecookie value.* @return string*/function open_https_url($url,$refer = "", $usecookie = false) { if ($usecookie) { if (file_exists($usecookie)) { if (!is_writable($usecookie)) { return "Can't write to $usecookie cookie file, change file permission to 777 or remove read only for windows."; } } else { $usecookie = ($usecookie === true)? "cookie.txt" : $usecookie; if (!touch($usecookie)) { return "Can't write to $usecookie cookie file, change file permission to 777 or remove read only for windows."; } } } $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE); curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2); curl_setopt($ch, CURLOPT_HEADER, 0); curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0)"); if ($usecookie) { curl_setopt($ch, CURLOPT_COOKIEJAR, $usecookie); curl_setopt($ch, CURLOPT_COOKIEFILE, $usecookie); } if ($refer != "") { curl_setopt($ch, CURLOPT_REFERER, $refer ); } curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); return $ch;}/*** Limpeza ao terminar de executar* Requer $ws*/function ws_shutdown(){global $ws;if (file_exists($ws['cookie'])) {unlink($ws['cookie']);}}register_shutdown_function('ws_shutdown');/*** Ajax Request* Requer $ws Global Config (comp/path/cookie)* aPost (array) json params* sModule (string) mod (i.e. login/Upload/Retrieve)* $sConn (string) URI to connect*/function websysRequest($aPost, $sModule = 'login', $sConn = 'http://www.averbeporto.com.br/websys/php/conn.php') {global $ws;if (!isset($aPost['comp'])) { $aPost['comp'] = $ws['comp']; }if (!isset($aPost['path'])) { $aPost['path'] = $ws['path']; } elseif ($aPost['path'] == '') { unset($aPost['path']); }$aPost['mod'] = $sModule;$ch = open_https_url($sConn, '', $ws['cookie']);curl_setopt($ch, CURLOPT_POST, 1);curl_setopt($ch, CURLOPT_POSTFIELDS, $aPost);$res = curl_exec($ch);curl_close($ch);return $res;}?> Exemplo de Uso: <?phprequire_once('func.php'); // Exemplo Config $ws$ws = array('comp' => 5,'path' => 'eguarda/php/','conn' => 'http://www.averbeporto.com.br/websys/php/conn.php','cookie' => tempnam(sys_get_temp_dir(), 'ws_'),'logged' => ''); /*** Envia arquivo** @param {String} Conteudo do arquivo* @param {Array} Usuario e senha. Ex.: array('user'=>'USUARIO', 'pass'=>'SENHA', 'path'=>'')* @param {String} (optional) Remetente (em caso de email)* @return {Array} Retorna resposta do webservice*/function sendFile($sFileContent, $aUser, $sRecipient = ''){global $ws;$file = tmpfile();fwrite($file, $sFileContent);rewind($file);$meta = stream_get_meta_data($file);$mime = mime_content_type($meta['uri']);$post = array('file' => (version_compare(PHP_VERSION, '5.5') >= 0)? new CURLFile($meta['uri'], $mime) : '@'.$meta['uri'].';type='.$mime);if ($sRecipient) {$post['recipient'] = $sRecipient;}// Loginif ($ws['logged'] != $aUser['user']) {$res = json_decode(websysRequest($aUser), true);if (isset($res['logout']) && $res['logout']) {//ws_log('MAIL2EG: ['.$aUser['user'].']: '.posix_getpid().': Falha do login. ');}} else {$res['success'] = $res['C'] = true;}// Uploadif ($res['success'] && isset($res['C'])) {$ws['logged'] = $aUser['user'];$res = json_decode(websysRequest($post, 'Upload'), true);}fclose($file);return $res;}$aUser = array( 'user' => 'USUARIO', 'pass' => 'SENHA', 'path' => '');$sFileContent = file_get_contents('ARQUIVO.xml');$res = sendFile($sFileContent, $aUser);print_r($res);?> ."" alguém teria um modelo mais ou menos parecido de como eu faria isso no xharbour Hoje eu fiz desta forma, o usuario envia o XML do CTE via email para a Porto Seguro, ele receber lá, depois o usuario entra no Site e copia o numero da averbação e depois digita no MDFE e envio, mas isso é muito trabalho pro usuario. Grato Quote Link to comment Share on other sites More sharing options...
wanderso Posted October 2, 2017 Report Share Posted October 2, 2017 Também estou na mesma, coloquei para digitar manualmente o resultado da averbação mas integrar seria melhor. Uma dúvida, se o cliente emitiu um manifesto na sexta passada na versão 2.0 e como hoje passa a valer a 3.0 como será finalizado o manifesto emitido já que o veículo ainda não chegou no destino? Quote Link to comment Share on other sites More sharing options...
kapiaba Posted October 2, 2017 Report Share Posted October 2, 2017 http://www.portalntc.org.br/comunicados/averbacao-do-seguro-no-manifesto-eletronico-de-documentos-fiscais-mdf-e/58624 Quote Link to comment Share on other sites More sharing options...
andreluc1361303601 Posted July 26, 2018 Report Share Posted July 26, 2018 EDUTEK Bom dia, você conseguiu fazer a averbação usando o webservice da porto seguro Quote Link to comment Share on other sites More sharing options...
EDUTEK Posted July 26, 2018 Author Report Share Posted July 26, 2018 só fiz a consulta estou enviando manualmente e pego a averbação na emissao do mdfe, não consegui fazer o envio do xml na hora de emitir o mdfe. Function busca_averba_cte(cCte) public oMSXML2 := TOleAuto():New( "MSXML2.ServerXMLHTTP" ) mNumaverb := Consultaws_cte(cCTE) return mNumaverb Function ConsultaWS_cte(cCTE) local oRs, ws url := "http://www.averbeporto.com.br/websys/atwe/php/Protocolo.php?out=xml"+; "&download=1"+; "&chave[]="+cCte oXMLSedex:= oMSXML2 // MSXML2.ServerXMLHTTP oXMLSedex:Open( "GET", url, .F.) oXMLSedex:Send() cXMLSedex := oXMLSedex:responseText MemoWrit( "sedex.xml", cXMLSedex ) cXMLProt := XMLGet( "protocolo", cXMLSedex ) cXMLErros := if(empty(cXMLProt),"Não Encontrato a Averbação","") cProtocolo := cXMLProt return cProtocolo isso pega o numero da averbação Quote Link to comment Share on other sites More sharing options...
andreluc1361303601 Posted July 27, 2018 Report Share Posted July 27, 2018 Boa tarde EDUTEK Você chegou a falar com alguem da ghsix ? Quote Link to comment Share on other sites More sharing options...
andreluc1361303601 Posted July 29, 2018 Report Share Posted July 29, 2018 EDUTEK Você conseguiu fazer o login ? Quote Link to comment Share on other sites More sharing options...
andreluc1361303601 Posted July 29, 2018 Report Share Posted July 29, 2018 Codigo que faz o login e retorna o cookie da sessão function LoginWS(cUsuario,cSenha) local strXml strXml := [] strXml += [mod=login] strXml += [&comp=5] strXml += [&user=]+cUsuario strXml += [&pass=]+cSenha cUrl := "http://www.averbeporto.com.br/websys/php/conn.php" oServer:= CreateObject( "MSXML2.ServerXMLHTTP") oServer:Open( "POST", cUrl, .f. ) oServer:SetRequestHeader( "Content-Type", "application/x-www-form-urlencoded" ) oServer:Send(strXml) // oServer:WaitForResponse( 10000 ) cCookieSessao := oServer:getResponseHeader("Set-Cookie") // pega o cookie da sessão cCookieSessao := substr(cCookieSessao,1,at(';',cCookieSessao)-1) cRetorno:= oServer:ResponseText MemoWrit( "xml\retorno.xml", cRetorno ) return(cCookieSessao) Quote Link to comment Share on other sites More sharing options...
EDUTEK Posted July 30, 2018 Author Report Share Posted July 30, 2018 beleza aqui funciunou retornou o arquivo Quote Link to comment Share on other sites More sharing options...
EDUTEK Posted July 30, 2018 Author Report Share Posted July 30, 2018 o Envio do XML do CTe seria mais ou menos assim function enviaWS(mUsuario,mSenha,mArqxml) local strXml, ws, oRs strXml := [] strXml += [mod=Upload] strXml += [&comp=5] strXml += [&user=]+mUsuario strXml += [&pass=]+mSenha strXml += [&Cookie=]+mCookie strXml += [&path=]+"eguarda/php/" strXml += [&file=]+mArqxml cUrl := "http://www.averbeporto.com.br/websys/php/conn.php" oServer:= CreateObject( "MSXML2.ServerXMLHTTP") oServer:Open( "POST", cUrl, .f. ) oServer:SetRequestHeader( "Content-Type", "multipart/form-data" ) oServer:Send(strXml) // oServer:WaitForResponse( 10000 ) cRetorno:= oServer:ResponseText MemoWrit( "xml\retorno.xml", cRetorno ) msginfo(cretorno,"envio") return(cRetorno) Quote Link to comment Share on other sites More sharing options...
EDUTEK Posted July 30, 2018 Author Report Share Posted July 30, 2018 mas desta forma ele não esta indo, alguém consegue verificar onde esta o erro Quote Link to comment Share on other sites More sharing options...
fladimir Posted July 30, 2018 Report Share Posted July 30, 2018 As etapas seriam: Gera a CTe Transmite o XML para o portal Pega o nr da averbação pra fazer o MDFe seria isso? Qual etapa não certo Edutek? Quote Link to comment Share on other sites More sharing options...
andreluc1361303601 Posted July 31, 2018 Report Share Posted July 31, 2018 Fladimir a etapa que não esta dando certo é o envio do xml para ser feito a averbação. que pode ser apenas um arquivo xml ou vários xmls compactado .zip só que o processo é o seguinte, você tem que fazer o login e pegar o cookie da sessão e só assim enviar o xml ou compactado junto com esse cookie. o login eu conseguir fazer com base em um comando usando o curl e converti para o postman extensão essa instalada no google chrome. o comando de transmissão tem também em curl e é a seguinte: Upload: curl ' http://www.averbeporto.com.br/websys/php/conn.php ' --compressed -X POST -H 'Cookie: portal[ses]=8c878b3ab2ba27bf7bc4d5d448b6489b' -H 'Content-Type: multipart/form-data' -F mod=Upload -F comp=5 -F path=eguarda/php/ -F file=@ARQUIVO.xml Quote Link to comment Share on other sites More sharing options...
fladimir Posted July 31, 2018 Report Share Posted July 31, 2018 Mas o q ta faltando então? a parte do envio do arquivo é isso? Se sim não teria q transformar em Base64 igual é feito na nota eletronica? Quote Link to comment Share on other sites More sharing options...
fladimir Posted July 31, 2018 Report Share Posted July 31, 2018 Acho q consegui... Testem ai... ******************************************************************************** function AverbandoXMLCTe() LOCAL hJSON, hDados LOCAL cRet, oUrl, oHTTP, cURL cURL := "http://www.averbeporto.com.br/websys/php/conn.php" oUrl := TURL():new( cUrl ) oHTTP := TIPClientHTTP():new( oUrl ) IF !oHTTP:open() RETURN .F. ENDIF hDados := hb_hash() // Reseto a variavel hDados["mod"] := 'login' hDados["comp"] := '5' hDados["user"] := 'Usuario' hDados["pass"] := 'Senha' hDados["dump"] := '1' IF !oHTTP:post( hDados ) RETURN .F. ENDIF cRet:= oHTTP:ReadAll() hb_jsonDecode(cRet, @hJson) // Aki analiso se logou ok // Se no hJson q volta tiver hJson["C"]["userName"] = usuario q mandei blz logou ok // Cookie q veio fica em : oHTTP:hCookies["www.averbeporto.com.br"]["/"]["portal[ses]"] // Depois pra mandar o arquivo XML monto um hDados assim: // Até aki ta testado e funcionando... não testei o envio mas é pra funcionar no meu entendimento // o Cookie já consta do objeto oHTTP então não preciso reenviar, pq já esta ali, basta montar o Hash com o conteúdo pra envio do XML /* Montagem do Hash pra envio hDados := hb_hash() // Reseto a variavel hDados["comp"] := '5' hDados["mod"] := 'Upload' hDados["path"] := 'eguarda/php' hDados["recipient"] := '' hDados["file"] := 'ConteudodoarquivoXML' // aki q não tenho certeza tem q testar, mas acredito q seja carregar esse campo com o conteúdo do XML // Como estou logado e o Cookie dentro o oHTTP passo o hDados novo IF !oHTTP:post( hDados ) RETURN .F. ENDIF cRet:= oHTTP:ReadAll() // pego o retorno hb_jsonDecode(cRet, @hJson) // transformo em JSON // Ai o retorno disso deve ser algo do tipo hJson["S"]["P"] //1 // Processado (xml guardadado com sucesso) hJson["S"]["D"] //0 // Duplicado hJson["S"]["R"] //0 // Rejeitado hJson["S"]["N"] //0 // Negado hJson["prot"] // Protocolo do xml guardado P //-- Mensagens de erro para resultados R ou N hJson["error"]["code"] hJson["error"]["msg"] */ oHTTP:Close() // Encerra conexão RETURN NIL Quote Link to comment Share on other sites More sharing options...
andreluc1361303601 Posted July 31, 2018 Report Share Posted July 31, 2018 Bom dia Fladimir Eu uso o xharbour existe esse metodo oHTTP:hCookies["www.averbeporto.com.br"]["/"]["portal[ses]"] Quote Link to comment Share on other sites More sharing options...
fladimir Posted July 31, 2018 Report Share Posted July 31, 2018 Não tenho certeza, mas acredito q sim pq na verdade é uma propriedade da classe q é instaciada através do TipClientHTTP, q qdo é aberta a URL carrega e conforme o manual quem retorna essa informação é o Site da Porto Seguro, ou seja, teoricamente tem q funcionar, só um detalhe a forma de trabalhar com Hashs no xHarbour, até onde eu lembro, é um pouco diferente, lembrando q é CaseSensitive, mas tem uma função q passa antes pra ignorar, só não lembro qual é. Quote Link to comment Share on other sites More sharing options...
EDUTEK Posted July 31, 2018 Author Report Share Posted July 31, 2018 bom dia fiz desta forma e ele me retorno o seguinte function enviaWS(mUsuario,mSenha,mArqxml) local strXml, ws, oRs, olServer cUrl := "http://www.averbeporto.com.br/websys/php/conn.php?"+; "mod=Upload"+; "&comp=5"+; "&path=eguarda/php/"+; "&file=@"+mArqxml+"" msginfo(cURL) oServer:= CreateObject( "MSXML2.ServerXMLHTTP") oServer:Open( "POST", cUrl, .F. ) oServer:SetRequestHeader( "Cookie", mCookie ) oServer:SetRequestHeader( "Content-Type", "multipart/form-data" ) oServer:Send() // oServer:WaitForResponse( 10000 ) cRetorno:= oServer:ResponseText MemoWrit( "xml\retornoenv.xml", cRetorno ) msginfo(cretorno,"envio") return(cRetorno) {"success":1,"S":{"P":0,"D":0,"R":0,"N":0},"error":{"msg":"No XML or ZIP file found"}} dizendo que não é um arquivo xml. Quote Link to comment Share on other sites More sharing options...
fladimir Posted July 31, 2018 Report Share Posted July 31, 2018 Vc tentou usando meu código? Estou aguardando um XML de um cliente aki pra testar meu código pq não testei ainda ele, mas acredito q vai funcionar. Quote Link to comment Share on other sites More sharing options...
EDUTEK Posted July 31, 2018 Author Report Share Posted July 31, 2018 sim ele não vai hDados := hb_hash() // Reseto a variavel hDados["mod"] := 'Upload' hDados["comp"] := '5' hDados["path"] := 'eguarda/php/' hDados["recipient"] := '' hDados["file"] := mArqXml && 'ConteudodoarquivoXML' // aki q não tenho certeza tem q testar, mas acredito q seja carregar esse campo com o conteúdo do XML // Como estou logado e o Cookie dentro o oHTTP passo o hDados novo IF !oHTTP:post( hDados ) /// ele encerra aqui RETURN .F. ENDIF cRet:= oHTTP:ReadAll() // pego o retorno hb_jsonDecode(cRet, @hJson) // transformo em JSON ja tentei com o conteuido do xml e com p caminho os dois sai na opcao acima Quote Link to comment Share on other sites More sharing options...
andreluc1361303601 Posted July 31, 2018 Report Share Posted July 31, 2018 Também testei e não vai, retorna .f. Quote Link to comment Share on other sites More sharing options...
kapiaba Posted July 31, 2018 Report Share Posted July 31, 2018 Mira se ayuda: http://www.pctoledo.com.br/forum/viewtopic.php?f=4&t=17879 Quote Link to comment Share on other sites More sharing options...
kapiaba Posted July 31, 2018 Report Share Posted July 31, 2018 #Include "Fivewin.ch" //-------------------------------- Function Main() Local oHttp Try oHttp := CreateObject( 'MSXML2.XMLHTTP' ) Catch oHttp := CreateObject( 'Microsoft.XMLHTTP' ) End oHttp:Open( 'POST', "https://www.winwebconnect.com/api/v1/Login", .F. ) oHttp:SetRequestHeader( "Content-Type","application/json") oHttp:Send( '{ "Username": "user@company.com", "Password": "secret"}' ) SysRefresh() MsgInfo(oHttp:ResponseBody) Return Quote Link to comment Share on other sites More sharing options...
andreluc1361303601 Posted July 31, 2018 Report Share Posted July 31, 2018 kapiaba o problema esta em enviar o arquivo para o webservice Quote Link to comment Share on other sites More sharing options...
kapiaba Posted July 31, 2018 Report Share Posted July 31, 2018 ke treko dificil, veja se ajuda: http://forums.fivetechsupport.com/viewtopic.php?f=6&t=28650&p=160640&hilit=enviar+archivo+para+webservice#p160640 Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.