Error When Receiving POST in Paysafecard

Asked

Viewed 585 times

2

I have a platform that makes purchases via Pagseguro form. The problem is that I’m only receiving the POST in which the StatusTransacao is as "Waiting for Payment", ie in the case of a billet generated. If the purchase was approved, I do not receive POST and on the platform of Pagseguro visualize an error 500.

Follow my code below:

[HttpPost]
        public ActionResult RetornoPagamento(FormCollection collection)
        {
            string Token = "";
            string Pagina = "https://pagseguro.uol.com.br/pagseguro-ws/checkout/NPI.jhtml";
            string Dados = System.Web.HttpContext.Current.Request.Form.ToString() + "&Comando=validar" + "&Token=" + Token;

            System.Net.HttpWebRequest req = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(Pagina);

            req.Method = "POST";
            req.ContentLength = Dados.Length;
            req.ContentType = "application/x-www-form-urlencoded";

            System.IO.StreamWriter stOut = new System.IO.StreamWriter(req.GetRequestStream(), System.Text.Encoding.GetEncoding("ISO-8859-1"));
            stOut.Write(Dados);
            stOut.Close();

            System.IO.StreamReader stIn = new System.IO.StreamReader(req.GetResponse().GetResponseStream(), System.Text.Encoding.GetEncoding("ISO-8859-1"));
            string Result = stIn.ReadToEnd();
            stIn.Close();

            if (Result == "VERIFICADO")
            {

                SqlConnection MinhaConexao = new SqlConnection(ConfigurationManager.ConnectionStrings["BancoDados"].ConnectionString);
                MinhaConexao.Open();
                string query = "";

                CursoAlunoAplicacao bdCursoAluno;
                bdCursoAluno = CursoAlunoAplicacaoConstrutor.CursoAlunoAplicacaoEF();
                var VerificarCursoAluno = bdCursoAluno.ListarTodos().Where(x => x.Transacao == collection["TransacaoID"]);

                if (VerificarCursoAluno.Count() >= 1)
                {
                    if (collection["StatusTransacao"] == "Aprovado")
                    {
                        query = "UPDATE CursoRapido_CursoAluno SET Pagamento = 1 WHERE Transacao = '" + collection["TransacaoID"] + "'";
                    }
                }
                else
                {
                    if (collection["StatusTransacao"] == "Aprovado")
                    {
                        query = "INSERT INTO CursoRapido_CursoAluno (Pagamento,Aluno_ID,Cursos_ID,Transacao) VALUES (1, '" + collection["Referencia"] + "'," + collection["ProdID_1"] + ",'" + collection["TransacaoID"] + "')";
                    }
                    else
                    {
                        query = "INSERT INTO CursoRapido_CursoAluno (Pagamento,Aluno_ID,Cursos_ID,Transacao) VALUES (0, '" + collection["Referencia"] + "'," + collection["ProdID_1"] + ",'" + collection["TransacaoID"] + "')";
                    }
                }

                SqlCommand comando = new SqlCommand(query, MinhaConexao);
                comando.ExecuteNonQuery();
                MinhaConexao.Close();
            }

            return View();
        }

        public ActionResult RetornoPagamento()
        {
            string url = System.Web.HttpContext.Current.Request.Url.AbsoluteUri;
            var ID_Transacao = url.Substring(url.IndexOf("ID_Transacao="));
            ID_Transacao = ID_Transacao.Replace("ID_Transacao=", "");
            ID_Transacao = ID_Transacao.Replace("-", "");

            CursoAlunoAplicacao bdCursoAluno;
            bdCursoAluno = CursoAlunoAplicacaoConstrutor.CursoAlunoAplicacaoEF();

            if (bdCursoAluno.ListarTodos().Where(x => x.Transacao == ID_Transacao).Count() > 0)
            {
                var IDAtual = System.Web.HttpContext.Current.User.Identity.Name;

                var CursoComprado = bdCursoAluno.ListarTodos().Where(x => x.Aluno.ID == int.Parse(IDAtual)).LastOrDefault();
                string Parametro = IDAtual + "-" + CursoComprado.Cursos.ID;

                return RedirectToAction("CursoDetalhe", new { id = Parametro });
            }

            else
            {
                return RedirectToAction("AguardandoPagamento");
            }

        }
  • Because as it is a simple application and even without cart, I thought it would be easier so

  • Apparently it is, but I can see that you have no way to make the mistake. See this answer to learn how to use the package.

  • I visualized the link you gave me but did not find there the way to work with the return. Sending is ok, is working in my current code. I just don’t understand why the POST error 500 when trying to access my Feedback action

  • I can’t remember, but I think it’s in the object payment. I’ll check for you when I can

  • Okay, I’ll be waiting. Thank you.

  • @Rafaelbarbosa just to make sure you understand how Pagseguro works, the POST it sends to your server is server-to-server communication, it doesn’t work on the "client" side. Have you tried the Pagseguro test environment?

  • @Guilhermenascimento I understand this, so I have my Return method with [Httppost], to receive the post confirmation POST and execute my query. The problem is that I only receive POST at the time the purchase is made via boleto.

  • @Rafaelbarbosa was just to be sure :) tell me are you using the test environment? I’ll see if I can test your code today

  • @Guilhermenascimento Ah yes. So, to be honest I used the test environment until I received something positive, which in the case was the interaction I got when I generated boleto, after that I continued in stubbornness from the point that my code was communicating with Pagseguro.

