Last active
November 13, 2023 01:15
-
-
Save premy/4773e752da9d63f98edfd44cfe49a3ba to your computer and use it in GitHub Desktop.
Implementação Pix Efi em .NET Framework
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
'precisa adicionar o webapi para poder receber o post no Webhook | |
Sub Application_Start(ByVal sender As Object, ByVal e As EventArgs) | |
System.Net.ServicePointManager.SecurityProtocol = System.Net.SecurityProtocolType.Tls12 | |
RouteTable.Routes.MapHttpRoute("DefaultApi", "api/{controller}/{action}/{id}", New With {Key .id = System.Web.Http.RouteParameter.[Optional] | |
}) | |
GlobalConfiguration.Configuration.Formatters.Clear() | |
GlobalConfiguration.Configuration.Formatters.Add(New JsonMediaTypeFormatter With { | |
.SerializerSettings = New JsonSerializerSettings With { | |
.Formatting = Formatting.None, | |
.DateFormatHandling = DateFormatHandling.IsoDateFormat, | |
.NullValueHandling = NullValueHandling.Include, | |
.ReferenceLoopHandling = ReferenceLoopHandling.Ignore, | |
.ContractResolver = New Newtonsoft.Json.Serialization.CamelCasePropertyNamesContractResolver() | |
} | |
}) | |
End Sub |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<HttpPost()> | |
Public Function WebHook(pix As JObject) As HttpStatusCode | |
Dim txId As String = "txidEmpty" | |
Dim eid As String = "EidEmpty" | |
Dim jsonResulttodict = JsonConvert.DeserializeObject(Of Dictionary(Of String, Object))(Convert.ToString(pix)) | |
Dim errText as String ="" | |
Try | |
'Dim obj As JObject = JObject.Parse(pix) | |
Dim children As JArray = jsonResulttodict("pix") | |
For Each child As JObject In children | |
txId = child("txid") | |
eid = child("endToEndId") | |
Next | |
WriteLog(txId, eid, errText) 'escreva no log e aqui tbm pode incluir o código para atualizar o seu banco de dados | |
Return HttpStatusCode.OK | |
Catch ex As Exception | |
txId = "err" | |
eid = "erro" | |
errText = ex.Message | |
WriteLog(txId, eid, errText) | |
Return HttpStatusCode.BadRequest | |
End Try | |
'Redirect("https://xxx.xxx.com") | |
End Function | |
Private Sub WriteLog(txId As String, eid As String, err As String) | |
Dim FILENAME As String = System.Web.HttpContext.Current.Server.MapPath("~/Webhook.txt") | |
Dim Fs As FileStream = New FileStream(FILENAME, FileMode.Create) | |
Using SwFromFileStream As StreamWriter = New StreamWriter(Fs) | |
SwFromFileStream.Write(txId) | |
SwFromFileStream.Write(vbCrLf) | |
SwFromFileStream.Write(eid) | |
SwFromFileStream.Write(vbCrLf) | |
SwFromFileStream.Write(err) | |
SwFromFileStream.Flush() | |
SwFromFileStream.Close() | |
Fs.Dispose() | |
Fs.Close() | |
End Using | |
End Sub |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Imports System | |
Imports Gerencianet.SDK | |
Imports System.Dynamic | |
Imports Newtonsoft.Json | |
Imports System.Security.Cryptography.X509Certificates | |
Imports RestSharp | |
Imports RestSharp.Authenticators | |
Imports BPL.BOL | |
Imports ZXing | |
Imports System.Drawing | |
Imports System.IO | |
Imports System.Drawing.Imaging | |
Imports Newtonsoft.Json.Linq | |
Imports System.Text.Json | |
Imports System.Text.Json.Serialization | |
Imports System.Net | |
Partial Class TestePix | |
Inherits System.Web.UI.Page | |
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click | |
Dim client_id As String = hdnClientID.Value | |
Dim client_secret As String = hdnClientSecret.Value | |
Dim token As String = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ0eXBlIjoiYWNjZXNzX3Rva2VuIiwiY2xpZW50SWQiOiJDbGllbnRfSWRfNjg5MDBkNjI3OTcxMjk2NWExM2I1NWNhNTMyMjA0YzAwMDc4MThjZiIsImFjY291bnQiOjI3OTU3NCwiYWNjb3VudF9jb2RlIjoiMjJkOTY0NWRlNjY0MmJkMmYxYTJiNDcyODY1ZDE5NzIiLCJzY29wZXMiOlsiY29iLnJlYWQiLCJjb2Iud3JpdGUiLCJjb2J2LnJlYWQiLCJjb2J2LndyaXRlIiwiZ24uYmFsYW5jZS5yZWFkIiwiZ24ucGl4LmV2cC5yZWFkIiwiZ24ucGl4LmV2cC53cml0ZSIsImduLnBpeC5zZW5kLnJlYWQiLCJnbi5yZXBvcnRzLnJlYWQiLCJnbi5yZXBvcnRzLndyaXRlIiwiZ24uc2V0dGluZ3MucmVhZCIsImduLnNldHRpbmdzLndyaXRlIiwiZ24uc3BsaXQucmVhZCIsImduLnNwbGl0LndyaXRlIiwicGF5bG9hZGxvY2F0aW9uLnJlYWQiLCJwYXlsb2FkbG9jYXRpb24ud3JpdGUiLCJwaXgucmVhZCIsInBpeC5zZW5kIiwicGl4LndyaXRlIiwid2ViaG9vay5yZWFkIiwid2ViaG9vay53cml0ZSJdLCJleHBpcmVzSW4iOjM2MDAsImNvbmZpZ3VyYXRpb24iOnsieDV0I1MyNTYiOiJNMi9aS3lsVk9tM2Erc0V4ejNBYTB0cmxXR3phbUhhVUlwbC84aHcwTmJnPSJ9LCJpYXQiOjE2OTgyMDYxNzQsImV4cCI6MTY5ODIwOTc3NH0.mi6whJYhRMy1HEzvTP-nKJcWhqimF_tWxijt5kr87VI" | |
'depois de conseguir autenticar e obter o token, pode colocar o token aqui, pois fica válido por 1 hora e te permite chamar os | |
seguintes métodos sem precisar autenticar de novo: | |
'CriarPix(token) 'cria o pix | |
'GetQrCode(token) 'cria o QrCode do pix | |
' SetWebHook(token) 'cadastrar webhook | |
' CheckWebHook(token) 'consultar webhook | |
'CheckPayment(token) ' verificação direta se o pix foi pago | |
' | |
Try | |
GerarTokenGN(cid, cs) 'gera o token, depois chama o metodo CriarPix que, depois de criar o pix, chama o Metodo GetQRCode | |
'CriarPix(token) 'cria o pix | |
'GetQrCode(token) 'cria o QrCode do pix | |
' SetWebHook(token) 'cadastrar webhook | |
' CheckWebHook(token) 'consultar webhook | |
'CheckPayment(token) ' verificação direta se o pix foi pago | |
Catch ex As Exception | |
ShowMessage(ex.Message) | |
End Try | |
End Sub | |
'acrescentei X509KeyStorageFlags.MachineKeySet na inicilaização do certificado, senão dá erro no servido remoto. | |
'Também é preciso acrescentar System.Net.Http.dll no bin para funcionar no remoto. | |
Public Async Sub GerarTokenGN(ByVal client_id As String, ByVal client_secret As String) | |
Dim certPath As String = Server.MapPath("~/BolsasPixCert.p12") | |
Dim uidCert As X509Certificate2 = New X509Certificate2(certPath, "",X509KeyStorageFlags.MachineKeySet) | |
Dim options = New RestClientOptions("https://pix.api.efipay.com.br") With { | |
.ClientCertificates = New X509CertificateCollection() From { | |
uidCert | |
} | |
} | |
Dim client = New RestClient(options) | |
Dim request = New RestRequest("/oauth/token", Method.Post) | |
request.AddHeader("Authorization", "Basic " & System.Convert.ToBase64String(Encoding.ASCII.GetBytes(String.Format("{0}:{1}", client_id, client_secret)))) | |
request.AddHeader("Content-Type", "application/json") | |
request.AddParameter("application/json", "{""grant_type"":""client_credentials"",""client_id"":""" & client_id & """,""client_secret"":""" & client_secret & """}", ParameterType.RequestBody) | |
Dim restResponse As RestResponse = Await client.ExecuteAsync(request) | |
Dim statusCode As HttpStatusCode = restResponse.StatusCode | |
Dim statusCodeNumber As Integer = CInt(statusCode) | |
Dim response As String = restResponse.Content | |
Label1.Text = response | |
If statusCodeNumber = 200 Then | |
Dim jsonResulttodict = JsonConvert.DeserializeObject(Of Dictionary(Of String, Object))(Convert.ToString(response)) | |
Dim token As String = jsonResulttodict.Item("access_token") 'jsonData.access_token | |
CriarPix(token) | |
Else | |
ShowMessage("Erro credenciais:" & statusCodeNumber) | |
End If | |
End Sub | |
Private Async Sub CriarPix(token As String) | |
Dim client_id As String = hdnClientID.Value | |
Dim client_secret As String = hdnClientSecret.Value | |
Dim certPath As String = Server.MapPath("~/BolsasPixCert.p12") | |
Dim uidCert As X509Certificate2 = New X509Certificate2(certPath, "") | |
Dim options = New RestClientOptions("https://pix.api.efipay.com.br") With { | |
.MaxTimeout = -1, | |
.ClientCertificates = New X509CertificateCollection() From { | |
uidCert | |
} | |
} | |
Dim client = New RestClient(options) | |
Dim request = New RestRequest("/v2/cob", Method.Post) | |
request.AddHeader("Authorization", "Bearer " + token) | |
request.AddHeader("Content-Type", "application/json") | |
Dim body = New With { | |
.calendario = New With { | |
.expiracao = 3600 | |
}, | |
.devedor = New With { | |
.cpf = "52537188266", | |
.nome = "Jake Harper" | |
}, | |
.valor = New With { | |
.original = "0.01" | |
}, | |
.chave = "63b4dcb1-1afb-455a-acd3-edff14a0bxxx", | |
.solicitacaoPagador = "Taxa Inscrição Processo Seletivo" | |
} | |
request.AddParameter("application/json", body, ParameterType.RequestBody) | |
Dim restResponse As RestResponse = Await client.ExecuteAsync(request) | |
Dim statusCode As HttpStatusCode = restResponse.StatusCode | |
Dim statusCodeNumber As Integer = CInt(statusCode) | |
If statusCodeNumber = 201 Then | |
Dim response As String = restResponse.Content | |
Dim jsonResulttodict = JsonConvert.DeserializeObject(Of Dictionary(Of String, Object))(Convert.ToString(response)) | |
Dim locID As String = jsonResulttodict.Item("loc")("id") | |
Dim txID As String = jsonResulttodict.Item("txid") | |
If SaveTxID(txID) Then 'salvar txid no banco de dados | |
Label1.Text = response | |
GetQrCode(token, locID) 'gerar o qr code | |
End If | |
Else | |
ShowMessage("Erro Gerar Pix:" & statusCodeNumber) | |
End If | |
End Sub | |
Private Async Sub GetQrCode(token As String, locID As String) | |
Dim client_id As String = hdnClientID.Value | |
Dim client_secret As String = hdnClientSecret.Value | |
Dim certPath As String = Server.MapPath("~/BolsasPixCert.p12") | |
Dim uidCert As X509Certificate2 = New X509Certificate2(certPath, "") | |
Dim options = New RestClientOptions("https://pix.api.efipay.com.br") With { | |
.MaxTimeout = -1, | |
.ClientCertificates = New X509CertificateCollection() From { | |
uidCert | |
} | |
} | |
Dim client = New RestClient(options) | |
Dim request = New RestRequest("/v2/loc/" & locID & "/qrcode", Method.Get) | |
request.AddHeader("Authorization", "Bearer " + token) | |
Dim restResponse As RestResponse = Await client.ExecuteAsync(request) | |
Dim statusCode As HttpStatusCode = restResponse.StatusCode | |
Dim statusCodeNumber As Integer = CInt(statusCode) | |
If statusCodeNumber = 200 Then | |
Dim response As String = restResponse.Content | |
Dim jsonResulttodict = JsonConvert.DeserializeObject(Of Dictionary(Of String, Object))(Convert.ToString(response)) | |
Image1.ImageUrl = jsonResulttodict.Item("imagemQrcode") 'mostrar qr code na tela | |
txtQrCode.Text = jsonResulttodict.Item("qrcode") | |
Else | |
ShowMessage("Erro QrCode:" & statusCodeNumber) | |
End If | |
End Sub | |
Private Function SaveTxID(txID As String) As Boolean 'salvando o txId no banco de dados | |
Dim pid As Integer = 3 | |
Dim objPremat As New Premat | |
objPremat.PrematID = pid | |
objPremat.TxID = txID | |
Try | |
Premat.SetTxID(objPremat) | |
Return True | |
Catch ex As Exception | |
ShowMessage("Erro ao atualizar Código transação: " & ex.Message) | |
Return False | |
End Try | |
End Function | |
Private Async Sub SetWebHook(token As String) 'cadastrar o webhook | |
Dim client_id As String = hdnClientID.Value | |
Dim client_secret As String = hdnClientSecret.Value | |
Dim certPath As String = Server.MapPath("~/BolsasPixCert.p12") | |
Dim uidCert As X509Certificate2 = New X509Certificate2(certPath, "") | |
Dim options = New RestClientOptions("https://pix.api.efipay.com.br") With { | |
.MaxTimeout = -1, | |
.ClientCertificates = New X509CertificateCollection() From { | |
uidCert | |
} | |
} | |
Dim client = New RestClient(options) | |
Dim request = New RestRequest("/v2/webhook/63b4dcb1-1afb-455a-acd3-edff14a0bxxx", Method.Put) | |
request.AddHeader("Authorization", "Bearer " + token) | |
request.AddHeader("x-skip-mtls-checking", "true") 'host compartilhado | |
Dim body = New With { | |
.webhookUrl = "https://meusite.com.br/api/NotasApi/WebHook" | |
} | |
request.AddParameter("application/json", body, ParameterType.RequestBody) | |
Dim restResponse As RestResponse = Await client.ExecuteAsync(request) | |
Dim statusCode As HttpStatusCode = restResponse.StatusCode | |
Dim statusCodeNumber As Integer = CInt(statusCode) | |
Dim response As String = restResponse.Content | |
Label1.Text = response | |
If statusCodeNumber = 201 Then | |
Label1.Text = "tudo ok" | |
Else | |
ShowMessage("Erro Cadastrar WebHook:" & statusCodeNumber) | |
End If | |
End Sub | |
Private Async Sub CheckWebHook(token As String) | |
Dim client_id As String = hdnClientID.Value | |
Dim client_secret As String = hdnClientSecret.Value | |
Dim certPath As String = Server.MapPath("~/BolsasPixCert.p12") | |
Dim uidCert As X509Certificate2 = New X509Certificate2(certPath, "") | |
Dim options = New RestClientOptions("https://pix.api.efipay.com.br") With { | |
.MaxTimeout = -1, | |
.ClientCertificates = New X509CertificateCollection() From { | |
uidCert | |
} | |
} | |
Dim client = New RestClient(options) | |
Dim request = New RestRequest("/v2/webhook/63b4dcb1-1afb-455a-acd3-edff14a0bxxx", Method.Get) | |
request.AddHeader("Authorization", "Bearer " + token) | |
Dim restResponse As RestResponse = Await client.ExecuteAsync(request) | |
Dim statusCode As HttpStatusCode = restResponse.StatusCode | |
Dim statusCodeNumber As Integer = CInt(statusCode) | |
Dim response As String = restResponse.Content | |
Label1.Text = response | |
If statusCodeNumber = 201 Then | |
Else | |
ShowMessage("Erro Cadastrar WebHook:" & statusCodeNumber) | |
End If | |
End Sub | |
Private Async Sub CheckPayment(token As String) 'verficar pagto direto através do txid | |
Dim client_id As String = hdnClientID.Value | |
Dim client_secret As String = hdnClientSecret.Value | |
Dim certPath As String = Server.MapPath("~/BolsasPixCert.p12") | |
Dim uidCert As X509Certificate2 = New X509Certificate2(certPath, "") | |
Dim options = New RestClientOptions("https://pix.api.efipay.com.br") With { | |
.MaxTimeout = -1, | |
.ClientCertificates = New X509CertificateCollection() From { | |
uidCert | |
} | |
} | |
Dim client = New RestClient(options) | |
Dim request = New RestRequest("/v2/cob/0fa59ef355a94b809cdae74df1fb2030", Method.Get) 'txid | |
request.AddHeader("Authorization", "Bearer " + token) | |
Dim restResponse As RestResponse = Await client.ExecuteAsync(request) | |
Dim statusCode As HttpStatusCode = restResponse.StatusCode | |
Dim statusCodeNumber As Integer = CInt(statusCode) | |
Dim response As String = restResponse.Content | |
Label1.Text = response | |
If statusCodeNumber = 200 Then | |
Dim jsonResulttodict = JsonConvert.DeserializeObject(Of Dictionary(Of String, Object))(Convert.ToString(response)) | |
Label1.Text = jsonResulttodict.Item("status") | |
Else | |
ShowMessage("Erro Consultar Pix:" & statusCodeNumber) | |
End If | |
End Sub | |
Protected Sub ShowMessage(ByVal msg As String) | |
If Not String.IsNullOrEmpty(msg) Then | |
divMsg.Style("padding") = "20px" | |
divMsg.InnerHtml = msg | |
' ClientScript.RegisterStartupScript(Me.GetType(), "hash", "location.hash = '#premat';", True) | |
End If | |
End Sub | |
End Class | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Fiz esses gists, visto que a sdk .NET framework que a Efi disponibiliza no github não tem nada relacionado ao pix. Então tive que ir implementando tudo manualmente: Autenticação, Criar Pix, Criar Qr Qode, Cadastrar WebHook, Consultar WebHook, Configurar o recebimento de Callbacks e Verificação Direta de Status de um pix. E no discord da Efi, tbm não consegui ter ajuda de gente que já fez isto no .NET framework.