protected void Page_Load(object sender, EventArgs e) { // envia email para gestores avisando sobre nova entrega EnviarEmail(); //dados da solicitação string chkvalorstr = Request.QueryString["v1"]; decimal chkvalor = Convert.ToDecimal(chkvalorstr); Session["OSId"] = Request.QueryString["v2"]; bool isSandbox = true; EnvironmentConfiguration.ChangeEnvironment(isSandbox); // Instantiate a new payment request PaymentRequest payment = new PaymentRequest(); // Sets the currency payment.Currency = Currency.Brl; // Add an item for this payment request payment.Items.Add(new Item("0001", "Servico de Motoboy", 1, chkvalor)); // Sets a reference code for this payment request, it is useful to identify this payment in future notifications. payment.Reference = "Cli_" + Session["UserID"].ToString(); payment.AddParameter("shippingAddressRequired", "false"); // Sets the url used by PagSeguro for redirect user after ends checkout process payment.RedirectUri = new Uri("http://logvai01.azurewebsites.net/RedirectRetorno.aspx"); // Add and remove groups and payment methods List <string> accept = new List <string>(); accept.Add(ListPaymentMethodNames.DebitoItau); payment.AcceptPaymentMethodConfig(ListPaymentMethodGroups.CreditCard, accept); try { //faz requisição de check-out e aguarda retorno com link para pagamento AccountCredentials credentials = new AccountCredentials("*****@*****.**", "C1BF7C4BE89A481A8C215B3275F41973"); Uri paymentRedirectUri = payment.Register(credentials); string urlpagam = paymentRedirectUri.ToString(); //encaminha usuário para pagina de pagamento (ambiente pagseguro) Response.Write("<script>self.parent.location.href='" + urlpagam + "';</script>"); } catch (PagSeguroServiceException exception) { Response.Write("<script>alert('Tente Novamente! Motivo: " + exception.Message + "');</script>"); } }
static void RegisterExample() { PaymentRequest paymentRequest = new PaymentRequest(); // Preencher propriedades da requisição do pagamento aqui bool isSandbox = false; EnvironmentConfiguration.ChangeEnvironment(isSandbox); AccountCredentials credentials = PagSeguroConfiguration.Credentials(isSandbox); // Criando o código de requisição de pagamento // e obtendo a URL da página de pagamento // do PagSeguro Uri paymentRedirectUri = paymentRequest.Register(credentials); //Response.Redirect(paymentRedirectUri.ToString()); }
public IActionResult PostTransactions([FromBody] TransactionDto transaction) { if (transaction?.UserId == null || transaction.Itens == null) { return(BadRequest(ModelState)); } try { const bool isSandbox = true; EnvironmentConfiguration.ChangeEnvironment(isSandbox); var credentials = PagSeguroConfiguration.Credentials(isSandbox); var payment = new PaymentRequest { Currency = Currency.Brl }; var id = 1; foreach (var item in transaction.Itens) { var paddedId = id.ToString().PadLeft(4, '0'); payment.Items.Add(new Item(paddedId, item.ItemDescription, item.ItemQuantity, (decimal)item.ItemAmount)); id += 1; } payment.RedirectUri = new Uri("http://localhost:3000/carrinho?transaction_id="); var paymentRedirectUri = payment.Register(credentials); var code = paymentRedirectUri.ToString().Substring(paymentRedirectUri.ToString().IndexOf("code=", StringComparison.Ordinal)).Remove(0, 5); SaveTransaction(transaction, code); return(Ok(paymentRedirectUri)); } catch (PagSeguroServiceException exception) { return(StatusCode(500, exception.Errors)); } catch (Exception ex) { return(StatusCode(500, ex.Message)); } }
/// <summary> /// Quando um fornecedor vier convidado do VendorList, será direcionado para essa página. /// </summary> /// <returns></returns> //[ActionName("Convite")] //public ActionResult Index(string chaveUrl) //{ // try // { // int id = _conviteAppService.DescriptografarLinkConvite(chaveUrl); // Categoria conviteModel = _conviteAppService.BuscarConvite(id); // ConviteVM model = ConviteVM.ToViewModel(conviteModel); // //TODO: Gravar dados no banco de fornecedores convidados pelo VendorList // return View("Index", model); // } // catch (Exception ex) // { // return HttpNotFound(); // } //} public ActionResult PagSeguro() { Criptografia descripto = new Criptografia(EnumCripto.Criptografar, "Pln=1&Sol=12346", "r10X310y"); string planoEscolhido = string.Format("REF_{0}", descripto.Resultado); PaymentRequest payment = new PaymentRequest(); payment.Items.Add(new Item("0001", "Plano_1", 1, 2430.00m)); payment.Currency = Currency.Brl; payment.Shipping = new Shipping(); payment.Shipping.ShippingType = ShippingType.NotSpecified; payment.Reference = planoEscolhido; AccountCredentials credentials = new AccountCredentials( "*****@*****.**", "86D588A7611E48FABA6125B049503F5F" ); Uri paymentRedirectUri = payment.Register(credentials); return(Redirect(paymentRedirectUri.AbsoluteUri)); //return View(); }
public ActionResult Adesao(string id_pagseguro) { try { string planoEscolhido = string.Format("REF_{0}", 1); PaymentRequest payment = new PaymentRequest(); payment.Items.Add(new Item("0001", "WebForLink", 1, 2800.00m)); payment.Currency = Currency.Brl; payment.Shipping = new Shipping(); payment.Shipping.ShippingType = ShippingType.NotSpecified; payment.Reference = planoEscolhido; AccountCredentials credentials = new AccountCredentials( "*****@*****.**", "86D588A7611E48FABA6125B049503F5F" ); Uri paymentRedirectUri = payment.Register(credentials); return(Redirect(paymentRedirectUri.AbsoluteUri)); } catch (Exception ex) { Log.Error(ex); } return(RedirectToAction("Index")); }
static void Main(string[] args) { bool isSandbox = true; EnvironmentConfiguration.ChangeEnvironment(isSandbox); try { AccountCredentials credentials = PagSeguroConfiguration.Credentials(isSandbox); // Instantiate a new payment request PaymentRequest payment = new PaymentRequest(); // Sets the currency payment.Currency = Currency.Brl; // Add an item for this payment request payment.Items.Add(new Item("0001", "Notebook Prata", 1, 2430.00m)); // Add another item for this payment request payment.Items.Add(new Item("0002", "Notebook Rosa", 2, 150.99m)); // Sets a reference code for this payment request, it is useful to identify this payment in future notifications. payment.Reference = "REF1234"; // Sets shipping information for this payment request payment.Shipping = new Shipping(); payment.Shipping.ShippingType = ShippingType.Sedex; //Passando valor para ShippingCost payment.Shipping.Cost = 10.00m; payment.Shipping.Address = new Address( "BRA", "SP", "Sao Paulo", "Jardim Paulistano", "01452002", "Av. Brig. Faria Lima", "1384", "5o andar" ); // Sets your customer information. payment.Sender = new Sender( "Joao Comprador", "*****@*****.**", new Phone("11", "56273440") ); // Sets the url used by PagSeguro for redirect user after ends checkout process payment.RedirectUri = new Uri("http://www.lojamodelo.com.br"); // Add checkout metadata information payment.AddMetaData(MetaDataItemKeys.GetItemKeyByDescription("CPF do passageiro"), "123.456.789-09", 1); payment.AddMetaData("PASSENGER_PASSPORT", "23456", 1); // Another way to set checkout parameters 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); SenderDocument senderCPF = new SenderDocument(Documents.GetDocumentByType("CPF"), "12345678909"); payment.Sender.Documents.Add(senderCPF); Uri paymentRedirectUri = payment.Register(credentials); Console.WriteLine("URL do pagamento : " + paymentRedirectUri); Console.ReadKey(); } catch (PagSeguroServiceException exception) { Console.WriteLine(exception.Message + "\n"); foreach (ServiceError element in exception.Errors) { Console.WriteLine(element + "\n"); } Console.ReadKey(); } }
protected void LinkButtonHistorico_Click1(object sender, EventArgs e) { /// EXERCICIO: /// Conclua a integração com o PagSeguro /// EXERCICIO: /// Implemente a integração com o Paypal //Use global configuration PagSeguroConfiguration.UrlXmlConfiguration = "PagSeguroConfig.xml"; bool isSandbox = false; EnvironmentConfiguration.ChangeEnvironment(isSandbox); // Instantiate a new payment request PaymentRequest payment = new PaymentRequest(); // Sets the currency payment.Currency = Currency.Brl; List <VendaDetalheDTO> ListaVenda = VendaAtual.ListaVendaDetalhe; foreach (VendaDetalheDTO objVenda in ListaVenda) { payment.Items.Add(new Item(objVenda.Produto.CodigoInterno.ToString(), objVenda.Produto.Nome, 1, objVenda.Produto.ValorVenda.Value)); } // Sets a reference code for this payment request, it is useful to identify this payment in future notifications. payment.Reference = "REF1234"; // Sets shipping information for this payment request payment.Shipping = new Shipping(); payment.Shipping.ShippingType = ShippingType.Sedex; //Passando valor para ShippingCost payment.Shipping.Cost = 10.00m; payment.Shipping.Address = new Address( "BRA", "SP", "Sao Paulo", "Jardim Paulistano", "01452002", "Av. Brig. Faria Lima", "1384", "5o andar" ); // Sets your customer information. payment.Sender = new Sender( "Joao Comprador", "*****@*****.**", new Phone("11", "56273440") ); SenderDocument document = new SenderDocument(Documents.GetDocumentByType("CPF"), "12345678909"); payment.Sender.Documents.Add(document); // Sets the url used by PagSeguro for redirect user after ends checkout process payment.RedirectUri = new Uri("http://www.t2ti.com"); // Add installment without addition per payment method payment.AddPaymentMethodConfig(PaymentMethodConfigKeys.MaxInstallmentsNoInterest, 6, PaymentMethodGroup.CreditCard); // Add and remove groups and payment methods List <string> accept = new List <string>(); accept.Add(ListPaymentMethodNames.DebitoItau); accept.Add(ListPaymentMethodNames.DebitoHSBC); payment.AcceptPaymentMethodConfig(ListPaymentMethodGroups.CreditCard, accept); List <string> exclude = new List <string>(); exclude.Add(ListPaymentMethodNames.Boleto); payment.ExcludePaymentMethodConfig(ListPaymentMethodGroups.Boleto, exclude); try { /// Create new account credentials /// This configuration let you set your credentials from your ".cs" file. AccountCredentials credentials = new AccountCredentials("*****@*****.**", "01D9sdfg5446s5d4g6sd5f4gA48F"); /// @todo with you want to get credentials from xml config file uncommend the line below and comment the line above. //AccountCredentials credentials = PagSeguroConfiguration.Credentials(isSandbox); Uri paymentRedirectUri = payment.Register(credentials); Response.Redirect(paymentRedirectUri.ToString()); //Console.WriteLine("URL do pagamento : " + paymentRedirectUri); //Console.ReadKey(); } catch (PagSeguroServiceException exception) { Console.WriteLine(exception.Message + "\n"); foreach (ServiceError element in exception.Errors) { Console.WriteLine(element + "\n"); } Console.ReadKey(); } }
private string CreatePayment(Order order) { bool isSandbox = false; EnvironmentConfiguration.ChangeEnvironment(isSandbox); try { AccountCredentials credentials = PagSeguroConfiguration.Credentials(isSandbox); PaymentRequest payment = new PaymentRequest(); payment.Currency = Currency.Brl; foreach (var item in order.OrderItens) { var itemName = string.Format("{0}-{1} | {2} ", item.Product.Name, item.Product.ComplementName, item.Size.Code); payment.Items.Add(new Item(item.Product.Id.ToString(), itemName, item.Quantity, item.Product.Price.GetSallingPrice())); } var total = payment.Items.Sum(c => (c.Amount * c.Quantity)); if (order.PromoCode != null) { payment.ExtraAmount = -order.PromoCode.GetDiscount(total); } // Sets a reference code for this payment request, it is useful to identify this payment in future notifications. payment.Reference = order.Id.ToString(); // Sets shipping information for this payment request payment.Shipping = new Shipping(); payment.Shipping.ShippingType = ShippingType.NotSpecified; //Passando valor para ShippingCost payment.Shipping.Cost = 0.00m; payment.Shipping.Address = new Uol.PagSeguro.Domain.Address( "BRA", order.Address.City.State.Uf, order.Address.City.Name, order.Address.Neighbornhood, order.Address.ZipCode, order.Address.Street, order.Address.Number, order.Address.Complement ); // Sets your customer information. payment.Sender = new Sender( "", order.User.Email, new Uol.PagSeguro.Domain.Phone(order.User.AreaCode, order.User.Number) ); // Sets the url used by PagSeguro for redirect user after ends checkout process payment.RedirectUri = new Uri("http://www.estilofc.com.br/Order/Done"); SenderDocument senderCPF = new SenderDocument(Documents.GetDocumentByType("CPF"), order.User.CpfNoMask()); payment.Sender.Documents.Add(senderCPF); Uri paymentRedirectUri = payment.Register(credentials); return(paymentRedirectUri.ToString()); } catch (PagSeguroServiceException exception) { stockService.Add(order); throw exception; } }
public string CriarPagamento(PagSeguroModel pagSeguro) { EnvironmentConfiguration.ChangeEnvironment(isSandbox); // Instantiate a new payment request PaymentRequest payment = new PaymentRequest(); var itemParam = new ParameterItem("encoding", "UTF-8"); payment.Parameter.Items.Add(itemParam); // Sets the currency payment.Currency = Currency.Brl; foreach (var item in pagSeguro.produtos) { // Add an item for this payment request payment.Items.Add(new Item(item.id, RemoverAcentos(item.descricao), item.qtde, item.unitario)); } // Sets a reference code for this payment request, it is useful to identify this payment in future notifications. payment.Reference = pagSeguro.paymontReference; // Sets shipping information for this payment request payment.Shipping = new Shipping(); payment.Shipping.ShippingType = pagSeguro.shippingType;// ShippingType.Sedex; //Passando valor para ShippingCost payment.Shipping.Cost = pagSeguro.shippingCost; payment.Shipping.Address = new Address(pagSeguro.enderecoEntrega.pais, pagSeguro.enderecoEntrega.estado, pagSeguro.enderecoEntrega.cidade, pagSeguro.enderecoEntrega.bairro, pagSeguro.enderecoEntrega.cep, pagSeguro.enderecoEntrega.endereco, pagSeguro.enderecoEntrega.numero, pagSeguro.enderecoEntrega.complemento); // Sets your customer information. payment.Sender = new Sender(pagSeguro.cliente.nome, pagSeguro.cliente.email, new Phone(pagSeguro.cliente.ddd, pagSeguro.cliente.telefone)); SenderDocument document = new SenderDocument(Documents.GetDocumentByType("CPF"), pagSeguro.cliente.documento); payment.Sender.Documents.Add(document); // Sets the url used by PagSeguro for redirect user after ends checkout process payment.RedirectUri = new Uri("http://google.com"); // Add checkout metadata information //payment.AddMetaData(MetaDataItemKeys.GetItemKeyByDescription("CPF do passageiro"), "086.111.629-19", 1); //payment.AddMetaData("PASSENGER_PASSPORT", "23456", 1); // Another way to set checkout parameters //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); // Add discount per payment method //payment.AddPaymentMethodConfig(PaymentMethodConfigKeys.DiscountPercent, 5.00, PaymentMethodGroup.CreditCard); // Add installment without addition per payment method //payment.AddPaymentMethodConfig(PaymentMethodConfigKeys.MaxInstallmentsNoInterest, 6, PaymentMethodGroup.CreditCard); // Add installment limit per payment method //payment.AddPaymentMethodConfig(PaymentMethodConfigKeys.MaxInstallmentsLimit, 8, PaymentMethodGroup.CreditCard); // Add and remove groups and payment methods List <string> accept = new List <string>(); accept.Add(ListPaymentMethodNames.DebitoBradesco); accept.Add(ListPaymentMethodNames.DebitoBancoDoBrasil); accept.Add(ListPaymentMethodNames.Boleto); payment.AcceptPaymentMethodConfig(ListPaymentMethodGroups.CreditCard, accept); //List<string> exclude = new List<string>(); //exclude.Add(ListPaymentMethodNames.Boleto); //payment.ExcludePaymentMethodConfig(ListPaymentMethodGroups.Boleto, exclude); try { /// Create new account credentials /// This configuration let you set your credentials from your ".cs" file. //AccountCredentials credentials = new AccountCredentials("*****@*****.**", "B8F8E56F7F1F4D658427A25683472131"); /// @todo with you want to get credentials from xml config file uncommend the line below and comment the line above. AccountCredentials credentials = PagSeguroConfiguration.Credentials(isSandbox); Uri paymentRedirectUri = payment.Register(credentials); return(paymentRedirectUri.AbsoluteUri); } catch { throw; } }
public IHttpActionResult Checkout(AddressDto addressDto) { if (!ModelState.IsValid) { return(BadRequest("Dados inválidos!")); } // Check for empty cart if (!ActiveCart.Products.Any()) { return(NotFound()); } // Check for valid stock foreach (var cartProduct in ActiveCart.Products) { if (cartProduct.Quantity > cartProduct.Product.NumberInStock) { return(BadRequest($"Quantidade no carrinho é maior do que o estoque ({cartProduct.Product.Name})")); } } // PagSeguro Logic var address = GetAddress(addressDto); if (address == null) { return(BadRequest("CEP inválido!")); } var user = _userManager.FindById(_userId); var paymentRequest = new PaymentRequest { Currency = Currency.Brl, Sender = new Sender( $"{user.FirstName} {user.LastName}", "*****@*****.**", new Phone( Regex.Match(user.PhoneNumber, @"^\((.*?)\)").Value.Trim('(', ')'), user.PhoneNumber.Substring(user.PhoneNumber.IndexOf(')') + 1) )), Shipping = new Shipping { Address = address, Cost = 10.00m, ShippingType = ShippingType.Pac }, //ExtraAmount = 10.00m, Reference = ActiveCart.ReferenceCode, RedirectUri = new Uri(HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Authority) + "/PurchaseHistory/Details/" + ActiveCart.Id), MaxAge = 172800, // 2 dias NotificationURL = HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Authority) + "/Api/Cart/ReceiveNotification" }; foreach (var cartProduct in ActiveCart.Products) { paymentRequest.Items.Add( new Item(cartProduct.ProductId.ToString(), cartProduct.Product.Name, cartProduct.Quantity, (decimal)cartProduct.Product.Price) ); } var paymentRedirectUri = paymentRequest.Register(_credentials); // Update Cart/Products & Generate New Cart foreach (var cartProduct in ActiveCart.Products) { cartProduct.Product.NumberInStock -= cartProduct.Quantity; } ActiveCart.PurchaseDate = DateTime.Now; ActiveCart.CheckoutUrl = paymentRedirectUri.OriginalString; ActiveCart.IsActive = false; _context.Users .Include(u => u.Carts.Select(c => c.Products.Select(p => p.Product))) .Single(u => u.Id == _userId) .Carts.Add(new Cart { IsActive = true, CreationDate = DateTime.Now }); _context.SaveChanges(); return(Ok(paymentRedirectUri)); }
private static void Main(string[] args) { bool isSandbox = false; EnvironmentConfiguration.ChangeEnvironment(isSandbox); // Instantiate a new payment request PaymentRequest payment = new PaymentRequest { // Sets the currency Currency = Currency.Brl }; // Add an item for this payment request payment.Items.Add(new Item("0001", "Notebook Prata", 1, 2430.00m)); // Add another item for this payment request payment.Items.Add(new Item("0002", "Notebook Rosa", 2, 150.99m)); // Sets a reference code for this payment request, it is useful to identify this payment in future notifications. payment.Reference = "REF1234"; // Sets shipping information for this payment request payment.Shipping = new Shipping { ShippingType = ShippingType.Sedex, //Passando valor para ShippingCost Cost = 10.00m, Address = new Address( "BRA", "SP", "Sao Paulo", "Jardim Paulistano", "01452002", "Av. Brig. Faria Lima", "1384", "5o andar" ) }; // Sets your customer information. payment.Sender = new Sender( "Joao Comprador", "*****@*****.**", new Phone("11", "56273440") ); // Sets the url used by PagSeguro for redirect user after ends checkout process payment.RedirectUri = new Uri("http://www.lojamodelo.com.br"); // Add checkout metadata information payment.AddMetaData(MetaDataItemKeys.GetItemKeyByDescription("CPF do passageiro"), "123.456.789-09", 1); payment.AddMetaData("PASSENGER_PASSPORT", "23456", 1); // Another way to set checkout parameters 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); SenderDocument senderCPF = new SenderDocument(Documents.GetDocumentByType("CPF"), "12345678909"); payment.Sender.Documents.Add(senderCPF); // Sets the preApproval informations payment.PreApproval = new PreApproval(); var now = DateTime.Now; // Only works with Manual payment.PreApproval.Charge = Charge.Manual; payment.PreApproval.Name = "Seguro contra roubo do Notebook"; payment.PreApproval.AmountPerPayment = 100.00m; payment.PreApproval.MaxAmountPerPeriod = 100.00m; payment.PreApproval.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")); payment.PreApproval.Period = Period.Monthly; payment.PreApproval.DayOfMonth = now.Day; payment.PreApproval.InitialDate = now; payment.PreApproval.FinalDate = now.AddMonths(6); payment.PreApproval.MaxTotalAmount = 600.00m; payment.PreApproval.MaxPaymentsPerPeriod = 1; payment.ReviewUri = new Uri("http://www.lojamodelo.com.br/revisao"); try { AccountCredentials credentials = PagSeguroConfiguration.Credentials(isSandbox); Uri paymentRedirectUri = payment.Register(credentials); Console.WriteLine("URL do pagamento : " + paymentRedirectUri); Console.ReadKey(); } catch (PagSeguroServiceException exception) { Console.WriteLine(exception.Message + "\n"); foreach (ServiceError element in exception.Errors) { Console.WriteLine(element + "\n"); } Console.ReadKey(); } }
static void Main(string[] args) { //Use global configuration //PagSeguroConfiguration.UrlXmlConfiguration = "../../../../../Configuration/PagSeguroConfig.xml"; bool isSandbox = false; EnvironmentConfiguration.ChangeEnvironment(isSandbox); // Instantiate a new payment request PaymentRequest payment = new PaymentRequest(); // Sets the currency payment.Currency = Currency.Brl; // Add an item for this payment request payment.Items.Add(new Item("0001", "Notebook Prata", 1, 2430.00m)); // Add another item for this payment request payment.Items.Add(new Item("0002", "Notebook Rosa", 2, 150.99m)); // Sets a reference code for this payment request, it is useful to identify this payment in future notifications. payment.Reference = "REF1234"; // Sets shipping information for this payment request payment.Shipping = new Shipping(); payment.Shipping.ShippingType = ShippingType.Sedex; //Passando valor para ShippingCost payment.Shipping.Cost = 10.00m; payment.Shipping.Address = new Address( "BRA", "SP", "Sao Paulo", "Jardim Paulistano", "01452002", "Av. Brig. Faria Lima", "1384", "5o andar" ); // Sets your customer information. payment.Sender = new Sender( "Joao Comprador", "*****@*****.**", new Phone("11", "56273440") ); SenderDocument senderCPF = new SenderDocument(Documents.GetDocumentByType("CPF"), "12345678909"); payment.Sender.Documents.Add(senderCPF); // Sets the url used by PagSeguro for redirect user after ends checkout process payment.RedirectUri = new Uri("http://www.lojamodelo.com.br"); // Add checkout metadata information payment.AddMetaData(MetaDataItemKeys.GetItemKeyByDescription("CPF do passageiro"), "123.456.789-09", 1); payment.AddMetaData("PASSENGER_PASSPORT", "23456", 1); // Another way to set checkout parameters 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); // Add discount per payment method payment.AddPaymentMethodConfig(PaymentMethodConfigKeys.DiscountPercent, 50.00, PaymentMethodGroup.CreditCard); // Add installment without addition per payment method payment.AddPaymentMethodConfig(PaymentMethodConfigKeys.MaxInstallmentsNoInterest, 6, PaymentMethodGroup.CreditCard); // Add installment limit per payment method payment.AddPaymentMethodConfig(PaymentMethodConfigKeys.MaxInstallmentsLimit, 8, PaymentMethodGroup.CreditCard); // Add and remove groups and payment methods List<string> accept = new List<string>(); accept.Add(AcceptedPaymentNames.DebitoItau); accept.Add(AcceptedPaymentNames.DebitoHSBC); payment.AcceptPaymentMethodConfig(AcceptedPaymentGroups.CreditCard, accept); List<string> exclude = new List<string>(); exclude.Add(AcceptedPaymentNames.Boleto); payment.ExcludePaymentMethodConfig(AcceptedPaymentGroups.Boleto, exclude); try { AccountCredentials credentials = PagSeguroConfiguration.Credentials(isSandbox); Uri paymentRedirectUri = payment.Register(credentials); Console.WriteLine("URL do pagamento : " + paymentRedirectUri); Console.ReadKey(); } catch (PagSeguroServiceException exception) { Console.WriteLine(exception.Message + "\n"); foreach (ServiceError element in exception.Errors) { Console.WriteLine(element + "\n"); } Console.ReadKey(); } }
public ActionResult ReprocessarPagamento(string pedidoId) { var pedido = db.Pedidos.Find(pedidoId); AccountCredentials autenticacao = new AccountCredentials("*****@*****.**", "D07D86F6F5D7472182A2979A69D36AFA"); //Informando o Endereço de entrega Address endereco = new Address() { Country = "BRA", State = pedido.Uf, City = pedido.Cidade, District = pedido.Bairro, PostalCode = pedido.Cep, Street = pedido.Endereco, Number = pedido.Numero, Complement = pedido.Complemento }; var comprimento = pedido.ItensPedido.Max(c => c.ProdutoMontado.Comprimento); var altura = pedido.ItensPedido.Sum(c => c.ProdutoMontado.Altura * c.Quantidade); var largura = pedido.ItensPedido.Max(c => c.ProdutoMontado.Largura); var peso = pedido.ItensPedido.Sum(c => c.ProdutoMontado.PesoBruto * c.Quantidade); //Informações do Frete ServicoCorreio.cServico[] cep = new ServicoCorreio.CorreiosController().PrazoPreco(pedido.Cep, Convert.ToDecimal(comprimento), Convert.ToDecimal(largura), Convert.ToDecimal(altura), Convert.ToDecimal(peso)).Data as ServicoCorreio.cServico[]; var frete = new Shipping() { Address = endereco, Cost = Convert.ToDecimal(cep[0].Valor), ShippingType = ShippingType.Sedex }; // Dados do comprador var comprador = new Sender(pedido.Cliente.Nome, pedido.Cliente.Email, new Phone(pedido.Cliente.DddFixo, pedido.Cliente.TelefoneFixo)); var cpfComprador = new SenderDocument(Documents.GetDocumentByType("CPF"), pedido.Cliente.Cpf); comprador.Documents.Add(cpfComprador); // Número de referência ao pagseguro var numeroReferencia = Guid.NewGuid().ToString(); pedido.RefereciaPagSeguro = numeroReferencia; var requisicaoPagamento = new PaymentRequest() { Currency = "BRL", Shipping = frete, Sender = comprador, Reference = numeroReferencia }; var itensPedido = pedido.ItensPedido; foreach (var item in itensPedido) { // Passando os itens do carrinho para classe do PagSeguro. requisicaoPagamento.Items.Add(new Item(item.ProdutoMontadoId, item.ProdutoMontado.Descricao, Convert.ToInt32(item.Quantidade), Convert.ToDecimal(item.TabelaPreco.Valor.Value))); } var url = ""; requisicaoPagamento.NotificationURL = "http://www.famaraonline.com.br/PagSeguro/Notificacao"; try { url = requisicaoPagamento.Register(autenticacao).AbsoluteUri; } catch (PagSeguroServiceException ex) { ModelState.AddModelError("", "Não foi possível processar o pedido tente novamente."); foreach (var item in ex.Errors) { ModelState.AddModelError("", item.Message); } return(View("Index")); } catch (Exception ex) { ModelState.AddModelError("", ex.Message); return(View("Index")); } return(Redirect(url)); }
public ActionResult Pagar(string IdPedido) { //model.Produto = (from i in Lista // where i.ID_PRODUTO == id // select i).FirstOrDefault(); //var pedidoModel = _pedidoApp.GetById(Guid.Parse(IdPedido)); var includes = new[] { "ItensPedido" }; var pedidoModel = _pedidoApp.GetByIdWithIncludes(Guid.Parse(IdPedido), includes); if (pedidoModel != null) { EnvironmentConfiguration.ChangeEnvironment(true); PagamentoPagSeguroModel model = new PagamentoPagSeguroModel(); model.Pedido = new PagamentoPagSeguroPedido { Reference = "P" + IdPedido + "#" + DateTime.Now.Millisecond, RedirectUri = "https://www.google.com.br/search?q=url-temporaria" }; model.Cobrador = new PagamentoPagSeguroCobrador { Nome = "Gabriel Teste Silva", CPF = "33565201720", Email = "*****@*****.**", TelefonePrevixo = 71, TelefoneNumero = 88637803 }; //PagSeguroConfiguration.UrlXmlConfiguration = HttpRuntime.AppDomainAppPath + @"Configuration\PagSeguroConfig.xml"; //AccountCredentials credentials = new AccountCredentials("*****@*****.**", "2507D8278A9D478D94327BABDDC2A573"); AccountCredentials credentials = PagSeguroConfiguration.Credentials(true); try { PaymentRequest payment = new PaymentRequest(); payment.Currency = Currency.Brl; //payment.Items.Add(new Item(model.Produto.ID_PRODUTO.ToString(), model.Produto.Nome, 1, Convert.ToDecimal(model.Produto.Valor))); //var itensPedidoModel = _itemPedidoApp.BuscarItensPorIdPedido(pedidoModel.IdPedido); foreach (var item in pedidoModel.ItensPedido) { var produtoModel = _produtoApp.GetById(item.IdProduto); var produtoPrecoModel = _produtoPrecoApp.GetById(item.IdProdutoPreco); var nomeProdutoCompleto = produtoModel.Descricao + " (" + produtoPrecoModel.Descricao + ")"; payment.Items.Add(new Item(item.IdProduto.ToString(), nomeProdutoCompleto, item.QtdProduto, Convert.ToDecimal(item.ValorUnitario))); } payment.Reference = model.Pedido.Reference; payment.Shipping = new Shipping(); payment.Shipping.ShippingType = ShippingType.NotSpecified; payment.Shipping.Cost = 0.00m; payment.Shipping.Address = new Address( "BRA", "SP", "Sao Paulo", "Jardim Paulistano", "01452002", "Av. Brig. Faria Lima", "1384", "5o andar" ); //payment.Shipping.Address = new Address( // model.Endereco.Pais, // model.Endereco.Estado, // model.Endereco.Cidade, // model.Endereco.Bairro, // model.Endereco.Cep, // model.Endereco.Rua, // model.Endereco.Numero, // model.Endereco.Complemento //); // Sets your customer information. payment.Sender = new Sender( model.Cobrador.Nome, model.Cobrador.Email, new Phone(model.Cobrador.TelefonePrevixo.ToString(), model.Cobrador.TelefoneNumero.ToString()) ); // Sets the url used by PagSeguro for redirect user after ends checkout process payment.RedirectUri = new Uri(@"" + model.Pedido.RedirectUri); //payment.RedirectUri = new Uri(HttpRuntime.AppDomainAppPath + @"Configuration\PagSeguroConfig.xml"); SenderDocument senderCPF = new SenderDocument(Documents.GetDocumentByType("CPF"), model.Cobrador.CPF); payment.Sender.Documents.Add(senderCPF); string paymentRedirectUri = payment.Register(credentials).ToString(); if (!string.IsNullOrEmpty(paymentRedirectUri)) { int posicao = paymentRedirectUri.LastIndexOf("code="); string retor = paymentRedirectUri.Substring(posicao + 5, 32); // var resultado = new // { // checkoutCode = retor // }; //return Json(resultado); var result = new { Success = "True", Message = retor }; return(Json(result, JsonRequestBehavior.AllowGet)); //return Redirect(paymentRedirectUri); } else { ViewBag.Retorno = paymentRedirectUri; return(View("PagSeguro")); } } catch (PagSeguroServiceException exception) { ViewBag.Erro = "Não Foi possivel carregar a página"; return(View("Error")); } } else { ViewBag.Retorno = "Pedido não encontrado."; return(View("PagSeguro")); } }
public IHttpActionResult ObterURLPagamento(String email, String servico, String ip, String hash, String emitenota, String cpfnota) { var hashGerado = DomainUtil.GerarHashMD5(String.Concat(email, ip, servico)); String pedidoGerado = String.Empty; String nomeComprador = String.Empty; String codigoServico = String.Empty; String descricaoServico = String.Empty; String valorServico = String.Empty; Usuario usuarioAtual = null; Boolean sandbox = true; String ArquivoConfiguracaoPagSeguro = @"C:\temp\PagSeguroConfig.xml"; if (!File.Exists(ArquivoConfiguracaoPagSeguro)) { return(Json(new { erro = "S", mensagem = "Arquivo de configuração do pagamento com pagseguro não foi encontrado." })); } try { var configuracaoRepo = container.Resolve <IConfiguracaoRepository>(); var usuarioRepo = container.Resolve <IUsuarioRepository>(); var servicoRepo = container.Resolve <IServicoRepository>(); var usuario = usuarioRepo.ObterPeloEmail(email); var servicoBD = servicoRepo.ObterPeloCodigo(servico); var configuracao = configuracaoRepo.GetById(1); if (configuracao != null) { sandbox = configuracao.AmbienteProducao == "N"; ArquivoConfiguracaoPagSeguro = configuracao.ArquivoConfiguracaoPagSeguro; } if (usuario != null) { nomeComprador = usuario.Nome; usuarioAtual = usuario; var pedidoRepo = container.Resolve <IPedidoRepository>(); var pedido = new Pedido(); pedido.Usuario = usuario; pedido.IP = ip; pedido.Status = (Int32)StatusPedido.Pendente; pedido.Data = DateTime.Now; pedido.CPFNF = cpfnota; pedido.EmiteNF = emitenota; pedido.FormaPagamento = (Int32)FormaPagamento.PagSeguro; if (servicoBD != null) { codigoServico = servicoBD.Codigo; descricaoServico = servicoBD.DescricaoCurta; valorServico = String.Format("{0:0.00}", servicoBD.Valor); pedido.Servico = servicoBD; pedidoRepo.Save(pedido); pedidoGerado = pedido.Id.ToString(); } else { return(Json(new { erro = "S", mensagem = "Código do serviço não cadastrado." })); } } else { return(Json(new { erro = "S", mensagem = "Usuário não cadastrado." })); } } catch (Exception ex) { String debug = ex.Message; return(Json(new { erro = "S", mensagem = "Ocorreu um erro inesperado e não foi possível gerar o seu pedido, por gentileza informe ao desenvolvedor." })); } PagSeguroConfiguration.UrlXmlConfiguration = ArquivoConfiguracaoPagSeguro; EnvironmentConfiguration.ChangeEnvironment(sandbox); PaymentRequest payment = new PaymentRequest(); payment.Items.Add(new Item(codigoServico, descricaoServico, 1, Convert.ToDecimal(valorServico))); payment.Sender = new Sender(nomeComprador, email, null); payment.Shipping = new Shipping(); payment.Shipping.ShippingType = ShippingType.NotSpecified; payment.Currency = Currency.Brl; payment.Reference = pedidoGerado; try { AccountCredentials credentials = PagSeguroConfiguration.Credentials(sandbox); Uri paymentRedirectUri = payment.Register(credentials); var atividadeAtual = new Atividade() { Usuario = usuarioAtual, Data = DateTime.Now, TipoAtividade = Convert.ToInt32(TipoAtividade.NovaCompra), Origem = Convert.ToInt32(OrigemAcesso.Web), Descricao = String.Format("O usuário com o e-mail {0} fez o pedido {1} e gerou a url {2} para checkout no pagseguro", email, pedidoGerado, paymentRedirectUri.AbsoluteUri) }; container.Resolve <AtividadeCRUDService>().Salvar(atividadeAtual); return(Json(new { erro = "N", url = paymentRedirectUri.AbsoluteUri })); } catch (PagSeguroServiceException ex) { String mensagem = String.Empty; String assunto = "Erro de PagSeguroServiceException no método ObterURLPagamento - " + email; if (ex.Errors.Count > 0) { mensagem = ex.Errors[0].Code + " - " + ex.Errors[0].Message; } String mensagem2 = String.Format("Ocorreu um erro - Erro do pagseguro {0} - Data: {1}", mensagem, DateTime.Now.ToString("dd/MM/yyyy - HH:mm:ss")); container.Resolve <IEmailService>().EnviarEmail(Constantes.EMAIL_DESTINATARIO, Constantes.EMAIL_REMETENTE, "Suporte ", assunto, mensagem2, false); String texto = ex.Message; return(Json(new { erro = "S", mensagem = texto }));; } }
private static void Main(string[] args) { //Use global configuration //PagSeguroConfiguration.UrlXmlConfiguration = "../../../../../Configuration/PagSeguroConfig.xml"; bool isSandbox = false; EnvironmentConfiguration.ChangeEnvironment(isSandbox); // Instantiate a new payment request PaymentRequest payment = new PaymentRequest { // Sets the currency Currency = Currency.Brl }; // Add an item for this payment request payment.Items.Add(new Item("0001", "Notebook Prata", 1, 2430.00m)); // Add another item for this payment request payment.Items.Add(new Item("0002", "Notebook Rosa", 2, 150.99m)); // Sets a reference code for this payment request, it is useful to identify this payment in future notifications. payment.Reference = "REF1234"; // Sets shipping information for this payment request payment.Shipping = new Shipping { ShippingType = ShippingType.Sedex, //Passando valor para ShippingCost Cost = 10.00m, Address = new Address( "BRA", "SP", "Sao Paulo", "Jardim Paulistano", "01452002", "Av. Brig. Faria Lima", "1384", "5o andar" ) }; // Sets your customer information. payment.Sender = new Sender( "Joao Comprador", "*****@*****.**", new Phone("11", "56273440") ); SenderDocument document = new SenderDocument(Documents.GetDocumentByType("CPF"), "12345678909"); payment.Sender.Documents.Add(document); // Sets the url used by PagSeguro for redirect user after ends checkout process payment.RedirectUri = new Uri("http://www.lojamodelo.com.br"); // Add checkout metadata information payment.AddMetaData(MetaDataItemKeys.GetItemKeyByDescription("CPF do passageiro"), "123.456.789-09", 1); payment.AddMetaData("PASSENGER_PASSPORT", "23456", 1); // Another way to set checkout parameters 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); // Add discount per payment method payment.AddPaymentMethodConfig(PaymentMethodConfigKeys.DiscountPercent, 50.00, PaymentMethodGroup.CreditCard); // Add installment without addition per payment method payment.AddPaymentMethodConfig(PaymentMethodConfigKeys.MaxInstallmentsNoInterest, 6, PaymentMethodGroup.CreditCard); // Add installment limit per payment method payment.AddPaymentMethodConfig(PaymentMethodConfigKeys.MaxInstallmentsLimit, 8, PaymentMethodGroup.CreditCard); // Add and remove groups and payment methods List <string> accept = new List <string> { ListPaymentMethodNames.DebitoItau, ListPaymentMethodNames.DebitoHSBC }; payment.AcceptPaymentMethodConfig(ListPaymentMethodGroups.CreditCard, accept); List <string> exclude = new List <string> { ListPaymentMethodNames.Boleto }; payment.ExcludePaymentMethodConfig(ListPaymentMethodGroups.Boleto, exclude); try { /// Create new account credentials /// This configuration let you set your credentials from your ".cs" file. AccountCredentials credentials = new AccountCredentials("*****@*****.**", "256422BF9E66458CA3FE41189AD1C94A"); /// @todo with you want to get credentials from xml config file uncommend the line below and comment the line above. //AccountCredentials credentials = PagSeguroConfiguration.Credentials(isSandbox); Uri paymentRedirectUri = payment.Register(credentials); Console.WriteLine("URL do pagamento : " + paymentRedirectUri); Console.ReadKey(); } catch (PagSeguroServiceException exception) { Console.WriteLine(exception.Message + "\n"); foreach (ServiceError element in exception.Errors) { Console.WriteLine(element + "\n"); } Console.ReadKey(); } }
public async Task <ActionResult> Confirmar() { if (Session["IdCurso"] == null) { return(View()); } var id = Session["IdCurso"]; Curso curso = await db.Cursos.FindAsync(id); if (curso == null) { return(HttpNotFound()); } if (curso.FimInscricao < DateTime.Now || curso.DataInicio.AddDays(7) < DateTime.Now) { ViewBag.Mensagem = "O período de inscrições já finalizou."; return(View()); } int totalInscritos = db.Matriculas.Where(m => !m.Situacao.Equals("C") && m.IDCurso == curso.ID).Count(); if (totalInscritos >= curso.Vagas) { ViewBag.Mensagem = "Não há mais vagas dispononíveis para o curso."; return(View()); } if (Session["Aluno"] == null) { return(RedirectToAction("NovoAluno", "Alunos")); } Aluno aluno = (Aluno)Session["Aluno"]; var transacao = db.Database.BeginTransaction(); try { Matricula matricula = new Matricula(); matricula.IDAluno = aluno.ID; matricula.IDCurso = curso.ID; matricula.DataMatricula = DateTime.Now; matricula.Situacao = "I"; //Inscrito db.Matriculas.Add(matricula); db.SaveChanges(); string plano = "Cursos = " + curso.Titulo; string nome = aluno.Nome; string telefone = aluno.Telefone; string uf = aluno.UF.ToUpper(); string cidade = aluno.Cidade; string bairro = aluno.Bairro; string cep = aluno.CEP; string endereco = aluno.Endereco; string cpf = aluno.CPF; PaymentRequest payment = new PaymentRequest(); payment.Items.Add(new Item("0001", plano, 1, curso.Valor)); payment.Sender = new Sender( nome, User.Identity.Name, new Phone( telefone.Substring(0, 2), telefone.Substring(2) ) ); payment.Shipping = new Shipping(); payment.Shipping.ShippingType = ShippingType.NotSpecified; payment.Shipping.Address = new Address( "BRA", uf, cidade, bairro, cep, endereco, "0", null ); payment.Currency = Currency.Brl; payment.Reference = "MAT" + matricula.ID.ToString(); SenderDocument senderDocument = senderDocument = new SenderDocument(Documents.GetDocumentByType("CPF"), cpf); payment.Sender.Documents.Add(senderDocument); payment.RedirectUri = new Uri("http://www.insesf.com/Inscricao/RetornoPagseguro"); payment.NotificationURL = "http://www.insesf.com/RetornoPagamento/Retorno"; AccountCredentials credentials = PagSeguroConfiguration.Credentials(sandbox); Uri paymentRedirectUri = payment.Register(credentials); string url = paymentRedirectUri.AbsoluteUri; transacao.Commit(); Session["IdCurso"] = null; Session["TituloCurso"] = null; return(Redirect(url)); } catch (PagSeguroServiceException e) { transacao.Rollback(); ViewBag.Mensagem = string.Format("Não foi possível processar a matrícula. Tente de novo mais tarde. {0}", e.ToString()); return(View()); } }
public ActionResult Create(Pedido pedido, string FormaPagamento) { var userId = User.Identity.GetUserId(); var cliente = db.Clientes.FirstOrDefault(c => c.ApplicationUserId == userId); var user = db.Users.Find(userId); var Mensagens = !user.EmailConfirmed ? "Você precisa confirmar seu e-mail antes de continuar" : ""; ModelState.AddModelError("", Mensagens); if (!string.IsNullOrEmpty(Mensagens)) { pedido.ClienteId = cliente.Id; return(View(pedido)); } // Iniciando a sessão com PagSeguro // homologação: D07D86F6F5D7472182A2979A69D36AFA // Produção: 79C4FEC17D444783947521D2645E2DE5 // [email protected] //[email protected] AccountCredentials autenticacao = new AccountCredentials("*****@*****.**", "D07D86F6F5D7472182A2979A69D36AFA"); //Informando o Endereço de entrega Address endereco = new Address() { Country = "BRA", State = pedido.Uf, City = pedido.Cidade, District = pedido.Bairro, PostalCode = pedido.Cep, Street = pedido.Endereco, Number = pedido.Numero, Complement = pedido.Complemento }; // Definindo os paramêtros para transação var carrinho = new Carrinho(User.Identity.GetUserId(), Request.AnonymousID); ViewBag.TotalItens = carrinho?.ObterQuantidadeItens(); var comprimento = carrinho.ItemCarrinhos.Max(c => c.ProdutoMontado.Comprimento); var altura = carrinho.ItemCarrinhos.Sum(c => c.ProdutoMontado.Altura * c.QuantidadeTotalItem); var largura = carrinho.ItemCarrinhos.Max(c => c.ProdutoMontado.Largura); var peso = carrinho.ItemCarrinhos.Sum(c => c.ProdutoMontado.PesoBruto * c.QuantidadeTotalItem); var cupomDesconto = carrinho.ItemCarrinhos.First().Promocao; pedido.PromocaoId = cupomDesconto?.Id; //Informações do Frete ServicoCorreio.cServico[] cep = new ServicoCorreio.CorreiosController().PrazoPreco(pedido.Cep, Convert.ToDecimal(comprimento), Convert.ToDecimal(largura), Convert.ToDecimal(altura), Convert.ToDecimal(peso)).Data as ServicoCorreio.cServico[]; var frete = new Shipping() { Address = endereco, Cost = Convert.ToDecimal(cep[0].Valor), ShippingType = ShippingType.Sedex }; // Dados do comprador var comprador = new Sender(cliente.Nome, cliente.Email, new Phone(cliente.DddFixo, cliente.TelefoneFixo)); var cpfComprador = new SenderDocument(Documents.GetDocumentByType("CPF"), cliente.Cpf); comprador.Documents.Add(cpfComprador); // Número de referência ao pagseguro var numeroReferencia = Guid.NewGuid().ToString(); pedido.RefereciaPagSeguro = numeroReferencia; var requisicaoPagamento = new PaymentRequest() { Currency = "BRL", Shipping = frete, Sender = comprador, Reference = numeroReferencia }; var itensCarrinho = carrinho.ItemCarrinhos.ToList(); foreach (var item in itensCarrinho) { requisicaoPagamento.Items.Add(new Item(item.ProdutoMontadoId, item.ProdutoMontado.Descricao, item.QuantidadeTotalItem, Convert.ToDecimal(item.ValorUnitario))); } var url = ""; requisicaoPagamento.NotificationURL = "http://www.famaraonline.com.br/PagSeguro/Notificacao"; // try try { url = requisicaoPagamento.Register(autenticacao).AbsoluteUri; } catch (PagSeguroServiceException ex) { ViewBag.TotalItens = carrinho.ObterQuantidadeItens(); ModelState.AddModelError("", "Não foi possível processar o pedido tente novamente."); foreach (var item in ex.Errors) { ModelState.AddModelError("", item.Message); } return(View(pedido)); } catch (Exception ex) { ModelState.AddModelError("", ex.Message); return(View(pedido)); } pedido.Id = (Convert.ToInt32(db.Pedidos.Max(c => c.Id)) + 1).ToString().PadLeft(6, '0'); pedido.DataEmissao = DateTime.Now; pedido.data_alteracao = DateTime.Now; pedido.data_gravacao = DateTime.Now; pedido.ValorFrete = double.Parse(frete.Cost.Value.ToString()); pedido.ValorPedido = Convert.ToDouble(carrinho.ObterValorTotal()); pedido.ValorPedido1 = pedido.ValorPedido; pedido.ClienteId = cliente.Id; pedido.CpfCliente = cliente.Cpf; pedido.CpfCliente = cliente.Cpf; var local = db.Parametros.FirstOrDefault().local_loja; var itensPedido = itensCarrinho.Select(item => new ItensPedido() { ClienteId = cliente.Id, CodTabelaPreco = item.TabelaPreco.Codigo, TabelaPrecoId = item.TabelaPrecoId, ProdutoMontadoId = item.ProdutoMontadoId, Quantidade = item.QuantidadeTotalItem, ValorTotal = item.ValorTotalItem, ValorTotal1 = item.ValorTotalItem, CpfCliente = cliente.Cpf, DescricaoProduto = item.ProdutoMontado.Descricao, ValorUnitario = item.ValorUnitario, ItemPedido = (itensCarrinho.IndexOf(item) + 1).ToString().PadLeft(3, '0'), PedidoId = pedido.Id, LocalId = local, data_entrega = DateTime.Now, data_emissao = DateTime.Now, data_alteracao = DateTime.Now, data_gravacao = DateTime.Now }).ToList(); pedido.aprovacao_financeiro = "N"; pedido.DataEmissaoPagSeguro = DateTime.Now; pedido.UrlPagamento = url; pedido.StatusCode = "1"; pedido.StatusDescricao = "Aguardando pagamento"; using (var transaction = db.Database.BeginTransaction()) { try { db.Pedidos.Add(pedido); db.SaveChanges(); db.ItensPedido.AddRange(itensPedido); db.SaveChanges(); var itens = db.ItemCarrinhos.Where(c => c.ApplicationUserId == cliente.ApplicationUserId).ToList(); foreach (var item in itens) { var produto = db.ProdutosMontados.Find(item.ProdutoMontadoId); var grade = db.Produtos.Find(produto.ProdutoId); produto.QtdVendida += 1; grade.QtdVendida += 1; db.Entry(produto).State = EntityState.Modified; db.SaveChanges(); db.Entry(grade).State = EntityState.Modified; db.SaveChanges(); } db.ItemCarrinhos.RemoveRange(itens); db.SaveChanges(); transaction.Commit(); } catch (Exception ex) { transaction.Rollback(); ViewBag.TotalItens = carrinho.ObterQuantidadeItens(); ModelState.AddModelError("", "Não foi possível processar o pedido tente novamente."); return(View(pedido)); } } return(Redirect(url)); //return RedirectToAction("Index", "Pedidos"); }
public void Pay() { const bool isSandbox = true; // EnvironmentConfiguration.ChangeEnvironment(isSandbox); 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", "Orçamento", 1, 20.00m)); // 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", "*****@*****.**", new Phone("11", "56273440") ); // URL a redirecionar o usuário após pagamento payment.RedirectUri = new Uri("http://www.agilizaorcamento.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"), "03078690164"); //payment.Sender.Documents.Add(senderCpf); var paymentRedirectUri = payment.Register(credentials); }