Show 5 more comments

2 answers

2


I sent an email with each situation of the process of purchase and response of the Pagseguro server.

With that I found that the problem was with the parole if (Result == "VERIFICADO"). Now the problem is solved.

Follow the code below:

 [HttpPost]
        public ActionResult RetornoPagamento(FormCollection collection)
        {
            string Mensagem;
            Mensagem = "Entrou";
            Helpers.Email enviarEmail = new Helpers.Email();
            enviarEmail.Enviar(Mensagem);


            string Token = "";
            string Pagina = "https://pagseguro.uol.com.br/pagseguro-ws/checkout/NPI.jhtml";
            string Dados = System.Web.HttpContext.Current.Request.Form.ToString() + "&Comando=validar" + "&Token=" + Token;
            enviarEmail.Enviar(Dados);

            System.Net.HttpWebRequest req = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(Pagina);

            req.Method = "POST";
            req.ContentLength = Dados.Length;
            req.ContentType = "application/x-www-form-urlencoded";

            System.IO.StreamWriter stOut = new System.IO.StreamWriter(req.GetRequestStream(), System.Text.Encoding.GetEncoding("ISO-8859-1"));
            stOut.Write(Dados);
            stOut.Close();

            System.IO.StreamReader stIn = new System.IO.StreamReader(req.GetResponse().GetResponseStream(), System.Text.Encoding.GetEncoding("ISO-8859-1"));
            string Result = stIn.ReadToEnd();
            stIn.Close();


                SqlConnection MinhaConexao = new SqlConnection(ConfigurationManager.ConnectionStrings["BancoDados"].ConnectionString);
                MinhaConexao.Open();
                string query = "";

                CursoAlunoAplicacao bdCursoAluno;
                bdCursoAluno = CursoAlunoAplicacaoConstrutor.CursoAlunoAplicacaoEF();
                var VerificarCursoAluno = bdCursoAluno.ListarTodos().Where(x => x.Transacao == collection["TransacaoID"]);

                if (VerificarCursoAluno.Count() >= 1)
                {
                    Mensagem = "Já existe";
                    enviarEmail.Enviar(Mensagem);
                    if (collection["StatusTransacao"] == "Aprovado")
                    {
                        Mensagem = "Aprovado";
                        enviarEmail.Enviar(Mensagem);
                        query = "UPDATE CursoRapido_CursoAluno SET Pagamento = 1 WHERE Transacao = '" + collection["TransacaoID"] + "'";
                    }
                }
                else
                {
                    Mensagem = "Não existe ainda";
                    enviarEmail.Enviar(Mensagem);
                    if (collection["StatusTransacao"] == "Aprovado")
                    {
                        Mensagem = "Aprovado Boleto";
                        enviarEmail.Enviar(Mensagem);
                        query = "UPDATE CursoRapido_CursoAluno SET Pagamento = 1 WHERE Transacao = '" + collection["TransacaoID"] + "'";
                    }
                    else if (collection["StatusTransacao"] == "Aguardando Pagto" || collection["StatusTransacao"] == "Em Análise")
                    {
                        Mensagem = "Boleto Gerado";
                        enviarEmail.Enviar(Mensagem);
                        query = "INSERT INTO CursoRapido_CursoAluno (Pagamento,Aluno_ID,Cursos_ID,Transacao) VALUES (0, '" + collection["Referencia"] + "'," + collection["ProdID_1"] + ",'" + collection["TransacaoID"] + "')";
                    }
                }

                SqlCommand comando = new SqlCommand(query, MinhaConexao);
                comando.ExecuteNonQuery();
                MinhaConexao.Close();
            return View();
        }

        public ActionResult RetornoPagamento()
        {
            string url = System.Web.HttpContext.Current.Request.Url.AbsoluteUri;
            var ID_Transacao = url.Substring(url.IndexOf("ID_Transacao="));
            ID_Transacao = ID_Transacao.Replace("ID_Transacao=", "");
            ID_Transacao = ID_Transacao.Replace("-", "");

            CursoAlunoAplicacao bdCursoAluno;
            bdCursoAluno = CursoAlunoAplicacaoConstrutor.CursoAlunoAplicacaoEF();

            if (bdCursoAluno.ListarTodos().Where(x => x.Transacao == ID_Transacao).Count() > 0)
            {
                var IDAtual = System.Web.HttpContext.Current.User.Identity.Name;

                var CursoComprado = bdCursoAluno.ListarTodos().Where(x => x.Aluno.ID == int.Parse(IDAtual)).LastOrDefault();
                string Parametro = IDAtual + "-" + CursoComprado.Cursos.ID;

                return RedirectToAction("CursoDetalhe", new { id = Parametro });
            }

            else
            {
                return RedirectToAction("AguardandoPagamento");
            }

        }

2

Rafael, I suggest you generate a new Token as it may cause problems in the application security. Also do not disclose your website address because the application does not check if it is CHECKED then can easily receive an external POST.

  • I updated my answer and removed the Token, there really had not attacked me to that. On the issue of disclosure, I checked the entire question to ensure there were no links to my platform. Previously I had already solved my question related to the question, however, as it helped me to think about security issues and counting on the fact that the bonus can not be canceled, I will be granting you.

  • Okay, I appreciate it.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.