Hello! I have been the "jr programmer." in maintaining a virtual store, making changes and improvements to the site through Classic ASP hosted on Windows server, with IIS.
Context : The virtual store uses a "payment gateway" that bridges the site with the forms of payments available in the market, from ticket to credit cards. It has been defined to move from this service to another, and for the site to be able to communicate with the new gateway, it is necessary to adapt the programming, this time the task requires more than I can match at that time.
Originally, this communication starts as follows (.asp):
' URL de acesso ao Gateway
urlCE = "Aqui a URL"
' Instancia o objeto HttpRequest.
Set objSrvHTTP = Server.CreateObject("MSXML2.XMLHTTP.3.0")
' Informe o método e a URL a ser capturada
objSrvHTTP.open "POST", urlCE, false
' Com o método setRequestHeader informamos o cabeçalho HTTP
objSrvHTTP.setRequestHeader "Content-Type", "application/x-www-form-urlencoded"
' O método Send envia a solicitação HTTP e exibe o conteúdo da página
objSrvHTTP.Send(parametros)
The new service specification uses: REST V3 and JSON . I've been able to understand that the way to write (maybe even store) is in different ways between x-www-form-urlencoded
and json
. The support of the service can not help with programming, after all it is the function of the site developer to have this knowledge, but they have some examples.
As the beginning of the solution, I thought of two reasonings:
1) Change the entire structure so that it conforms to json
2) Keep everything as it is and at the moment you are sending the information to the Gateway URL, "convert" the information to json
, and on return, convert to x-www-form-urlencoded
in the original structure.
Anyway, I do not know how to continue this reasoning (programming). I have done some researches like: x-www-form-urlencoded rest v3 , rest v3 asp classic , but nothing that I can totally take advantage of to solve my doubt.
(Meta-Note: I understand that it is not encouraged to make external links in this way, but I am sending in a pastebin without expiration in the corresponding language. >
Here are the examples:
Example vb_request: link
''Code to Send Http JSON POST request
''Get the response from the server
Imports System.Collections.Generic
Imports System.Linq
Imports System.Text
Imports System.Net
Imports System.IO
Module Module1
Sub Main()
Dim JsonData As String = "{""codigoEstabelecimento"":""1000000000000"",""codigoFormaPagamento"":""170"",""transacao"":{""numeroTransacao"":""4"",""valor"":""100"",""valorDesconto"":""0"",""parcelas"":""1"",""urlCampainha"":"",""urlResultado"":""/retorno.php"",""ip"":""127.0.0.1"",""idioma"":""1"",""campoLivre1"":"",""campoLivre2"":"",""campoLivre3"":"",""campoLivre4"":"",""campoLivre5"":"",""dataVencimentoBoleto"":""},""dadosCartao"":{""nomePortador"":""Teste Teste"",""numeroCartao"":""4111111111111111"",""codigoSeguranca"":""125"",""dataValidade"":""11/2019""},""itensDoPedido"":[{""codigoProduto"":""1"",""nomeProduto"":""Produto 1"",""codigoCategoria"":""1"",""nomeCategoria"":""Categoria"",""quantidadeProduto"":""1"",""valorUnitarioProduto"":""100""}],""dadosCobranca"":{""codigoCliente"":""1"",""tipoCliente"":""1"",""nome"":""Cliente Teste"",""email"":""[email protected]"",""dataNascimento"":"""",""sexo"":""F"",""documento"":"",""documento2"":"""",""endereco"":[{""logradouro"":""Rua"",""numero"":""123"",""complemento"":""Casa 1"",""cep"":""17516000"",""bairro"":""Bairro"",""cidade"":""Marilia"",""estado"":""SP"",""pais"":""BR""}],""telefone"":[{""tipoTelefone"":""1"",""ddi"":""55"",""ddd"":""14"",""telefone"":""33011122""}] }}"
Dim myRequest As HttpWebRequest = PostJSON(JsonData)
Console.WriteLine("Response of Request:{0}", GetResponse(myRequest))
Console.ReadKey()
End Sub
Private Function PostJSON(ByVal JsonData As String) As HttpWebRequest
Dim objhttpWebRequest As HttpWebRequest
Try
Dim httpWebRequest = DirectCast(WebRequest.Create("URL DO GATEWAY"), HttpWebRequest)
httpWebRequest.ContentType = "text/json"
httpWebRequest.Method = "POST"
Using streamWriter = New StreamWriter(httpWebRequest.GetRequestStream())
streamWriter.Write(JsonData)
streamWriter.Flush()
streamWriter.Close()
End Using
objhttpWebRequest = httpWebRequest
Catch ex As Exception
Console.WriteLine("Send Request Error[{0}]", ex.Message)
Return Nothing
End Try
Return objhttpWebRequest
End Function
Private Function GetResponse(ByVal httpWebRequest As HttpWebRequest) As String
Dim strResponse As String = "Bad Request:400"
Try
Dim httpResponse = DirectCast(httpWebRequest.GetResponse(), HttpWebResponse)
Using streamReader = New StreamReader(httpResponse.GetResponseStream())
Dim result = streamReader.ReadToEnd()
strResponse = result.ToString()
End Using
Catch ex As Exception
Console.WriteLine("GetResponse Error[{0}]", ex.Message)
Return ex.Message
End Try
Return strResponse
End Function
End Module
C # example: link
var client = new RestClient("URL DO GATEWAY");
var request = new RestRequest(Method.POST);
request.AddHeader("content-type", "application/json");
request.AddHeader("usuario", "USUARIO");
request.AddHeader("senha", "SENHA");
request.AddParameter("application/json","{\"codigoEstabelecimento\":\"1000000000000\",\"codigoFormaPagamento\":\"170\",\"transacao\":{\"numeroTransacao\":\"4\",\"valor\":\"100\",\"valorDesconto\":\"0\",\"parcelas\":\"1\",\"urlCampainha\":\"\",\"urlResultado\":\"retorno.php\",\"ip\":\"127.0.0.1\",\"idioma\":\"1\",\"campoLivre1\":\"\",\"campoLivre2\":\"\",\"campoLivre3\":\"\",\"campoLivre4\":\"\",\"campoLivre5\":\"\",\"dataVencimentoBoleto\":\"\"},\"dadosCartao\":{\"nomePortador\":\"Teste Teste\",\"numeroCartao\":\"4111111111111111\",\"codigoSeguranca\":\"125\",\"dataValidade\":\"11/2019\"},\"itensDoPedido\":[{\"codigoProduto\":\"1\",\"nomeProduto\":\"Produto 1\",\"codigoCategoria\":\"1\",\"nomeCategoria\":\"Categoria\",\"quantidadeProduto\":\"1\",\"valorUnitarioProduto\":\"100\"}],\"dadosCobranca\":{\"codigoCliente\":\"1\",\"tipoCliente\":\"1\",\"nome\":\"Cliente Teste\",\"email\":\"[email protected]\",\"dataNascimento\":\"\",\"sexo\":\"F\",\"documento\":\"\",\"documento2\":\"\",\"endereco\":[{\"logradouro\":\"Rua\",\"numero\":\"123\",\"complemento\":\"Casa 1\",\"cep\":\"17516000\",\"bairro\":\"Bairro\",\"cidade\":\"Marilia\",\"estado\":\"SP\",\"pais\":\"BR\"}],\"telefone\":[{\"tipoTelefone\":\"1\",\"ddi\":\"55\",\"ddd\":\"14\",\"telefone\":\"33011122\"}] }}", ParameterType.RequestBody);
IRestResponse response = client.Execute(request);
I do not know if it's useful, but I also have an XML request debug, with the original code: link
<pedido><dados_pedido siglaidioma="" simbolo_moeda="R$" valor_cambio="1" sigla_idioma="" id_transacao="00001" inicio_transacao="4/13/2018 4:50:06 PM" valor_cupom="0" codigo_cupom="" valor_frete="0,00" valor_subtotal="35,00" valor_total="31,50" peso_total="0,02" opcao_frete="PAC" pais_frete="BR" cep_frete="00000000" forma_pagamento="Boleto" tipo_taxa_adicional="" taxa_adicional="0" num_parcelas="1" logado="1" user_id="[email protected]" ip_usado="XXX.XXX.XXX.XX" status_pedido="finalizado" BoletoTipo="Boleto" valor_desconto="3,50"><produto codigo_produto="2207_c0_t0" codigo_categoria="1" codigo_cor="0" codigo_tamanho="0" nome_produto="Teste" preco_unitario="35,00" desconto="0" peso_unitario="0,020" peso_parcial="0,02" total_parcial="35,00" quantidade_produto="1" grade="0"/></dados_pedido></pedido>
Since I have no contact with programmers, some of the terms I used may not be part of the vocabulary, and I may have misunderstood the meaning. Thank you for your patience! :)