Bom dia ,
Tenho um exemplo feito em Harbour a funcionar com estas lib´s , mas preciso em xharbour , alguém pode ajudar-me , posso enviar as fontes do teste que fiz em harbour?
Cumprimentos
João Alpande
hbssl.lib hbcur.lib para xharbour?
-
- Posts: 33
- Joined: Wed Sep 16, 2009 8:53 am
Re: hbssl.lib hbcur.lib para xharbour?
O exemplo em harbour é este:
Code: Select all
#include "hbclass.ch"
#include "hbcurl.ch"
#include "hbssl.ch"
#define TRUE 1
#define FALSE 0
#define LOCAL_FILE "test1"
#define UPLOAD_FILE_AS "while-uploading.txt"
#define REMOTE_URL "ftp://localhost/"+UPLOAD_FILE_AS
#define RENAME_FILE_TO "renamed-and-fine.txt"
#define CURL_GLOBAL_SSL (1<<0)
#define CURL_GLOBAL_WIN32 (1<<1)
#define CURL_GLOBAL_ALL (CURL_GLOBAL_SSL|CURL_GLOBAL_WIN32)
#define CURL_GLOBAL_NOTHING 0
#define CURL_GLOBAL_DEFAULT CURL_GLOBAL_ALL
#xcommand TEXT INTO <v> => #pragma __text|<v>+=%s+HB_OSNEWLINE();<v>:=""
REQUEST __HBEXTERN__HBSSL__
FUNCTION main()
LOCAL e, l
//SetMode(30,80)
e := EnvioDocumentoTransporte():new()
e:user := "123456789/1"
e:senha := "Password "
e:datasistema := hb_DateTime()
e:contribuinte := "505422824"
e:nome := "Infor Pires Lda"
e:morada := "Sitio do Alem, 846-A"
e:cidade := "Almancil"
e:codPostal := "8135-011"
e:pais := "PT"
e:docId := "GT A1/52314"
// e:AtDocCodeId := "999999999" // se guia já comunicada, para reenviar como anulada ?
e:estado := "N" // estado : (N)ormal (T)erceiros (A)nulada
e:dataDoc := Date()
e:tipoDoc := "GT" // GR/GT/GA/GC/GD
e:clienteNif := "199530491"
//e:FornecedorNif := "999999990" // ???? NÂO PERCEBI A QUE RAIO SE DESTINA
e:clienteNome := "Nelson Pires"
e:clienteMorada := "Desconhecido"
e:clienteCidade := "Faro"
e:clienteCodPostal:= "8000-000"
e:clientePais := "PT"
e:descargaMorada := "Ali"
e:descargaCidade := "Desconhecido"
e:descargaCodPostal := "8000-000"
e:descargaPais := "PT"
e:cargaMorada := "Aqui"
e:cargaCidade := "Desconhecido"
e:cargaCodPostal := "8000-000"
e:cargaPais := "PT"
e:fimCarga := "2013-05-25T09:00:00"
e:inicioCarga := "2013-05-25T09:00:00"
e:matricula := "00-XX-00"
l := LinhaDocumentoTransporte():new()
//l:adicionaReferencia("VD A/20001") // TEM QUE REFERIR UM JA EXISTENTE, SENÃO ERRO VALIDACAO
//l:adicionaReferencia("VD A/20002")
l:descricao := "Produto da linha 1"
l:quantidade := 100
l:unidade := "KG"
l:precoUnitario := 5.25
e:adicionaLinha(l)
l := LinhaDocumentoTransporte():new()
//l:adicionaReferencia("VD A/20003")
l:descricao := "Produto da linha 2"
l:quantidade := 10
l:unidade := "UN"
l:precoUnitario := 1.25
e:adicionaLinha(l)
e:certificado("Certificado.pfx")
e:chavePublica("chavePublicaAT.cer")
e:ldebug := .T.
cls
@1,1 say "User Financas :" get e:user
@2,1 SAY "Pass Financas :" get e:senha
@3,1 say "Contribuinte :" get e:contribuinte
@4,1 say "Nº Guia.......:" get e:docid
@5,1 say "Incio Transp..:" get e:inicioCarga
@6,1 say "Fim Transporte:" get e:fimCarga
READ
e:enviaGuia()
IF e:resultado==0
? "Doc. "+ e:resultadoDocNum +" Inserido com exito"
? "Código AT : "+ e:resultadoDocIdAT
else
? "Erro a submeter documento : ", Str(e:resultado)
? e:resultadoTXT
endif
? e:resultadoTXT
Inkey(0)
return
CLASS EnvioDocumentoTransporte
var user as STRING
var senha as STRING
var datasistema
var contribuinte as string
var nome as string
var morada as string
var cidade as string
var codPostal as string
var pais as string
VAR atDocCodeId AS STRING INIT NIL
var docId as string
VAR estado as CHAR
VAR dataDoc as DATE
VAR tipoDoc as string
VAR clienteNif as string
VAR clienteNome, clienteMorada, clienteCidade, clienteCodPostal, clientePais as string
VAR descargaMorada, descargaCidade, descargaCodPostal, descargaPais as string
VAR cargaMorada, cargaCidade, cargaCodPostal, cargaPais as string
VAR inicioCarga, fimCarga, matricula as string
VAR certificado, chavepublica
VAR resultado INIT -999
VAR resultadoTxt INIT ""
VAR resultadoDocNum INIT ""
VAR resultadoDocIdAT INIT ""
DATA nOnce HIDDEN
DATA linhas HIDDEN INIT {}
DATA xmlOut INIT ""
DATA lDebug INIT .F.
DATA cUrl
DATA aesKey
DATA cryptedPassword INIT ""
DATA cryptedDate
METHOD new()
METHOD adicionaLinha(linhaDoc)
METHOD enviaGuia()
METHOD pwd()
METHOD buildXML()
METHOD gen_Crypt()
ENDCLASS
// ------------------------------------------------------------------
METHOD new() CLASS EnvioDocumentoTransporte
RETURN SELF
// -------------------------------------------------------------------
METHOD adicionaLinha(linhadoc) CLASS EnvioDocumentoTransporte
AAdd(::linhas,linhaDoc)
RETURN
// -------------------------------------------------------------------
METHOD pwd() CLASS EnvioDocumentoTransporte
RETURN
METHOD enviaGuia() CLASS EnvioDocumentoTransporte
::buildxml()
RETURN
// -------------------------------------------------------------------
METHOD buildXML() CLASS EnvioDocumentoTransporte
LOCAL n,i,nLinhas, oLine
nLinhas := Len(::linhas)
::gen_crypt()
::xmlOut := '<?xml version="1.0" encoding="utf-8" standalone="no"?>' + HB_OSNEWLINE()
::xmlOut += '<S:Envelope xmlns:S="http://schemas.xmlsoap.org/soap/envelope/">' + HB_OSNEWLINE()
::xmlOut += ' <S:Header> ' + HB_OSNEWLINE()
::xmlOut += ' <wss:Security xmlns:wss="http://schemas.xmlsoap.org/ws/2002/12/secext">' + HB_OSNEWLINE()
::xmlOut += ' <wss:UsernameToken>' + hb_osNewLine()
::xmlOut += ' <wss:Username>' + AllTrim(::user) + '</wss:Username>' + hb_osNewLine()
::xmlOut += ' <wss:Password>' + ::cryptedPassword + '</wss:Password>' + hb_osNewLine()
::xmlOut += ' <wss:Nonce>' + ::aeskey + '</wss:Nonce>' + hb_osNewLine()
::xmlOut += ' <wss:Created>' + ::cryptedDate +'</wss:Created>' + hb_osNewLine()
::xmlOut += ' </wss:UsernameToken>' + hb_osNewLine()
::xmlOut += ' </wss:Security>' + hb_osNewLine()
::xmlOut += ' </S:Header>' + hb_osNewLine()
::xmlOut += ' <S:Body>' + hb_osNewLine()
::xmlOut += ' <ns2:envioDocumentoTransporteRequestElem xmlns:ns2="https://servicos.portaldasfinancas.gov.pt/sgdtws/documentosTransporte/">' + hb_osNewLine()
::xmlOut += ' <TaxRegistrationNumber>' + ::contribuinte + '</TaxRegistrationNumber>' + hb_osNewLine()
::xmlOut += ' <CompanyName>' + ::nome + '</CompanyName>' + hb_osNewLine()
::xmlOut += ' <CompanyAddress>' + hb_osNewLine()
::xmlOut += ' <Addressdetail>' + ::Morada + '</Addressdetail>' + hb_osNewLine()
::xmlOut += ' <City>' + ::Cidade + '</City>' + hb_osNewLine()
::xmlOut += ' <PostalCode>' + ::codPostal + '</PostalCode>' + hb_osNewLine()
::xmlOut += ' <Country>' + ::pais+ '</Country>' + hb_osNewLine()
::xmlOut += ' </CompanyAddress>' + hb_osNewLine()
::xmlOut += ' <DocumentNumber>' + ::docId + '</DocumentNumber>' + hb_osNewLine()
IF ::atDocCodeId != NIL
::xmlOut += ' <AtDocCodeId>' + ::atDocCodeId + '</AtDocCodeId>' + hb_osNewLine()
ENDIF
::xmlOut += ' <MovementStatus>' + ::estado + '</MovementStatus>' + hb_osNewLine()
::xmlOut += ' <MovementDate>' + hb_DToC(::dataDoc,"yyyy-mm-dd") + '</MovementDate>' + hb_osNewLine()
::xmlOut += ' <MovementType>' + ::tipodoc + '</MovementType>' + hb_osNewLine()
::xmlOut += ' <CustomerTaxID>' + ::clienteNif + '</CustomerTaxID>' + hb_osNewLine()
::xmlOut += ' <CustomerAddress>' + hb_osNewLine()
::xmlOut += ' <Addressdetail>' + ::clienteMorada + '</Addressdetail>' + hb_osNewLine()
::xmlOut += ' <City>' + ::clienteCidade + '</City>' + hb_osNewLine()
::xmlOut += ' <PostalCode>' + ::clienteCodPostal + '</PostalCode>' + hb_osNewLine()
::xmlOut += ' <Country>' + ::clientePais + '</Country>' + hb_osNewLine()
::xmlOut += ' </CustomerAddress>' + hb_osNewLine()
::xmlOut += ' <CustomerName>' + ::clienteNome + '</CustomerName>' + hb_osNewLine()
::xmlOut += ' <AddressTo>' + hb_osNewLine()
::xmlOut += ' <Addressdetail>' + ::descargaMorada + '</Addressdetail>' + hb_osNewLine()
::xmlOut += ' <City>' + ::descargaCidade + '</City>' + hb_osNewLine()
::xmlOut += ' <PostalCode>' + ::descargaCodPostal + '</PostalCode>' + hb_osNewLine()
::xmlOut += ' <Country>' + ::descargaPais + '</Country>' + hb_osNewLine()
::xmlOut += ' </AddressTo>' + hb_osNewLine()
::xmlOut += ' <AddressFrom>' + hb_osNewLine()
::xmlOut += ' <Addressdetail>' + ::cargaMorada + '</Addressdetail>' + hb_osNewLine()
::xmlOut += ' <City>' + ::cargaCidade + '</City>' + hb_osNewLine()
::xmlOut += ' <PostalCode>' + ::cargaCodPostal + '</PostalCode>' + hb_osNewLine()
::xmlOut += ' <Country>' + ::cargaPais + '</Country>' + hb_osNewLine()
::xmlOut += ' </AddressFrom>' + hb_osNewLine()
::xmlOut += ' <MovementEndTime>' + ::fimCarga +'</MovementEndTime>' + hb_osNewLine()
::xmlOut += ' <MovementStartTime>' + ::inicioCarga + '</MovementStartTime>' + hb_osNewLine()
::xmlOut += ' <VehicleID>' + ::matricula + '</VehicleID>' + hb_osNewLine()
FOR n:=1 TO nLinhas
::xmlOut += ' <Line>' + hb_osNewLine()
oLine := ::linhas[n]
FOR i=1 TO Len(oLine:aRefs)
::xmlOut += ' <OrderReferences>' + hb_osNewLine()
::xmlOut += ' <OriginatingON>'+ oLine:aRefs[i] + '</OriginatingON>' + hb_osNewLine()
::xmlOut += ' </OrderReferences>' + hb_osNewLine()
NEXT
::xmlOut += ' <ProductDescription>' + oLine:descricao + '</ProductDescription>' + hb_osNewLine()
::xmlOut += ' <Quantity>' + aStr(oLine:quantidade) + '</Quantity>' + hb_osNewLine()
::xmlOut += ' <UnitOfMeasure>' + oLine:unidade + '</UnitOfMeasure>' + hb_osNewLine()
::xmlOut += ' <UnitPrice>' + aStr(oLine:precoUnitario) + '</UnitPrice>' + hb_osNewLine()
::xmlOut += ' </Line>' + hb_osNewLine()
NEXT
::xmlOut += ' </ns2:envioDocumentoTransporteRequestElem>' + hb_osNewLine()
::xmlOut += ' </S:Body>' + hb_osNewLine()
::xmlOut += '</S:Envelope>' + hb_osNewLine()
IF (::lDebug)
MemoWrit("pacote.txt",::xmlout)
endif
curl_global_init()
cUrl := curl_easy_init()
curl_easy_setopt(curl,HB_CURLOPT_URL,"https://servicos.portaldasfinancas.gov.pt:701/sgdtws/documentosTransporte")
curl_easy_setopt(curl,HB_CURLOPT_SSLCERT,"./good.pem")
curl_easy_setopt(curl,HB_CURLOPT_HTTPHEADER, "Content-Type:text/xml;charset=UTF-8")
// todo : if(::lVerbose
curl_easy_setopt(curl,HB_CURLOPT_VERBOSE,.T.)
curl_easy_setopt(curl, HB_CURLOPT_SSL_VERIFYPEER, .F.)
curl_easy_setopt(curl, HB_CURLOPT_SSL_VERIFYHOST, .F.)
curl_easy_setopt(curl,HB_CURLOPT_SSLCERTPASSWD,"TESTEwebservice")
curl_easy_setopt(cUrl, HB_CURLOPT_POSTFIELDS, ::xmlOut)
curl_easy_setopt(Curl, HB_CURLOPT_WRITEFUNCTION, 1)
curl_easy_setopt(Curl, HB_CURLOPT_DL_BUFF_SETUP )
curl_easy_perform(cUrl)
cXmlResp := ""
curl_easy_setopt( curl, HB_CURLOPT_DL_BUFF_GET, @cXMLResp )
Inkey(0)
// todo : if(::lDebug)
IF ::lDebug
Memowrit("resp.txt",cXmlResp)
endif
// Ver o resultado //
// todo : fazer o parser corretamente
oDocMaster := hxmldoc():new("UTF-8")
oDocMaster:readString(cXmlResp)
oNode := oDocMaster:aItems[1]:aItems[2]:aItems[1]:aItems[1]:aItems // Response status //
FOR n := 1 TO Len(oNode)
o:=oNode[n]
cTag := Upper(o:title)
cVal := o:aItems[1]
IF cTag == "RETURNCODE"
::resultado := Val(cVal)
ELSEIF cTag == "RETURNMESSAGE"
::resultadoTXT := cVal
ENDIF
NEXT
IF ::resultado==0 // OK, tirar docnum e atdocid
::resultadoDocNum := oDocMaster:aItems[1]:aItems[2]:aItems[1]:aItems[2]:aItems[1]
::resultadoDocIdAT := oDocMaster:aItems[1]:aItems[2]:aItems[1]:aItems[3]:aItems[1]
ENDIF
curl_easy_cleanup(curl)
curl_global_cleanup()
RETURN
// ---------------------------------------------------------------------
STATIC FUNCTION timefmt(dt)
LOCAL t,c
dt := dt - ((hb_UTCOffset()/3600) / 24)
c:= hb_TToS(dt)
t := SubStr(c,1,4)+"-"+SubStr(c,5,2)+"-"+SubStr(c,7,2)+"T"+;
SubStr(c,9,2)+":"+SubStr(c,11,2)+":"+SubStr(c,13,2)+"."+SubStr(c,15)+"Z"
RETURN t
// -------------------------------------------------------------------------------------------
STATIC FUNCTION aStr(n)
RETURN AllTrim(Str(n,10,2))
//----------------------------------------------------------------------------------------------
METHOD gen_crypt() CLASS EnvioDocumentoTransporte
LOCAL bio, ch, iv, ctx, publicKey, pub
LOCAL result, final
ssl_init()
OpenSSL_add_all_ciphers()
#pragma __cstream|publicKey:=%s
-----BEGIN PUBLIC KEY-----
MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAoQi+XDM9OJ+Kr+Blaxn3
MFBE7UMYL7bfPGCxS0JDIbYlfQp65mYfzRcIhwysheO9nn7SlpF1b6TNNZglf3BT
SpFWP4xwB+RpjmHj1ClLg+hO1E/+olLfbIUplFqATpTWP7TGsgGBOhenQedzasq6
qzEoEAiOx4x2kD0NLPGUzMZaUr8HTGriYePWC4SJgwFSGQ9V5Yf4g2zYVh0Kyr2V
hJi9mJsGi3mBrgpxueabxEXnDdrDR1PiPhEPIU/w+63jZzcV/cvaKTSyvPtebPSy
+AdMtR5r2HXtDoZUKLHfcWZ2LP794wM5WU7ZoIuAQGGKZZyULqneGzCNdvmMuWu8
5wIDAQAB
-----END PUBLIC KEY-----
#pragma __endtext
RAND_SEED("OITOLETR")
ctx := hb_EVP_CIPHER_ctx_create()
EVP_CIPHER_CTX_init( ctx )
pub:=PEM_read_bio_PUBKEY( bio := BIO_new_mem_buf( publicKey ), "" )
EVP_SealInit( ctx, "AES-128-ECB", @ch, @iv, pub )
::aeskey:=hb_base64Encode(ch[1])
//Alert(ch[1])
//Alert( Str(Len(ch[1]) ))
::dataSistema := hb_DateTime()
result := ""
final := ""
EVP_SealUpdate( ctx, @result, timefmt(::dataSistema) )
final += result
EVP_SealFinal( ctx, @result )
final += result
::cryptedDate := hb_base64Encode(final)
result := ""
final := ""
EVP_SealUpdate( ctx, @result, AllTrim(::senha) )
final += result
Len(result)
EVP_SealFinal( ctx, @result )
final += result
::cryptedPassword := hb_base64Encode(final)
// clean UP
BIO_free( bio )
EVP_PKEY_free( pub )
ctx := NIL
EVP_cleanup()
RETURN
// --------------------------------------------------------------------
CLASS LinhaDocumentoTransporte
VAR descricao, quantidade, unidade, precoUnitario
VAR aRefs INIT {}
METHOD New()
METHOD adicionaReferencia(cDocRef)
ENDCLASS
// -------------------------------------------------------------------
METHOD adicionaReferencia(cDocRef) CLASS LinhaDocumentoTransporte
AAdd(::aRefs,cDocRef)
RETURN
// -------------------------------------------------------------------
METHOD new() CLASS LinhaDocumentoTransporte
RETURN SELF