Communication with PagSeguro

9

I need to make an application that communicates with the pagseguro.

In other words, it makes the purchase, I send and then I need to automatically update the bank when I make the payment.

Until I send it to the payer I have a notion. My question is how to know when the customer made the payment. And also how to test this (no need to make payments).

With reference to the Pagename for .Net - Integration and Test Server Controls

I was able to run the with this code:

<form target="pagseguro" method="post"
              action="https://pagseguro.uol.com.br/checkout/checkout.jhtml">
            <input type="hidden" name="email_cobranca"
                   value="[email protected]" />
            <input type="hidden" name="tipo" value="CBR" />
            <input type="hidden" name="moeda" value="BRL" />
            <input type="hidden" name="item_id" value="@Model.ID" />
            <input type="hidden" name="item_descr"
                   value="@Model.Nome" />
            <input type="hidden" name="item_quant" value="1" />
            <input type="hidden" name="item_valor" value="1.00" />
            <input type="image" name="submit"
                   src="https://p.simg.uol.com.br/out/pagseguro/i/botoes/pagamentos/99x61-comprar-assina.gif"alt="Pague com PagSeguro - é rápido, grátis e seguro!" />
        </form>

In the test environment it runs normal, but in the environment of the pagseguro, it fails to receive the post.

My code:

[HttpPost]
    public ActionResult Retorno(FormCollection collection)
    {
        var teste2 = new Teste()
        {
            Cod = "TransacaoID",
            Id = 354684,
            Status = "StatusTransacao"
        };

        AddTeste(teste2); //utilizei para saber se chega até aqui!

        string TransacaoID = collection["TransacaoID"];
        string StatusTransacao = collection["StatusTransacao"];

        var teste = new Teste()
        {
            Cod = TransacaoID,
            Id = 354684,
            Status = StatusTransacao
        };


        AddTeste(teste);

        return null;
    }

Until AddTest (test2), it arrives, but in AddTeste (test), it does not arrive.

* You can not give Debug because I need to upload the project to a valid url in the pagseguro

    
asked by anonymous 07.10.2014 / 14:03

3 answers

11

I've assembled a NuGet package that submits to PagSeguro, based on their GitHub:

  

link

The fonts are here .

Creating an Order

These are the steps for creating a basic order. The other examples should be considered using the example below as a basis.

    // Essa variável define se é o ambiente de teste ou produção.
    const bool isSandbox = true;

    EnvironmentConfiguration.ChangeEnvironment(isSandbox);

    try
    {
        var credentials = PagSeguroConfiguration.Credentials(isSandbox);

        // Instanciar uma nova requisição de pagamento
        var payment = new PaymentRequest {Currency = Currency.Brl};

        // Adicionar produtos
        payment.Items.Add(new Item("0001", "Notebook Prata", 1, 2430.00m));
        payment.Items.Add(new Item("0002", "Notebook Rosa", 2, 150.99m));

        // Código que identifica o pagamento
        payment.Reference = "REF1234";

        // Informações de entrega
        payment.Shipping = new Shipping
        {
            ShippingType = ShippingType.Sedex,
            Cost = 10.00m,
            Address = new Address(
                "BRA",
                "SP",
                "Sao Paulo",
                "Jardim Paulistano",
                "01452002",
                "Av. Brig. Faria Lima",
                "1384",
                "5o andar"
                )
        };

        // Informações do remetente
        payment.Sender = new Sender(
            "Joao Comprador", 
            "[email protected]", 
            new Phone("11", "56273440")
        );

        // URL a redirecionar o usuário após pagamento
        payment.RedirectUri = new Uri("http://www.lojamodelo.com.br");

        // Informações extras para identificar o pagamento.
        // Essas informações são livres para adicionar o que for necessário.
        payment.AddMetaData(MetaDataItemKeys.GetItemKeyByDescription("CPF do passageiro"), "123.456.789-09", 1);
        payment.AddMetaData("PASSENGER_PASSPORT", "23456", 1);

        // Outra forma de definir os parâmetros de pagamento.
        payment.AddParameter("senderBirthday", "07/05/1980");
        payment.AddIndexedParameter("itemColor", "verde", 1);
        payment.AddIndexedParameter("itemId", "0003", 3);
        payment.AddIndexedParameter("itemDescription", "Mouse", 3);
        payment.AddIndexedParameter("itemQuantity", "1", 3);
        payment.AddIndexedParameter("itemAmount", "200.00", 3);

        var senderCpf = new SenderDocument(Documents.GetDocumentByType("CPF"), "12345678909"); 
        payment.Sender.Documents.Add(senderCpf);

        var paymentRedirectUri = payment.Register(credentials);

        Console.WriteLine("URL do pagamento : " + paymentRedirectUri);
        Console.ReadKey();
    }
    catch (PagSeguroServiceException exception)
    {
        Console.WriteLine(exception.Message + "\n");

        foreach (var element in exception.Errors)
        {
            Console.WriteLine(element + "\n");
        }
        Console.ReadKey();
    }

