Jump to content

Leaderboard

Popular Content

Showing content with the highest reputation on 03/16/2021 in all areas

  1. Partilho abaixo o código completo para comunicar com os serviços Saphety para quem precisar. A documentação é publica por isso não deve haver problema e com certeza muito pessoal agradece. Visto que existem vários brokers, para já estou a desenvolver para 2, saphety e espap, eu optei por criar uma interface com o essencial e derivar a partir dai para qualquer broker. No entanto quem quiser pode retirar a interface e usar apenas a classe. using System; using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using System.IO; using System.Linq; using System.Reflection; using System.Runtime.CompilerServices; using System.Security; using System.Text; using System.Threading.Tasks; using Microsoft.VisualBasic; public class SaphetyAS2 : AS2Interface { private string _token; public string Token { get { return _token; } } private string _responseText; public string ResponseText { get { return _responseText; } } private string _requestID; public string RequestID { get { return _requestID; } } private string _requestStatus; public string RequestStatus { get { return _requestStatus; } } private string _errors; public string Errors { get { return _requestStatus; } } private string server_base_adress = "dcn-solution.saphety.com/Dcn.Sandbox.WebApi"; // Saphety Invoice Network - Production Environment // Const server_base_adress = "dcn-solution.saphety.com/Dcn.Business.WebApi" private string TokenUri = "https://" + server_base_adress + "/api/Account/getToken"; private string SendFileUri = "https://" + server_base_adress + "/api/CountryFormatAsyncRequest/processDocument/{IssuerNIF}/{DocumentType}/PT"; private string GetStatusByRequestIDUri = "https://" + server_base_adress + "/api/CountryFormatAsyncRequest/{RequestId}"; private string GetStatusByDocumentKeyUri = "https://" + server_base_adress + "/api/OutboundFinancialDocument/documentFormats/{0}"; public HttpStatusCode GetToken(string username, string password) { HttpWebRequest http = (HttpWebRequest)WebRequest.Create(new Uri(TokenUri)); http.Method = "POST"; http.AllowAutoRedirect = true; http.KeepAlive = true; http.PreAuthenticate = false; http.SendChunked = false; Credentials cred = new Credentials() { UserName = username, Password = password }; string content = JsonConvert.SerializeObject(cred); string contentType = "application/json"; http.ContentType = contentType; http.ContentLength = content.Length; SendWebRequest(http, content); var resp = HandleWebResponse(http); if (resp == System.Net.HttpStatusCode.OK) { var json_response = JObject.Parse(_responseText); if (Convert.ToBoolean(json_response("IsValid")) == true) _token = json_response("Data"); } return resp; } public HttpStatusCode SendFileCIUSPT(string filename, string token, string DocType, string IssuerNIF) { string Content; if (string.IsNullOrEmpty(filename)) throw new ArgumentNullException("filename"); try { using (StreamReader xmlfilereader = new StreamReader(filename)) { Content = xmlfilereader.ReadToEnd(); } } catch (Exception ex) { Interaction.MsgBox("Ocorreu o seguinte erro a ler o ficheiro " + filename + Constants.vbNewLine + ex.Message); throw new ArgumentNullException("filename"); } HttpWebRequest http = (HttpWebRequest)WebRequest.Create(new Uri(SendFileUri.Replace("{IssuerNIF}", IssuerNIF).Replace("{DocumentType}", DocType))); http.Method = "POST"; http.UserAgent = "ENIGMA AGENT"; http.Headers.Add("Authorization", "Bearer " + token); http.ContentType = "application/xml"; http.ContentLength = Content.Length; SendWebRequest(http, Content); var resp = HandleWebResponse(http); if (resp == System.Net.HttpStatusCode.OK) _requestID = _responseText; return resp; } public HttpStatusCode GetStatusByRequestID(string ID, string token, string sender) { HttpWebRequest http = (HttpWebRequest)WebRequest.Create(new Uri(GetStatusByRequestIDUri.Replace("{RequestId}", ID))); http.Method = "GET"; http.UserAgent = "ENIGMA AGENT"; http.Headers.Add("Authorization", "Bearer " + token); // SendWebRequest(http, "") var resp = HandleWebResponse(http); if (resp == System.Net.HttpStatusCode.OK) { var json_response = JObject.Parse(_responseText); if (Convert.ToBoolean(json_response("IsValid")) == true) _requestStatus = json_response("Data")("AsyncStatus"); } return resp; } public HttpStatusCode GetStatusByDocumentKey(string ID, string token, string requester, string sender, string type, DateTime data) { } private HttpStatusCode HandleWebResponse(HttpWebRequest http) { try { HttpWebResponse response = (HttpWebResponse)http.GetResponse(); using (var reader = new System.IO.StreamReader(response.GetResponseStream(), true)) { _responseText = reader.ReadToEnd(); } response.Close(); return response.StatusCode; } catch (Exception ex) { Interaction.MsgBox("O servidor devolveu um erro: " + Constants.vbNewLine + ex.Message); } } private void SendWebRequest(HttpWebRequest http, byte[] fileData) { Stream oRequestStream = http.GetRequestStream(); oRequestStream.Write(fileData, 0, fileData.Length); oRequestStream.Flush(); oRequestStream.Close(); } private void SendWebRequest(HttpWebRequest http, string data) { StreamWriter oRequestStream = new StreamWriter(http.GetRequestStream(), Encoding.ASCII); oRequestStream.Write(data); oRequestStream.Close(); } }
    2 points
  2. têm de usar o singdeferred using (PdfReader reader = new PdfReader("_nome_ficheiro")) { using (FileStream fileStream = new FileStream($"_nome_ficheiro_assinado_ouput", FileMode.Create)) { Org.BouncyCastle.X509.X509Certificate[] chain = this.getUserCertificateChain(userBasePath); PdfSigner signer = new PdfSigner(reader, fileStream, new StampingProperties()); IExternalSignatureContainer external = new MyExternalcontainer(signature, chain.ToList()); PdfSigner.SignDeferred(signer.GetDocument(), Signature_Field_Name, fileStream, external); fileStream.Close(); fileStream.Dispose(); } reader.Close(); }
    1 point
×
×
  • Create New...

Important Information

By using this site you accept our Terms of Use and Privacy Policy. We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.