Creating Request with Subscription

Here is a signature launch inside a normal sale, which asks the user for approval.

        var now = DateTime.Now;

        payment.PreApproval = new PreApproval
        {
            Charge = Charge.Manual,
            Name = "Seguro contra roubo do Notebook",
            AmountPerPayment = 100.00m,
            MaxAmountPerPeriod = 100.00m,
            Details = string.Format("Todo dia {0} será cobrado o valor de {1} referente ao seguro contra roubo do Notebook.", now.Day, payment.PreApproval.AmountPerPayment.ToString("C2")),
            Period = Period.Monthly,
            DayOfMonth = now.Day,
            InitialDate = now,
            FinalDate = now.AddMonths(6),
            MaxTotalAmount = 600.00m,
            MaxPaymentsPerPeriod = 1
        };

Cancel Subscription

    // Tendo um código de transação, insira no segundo argumento.
    var cancelResult = PreApprovalService.CancelPreApproval(credentials, "3DFAD3123412340334A96F9136C38804");

Check Status of a Transaction

    // Transação Normal
    var transaction = NotificationService.CheckTransaction(credentials, "766B9C-AD4B044B04DA-77742F5FA653-E1AB24", false);

    // Transação Tipo Assinatura
    var preApprovalTransaction = NotificationService.CheckTransaction(credentials, "3DFAD3123412340334A96F9136C38804", true);

Search Transaction by Transaction Code

    var preApprovalTransaction = TransactionSearchService.SearchByCode(credentials, "3DFAD3123412340334A96F9136C38804", true);

Search Dates Range Transactions

        // Definindo a data de ínicio da consulta 
        var initialDate = new DateTime(2014, 07, 01, 08, 50, 0);

        // Definindo a data de término da consulta
        var finalDate = DateTime.Now.AddHours(-5);

        // Definindo o número máximo de resultados por página
        const int maxPageResults = 10;

        // Definindo o número da página
        const int pageNumber = 1;

        // Realizando a consulta
        var result =
            TransactionSearchService.SearchByDate(
                credentials,
                initialDate,
                finalDate,
                pageNumber,
                maxPageResults,
                false);

        if (result.Transactions.Count <= 0)
        {
            Console.WriteLine("Nenhuma transação");
        }

        if (result.PreApprovals.Count <= 0)
        {
            Console.WriteLine("Nenhuma assinatura");
        }

        foreach (var transaction in result.Transactions)
        {
            Console.WriteLine("Começando listagem de transações - \n");
            Console.WriteLine(transaction.ToString());
            Console.WriteLine(" - Terminando listagem de transações ");
        }

        foreach (var transaction in result.PreApprovals)
        {
            Console.WriteLine("Começando listagem de assinaturas - \n");
            Console.WriteLine(transaction.ToString());
            Console.WriteLine(" - Terminando listagem de assinaturas ");
        }
    
16.10.2014 / 05:55
5

Felipe,

You can use PagSeguro TestServer for testing purposes. To know when the user made the payment there is the callback URL that you set up which will be the address that he should return if he has made the transaction.

Follow the link below to explain how to configure and use the local server. A friend used it on TCC and was able to simulate the real environment.

Pagename for .Net - Integration and Test Server Controls

    
07.10.2014 / 14:12
2

Felipe Pag Insurance advises in their own blog the creation of payments of R $ 1.00 (if not mistaken) to be paid with a ticket! This will already generate a status change on their system that your app can receive and test.

The first thing I advise you to do is to verify that you are correctly setting up the return url of your site, because it is in you that you will make all the magic happen, if the address is not well configured on the platform of the Secure Pag you will not receive the answers for updating your system.

    
12.10.2014 / 15:41