public async Task <ValorPrazoFrete> CalcularFrete(String cepDestino, String tipoFrete, List <Pacote> pacotes)
        {
            List <ValorPrazoFrete> ValorDosPacotesPorFrete = new List <ValorPrazoFrete>();

            foreach (var pacote in pacotes)
            {
                var resultado = await CalcularValorPrazoFrete(cepDestino, tipoFrete, pacote);

                if (resultado != null)
                {
                    ValorDosPacotesPorFrete.Add(resultado);
                }
            }

            if (ValorDosPacotesPorFrete.Count > 0)
            {
                ValorPrazoFrete ValorDosFretes = ValorDosPacotesPorFrete
                                                 .GroupBy(a => a.TipoFrete)
                                                 .Select(list => new ValorPrazoFrete
                {
                    TipoFrete    = list.First().TipoFrete,
                    CodTipoFrete = list.First().CodTipoFrete,
                    Prazo        = list.Max(c => c.Prazo),
                    Valor        = list.Sum(c => c.Valor)
                }).ToList().First();

                return(ValorDosFretes);
            }
            return(null);
        }
        public IActionResult Index([FromForm] IndexViewModel indexViewModel)
        {
            if (ModelState.IsValid)
            {
                EnderecoEntrega    enderecoEntrega = ObterEndereco();
                ValorPrazoFrete    frete           = ObterFrete();
                List <ProdutoItem> produtos        = CarregarProdutoDB();
                Parcelamento       parcela         = BuscarParcelamento(produtos, indexViewModel.Parcelamento.Numero);

                try
                {
                    Transaction transaction = _gerenciarPagarMe.GerarPagCartaoCredito(indexViewModel.CartaoCredito, parcela, enderecoEntrega, frete, produtos);
                    Pedido      pedido      = ProcessarPedido(produtos, transaction);

                    return(new RedirectToActionResult("Index", "Pedido", new { id = pedido.Id }));
                }
                catch (PagarMeException e)
                {
                    _logger.LogError(e, "PagamentoController > Index ");
                    TempData["MSG_E"] = MontarMensagensDeErro(e);

                    return(Index());
                }
            }
            else
            {
                return(Index());
            }
        }
Exemplo n.º 3
0
        public async Task <IActionResult> CalcularFrete(string CepDestino)
        {
            try
            {
                List <ShoppingCartItem> produtos = _carrinho.GetShoppingCartItens();

                List <PacoteFrete> pacotes = _calcularPacote.CalcularPacotesdeProdutos(produtos);

                ValorPrazoFrete ValorPAC = await _wscorreios.CalcularFrete(CepDestino.ToString(), TipoFreteConstante.PAC, pacotes);

                ValorPrazoFrete ValorSEDEX = await _wscorreios.CalcularFrete(CepDestino.ToString(), TipoFreteConstante.SEDEX, pacotes);

                ValorPrazoFreteModel valorPrazoFreteModel = new ValorPrazoFreteModel();

                valorPrazoFreteModel.ListaValorPrazoFrete = new List <ValorPrazoFrete>();

                //_frete = ValorPAC;
                ValorPAC.SomaTotal   = _carrinho.TotalCarrinho() + (decimal)ValorPAC.Valor;
                ValorSEDEX.SomaTotal = _carrinho.TotalCarrinho() + (decimal)ValorSEDEX.Valor;


                valorPrazoFreteModel.ListaValorPrazoFrete.Add(ValorPAC);
                valorPrazoFreteModel.ListaValorPrazoFrete.Add(ValorSEDEX);

                //valorPrazoFreteModel.SomaTotalFrete = valorPrazoFreteModel.ListaValorPrazoFrete[0].SomaTotal;


                return(PartialView("_CalculoFrete", valorPrazoFreteModel));
            }
            catch (Exception e)
            {
                return(BadRequest(e));
            }
        }
Exemplo n.º 4
0
        private decimal ObterValorTotal(List <ProdutoItem> produtos, ValorPrazoFrete frete)
        {
            decimal Total = (decimal)frete.Valor;

            foreach (ProdutoItem produto in produtos)
            {
                Total += (decimal)produto.Valor * produto.QuantidadeCarrinhoProduto;
            }
            return(Total);
        }
Exemplo n.º 5
0
        public async Task <IActionResult> CalcularFrete(int cepDestino)
        {
            try
            {
                //Verifica se existe o calculo do frete e retorna
                Frete frete = this._cookieFrete.Consultar().Where(x => x.CEP == cepDestino && x.CodCarrinho == GerarHash(this._carrinhoCompra.Consultar())).FirstOrDefault();

                if (frete != null)
                {
                    return(Ok(frete));
                }
                else
                {
                    var           produto = CarregarProdutoDB();
                    List <Pacote> pacotes = this.CalcularPacote.CalcularPacotesDeProdutos(produto);

                    ValorPrazoFrete valorPAC = await this._wsCorreios.CalcularFrete(cepDestino.ToString(), TipoFreteConstante.PAC, pacotes);

                    ValorPrazoFrete valorSEDEX = await this._wsCorreios.CalcularFrete(cepDestino.ToString(), TipoFreteConstante.SEDEX, pacotes);

                    ValorPrazoFrete valorSEDEX10 = await this._wsCorreios.CalcularFrete(cepDestino.ToString(), TipoFreteConstante.SEDEX10, pacotes);

                    List <ValorPrazoFrete> lista = new List <ValorPrazoFrete>();
                    if (valorPAC != null)
                    {
                        lista.Add(valorPAC);
                    }
                    if (valorSEDEX != null)
                    {
                        lista.Add(valorSEDEX);
                    }
                    if (valorSEDEX10 != null)
                    {
                        lista.Add(valorSEDEX10);
                    }

                    frete = new Frete()
                    {
                        CEP          = cepDestino,
                        CodCarrinho  = GerarHash(this._carrinhoCompra.Consultar()),
                        ListaValores = lista
                    };



                    this._cookieFrete.Cadastrar(frete);
                    return(Ok(frete));
                }
            }
            catch (Exception e)
            {
                //this._cookieValorPrazo.Remover();
                return(BadRequest(e));
            }
        }
        public IActionResult Index()
        {
            List <ProdutoItem> produtoItemCompleto = CarregarProdutoDB();
            ValorPrazoFrete    frete = ObterFrete();

            ViewBag.Frete         = frete;
            ViewBag.Produtos      = produtoItemCompleto;
            ViewBag.Parcelamentos = CalcularParcelamento(produtoItemCompleto);

            return(View("Index"));
        }
        private decimal ObterValorTotalCompra(ValorPrazoFrete frete, List <ProdutoItem> produtos)
        {
            decimal total = Convert.ToDecimal(frete.Valor);

            foreach (var produto in produtos)
            {
                total += produto.Valor;
            }

            return(total);
        }
        private decimal ObterValorTotalCompra(List <ProdutoItem> produtos)
        {
            ValorPrazoFrete frete = ObterFrete();
            decimal         total = Convert.ToDecimal(frete.Valor);

            foreach (var produto in produtos)
            {
                total += produto.Valor * produto.UnidadesPedidas;
            }

            return(total);
        }
        public async Task <IActionResult> CalcularFrete(int cepDestino)
        {
            try
            {
                //Verifica se existe no Frete o calculo para o mesmo CEP e produtos.
                Frete frete = _cookieFrete.Consultar().Where(a => a.CEP == cepDestino && a.CodCarrinho == GerarHash(_cookieCarrinhoCompra.Consultar())).FirstOrDefault();
                if (frete != null)
                {
                    return(Ok(frete));
                }
                else
                {
                    List <ProdutoItem> produtos = CarregarProdutoDB();
                    List <Pacote>      pacotes  = _calcularPacote.CalcularPacotesDeProdutos(produtos);

                    ValorPrazoFrete valorPAC = await _wscorreios.CalcularFrete(cepDestino.ToString(), TipoFreteConstant.PAC, pacotes);

                    ValorPrazoFrete valorSEDEX = await _wscorreios.CalcularFrete(cepDestino.ToString(), TipoFreteConstant.SEDEX, pacotes);

                    ValorPrazoFrete valorSEDEX10 = await _wscorreios.CalcularFrete(cepDestino.ToString(), TipoFreteConstant.SEDEX10, pacotes);

                    List <ValorPrazoFrete> lista = new List <ValorPrazoFrete>();
                    if (valorPAC != null)
                    {
                        lista.Add(valorPAC);
                    }
                    if (valorSEDEX != null)
                    {
                        lista.Add(valorSEDEX);
                    }
                    if (valorSEDEX10 != null)
                    {
                        lista.Add(valorSEDEX10);
                    }

                    frete = new Frete()
                    {
                        CEP          = cepDestino,
                        CodCarrinho  = GerarHash(_cookieCarrinhoCompra.Consultar()),
                        ListaValores = lista
                    };

                    _cookieFrete.Cadastrar(frete);

                    return(Ok(frete));
                }
            }
            catch (Exception e)
            {
                _logger.LogError(e, "CarrinhoCompraControler > CalcularFrete");
                return(BadRequest(e));
            }
        }
Exemplo n.º 10
0
        public async Task <IActionResult> CalcularFrete(int cepDestino)
        {
            try
            {
                List <ProdutoItem> produtos = CarregarProdutoBancoDados();
                //TipoFreteConstant
                List <Pacote> pacotes = _calcularpacote.CalcularPacotesDeProduto(produtos);

                ValorPrazoFrete valorPAC = await _wsorreiosCalcularFrete.CalcularFrete(cepDestino.ToString(), TipoFreteConstant.PAC, pacotes);

                ValorPrazoFrete valorSEDEX = await _wsorreiosCalcularFrete.CalcularFrete(cepDestino.ToString(), TipoFreteConstant.SEDEX, pacotes);

                ValorPrazoFrete valorSEDEX10 = await _wsorreiosCalcularFrete.CalcularFrete(cepDestino.ToString(), TipoFreteConstant.SEDEX10, pacotes);

                List <ValorPrazoFrete> lista = new List <ValorPrazoFrete>();
                if (valorPAC != null)
                {
                    lista.Add(valorPAC);
                }
                if (valorSEDEX != null)
                {
                    lista.Add(valorSEDEX);
                }
                if (valorSEDEX10 != null)
                {
                    lista.Add(valorSEDEX10);
                }

                var frete = new Frete()
                {
                    CEP = cepDestino,
                    //CodCarrinho = HashCode,
                    ListaValores = lista
                };

                //_cookieValorPrazoFrete.Cadastrar(frete);

                return(Ok(frete));
            }
            catch (Exception e)
            {
                _cookieValorPrazoFrete.Remover();
                return(BadRequest(e));
            }
        }
Exemplo n.º 11
0
        public async Task <IActionResult> CalcularFrete([FromRoute] string cepDestino)
        {
            var produtos = await _carrinhoCompras.TodosItemsCarrinho();

            Frete frete = _cookieFrete.Consultar().Where(a => a.CEP == Convert.ToInt32(cepDestino) && a.CodCarrinho == StringMD5.GerarHash(produtos)).FirstOrDefault();

            if (frete != null)
            {
                return(Ok(frete));
            }
            //await _memoryCache.GetOrCreate("Itens",async () => await _carrinhoCompras.TodosItemsCarrinho());
            List <Pacote> pacotes = _calcularPacote.CalcularPacotesDeProdutos(produtos);

            ValorPrazoFrete valorPAC = await _wscorreios.CalcularFrete(cepDestino, TipoFreteConstant.PAC, pacotes);

            ValorPrazoFrete valorSEDEX = await _wscorreios.CalcularFrete(cepDestino, TipoFreteConstant.SEDEX, pacotes);

            ValorPrazoFrete valorSEDEX10 = await _wscorreios.CalcularFrete(cepDestino, TipoFreteConstant.SEDEX10, pacotes);

            List <ValorPrazoFrete> lista = new List <ValorPrazoFrete>();

            if (valorPAC != null)
            {
                lista.Add(valorPAC);
            }
            if (valorSEDEX != null)
            {
                lista.Add(valorSEDEX);
            }
            if (valorSEDEX10 != null)
            {
                lista.Add(valorSEDEX10);
            }

            frete = new Frete()
            {
                CEP          = Convert.ToInt32(cepDestino),
                CodCarrinho  = StringMD5.GerarHash(produtos),
                ListaValores = lista
            };
            _cookieFrete.Cadastrar(frete);

            return(Ok(frete));
        }
Exemplo n.º 12
0
        public IActionResult Boleto()
        {
            List <ProdutoItem> produtos = CarregarProdutoDB();
            EnderecoEntrega    endereco = ObterEndereco();
            ValorPrazoFrete    frete    = ObterFrete();
            decimal            Total    = ObterValorTotal(produtos, frete);

            try
            {
                Transaction transaction = _gerenciarPagarMe.GerarBoleto(Total, endereco, frete, produtos);
                Pedido      pedido      = SalvarPedido(produtos, transaction);
                return(new RedirectToActionResult("Index", "Pedido", new { id = pedido.Id }));
            }
            catch (PagarMeException e)
            {
                TempData["MSG_E"] = MontarMensagensExceptionsPagarme(e);
                return(RedirectToAction(nameof(Index)));
            }
        }
Exemplo n.º 13
0
        public async Task <ValorPrazoFrete> CalcularFrete(String cepDestino, String tipoFrete, List <PacoteFrete> Pacotes)
        {
            List <ValorPrazoFrete> ValorDosPacotesPorFrete = new List <ValorPrazoFrete>();

            foreach (var pacote in Pacotes)
            {
                ValorDosPacotesPorFrete.Add(await CalcularValorPrazoFrete(cepDestino, tipoFrete, pacote));
            }

            ValorPrazoFrete ValorDosFretes = ValorDosPacotesPorFrete
                                             .GroupBy(a => a.TipoFrete)
                                             .Select(list => new ValorPrazoFrete
            {
                TipoFrete = list.First().TipoFrete,
                Prazo     = list.Max(c => c.Prazo),
                Valor     = list.Sum(c => c.Valor)
            }).ToList().First();

            return(ValorDosFretes);
        }
        public IActionResult Index([FromForm] IndexViewModel indexViewModel)
        {
            if (ModelState.IsValid)
            {
                //TODO - Integrar os dados, Salvar os dados e redirecionar para a tela de pedido concluido
                EnderecoEntrega    enderecoEntrega = ObterEndereco();
                ValorPrazoFrete    frete           = ObterFrete(enderecoEntrega.CEP.ToString());
                List <ProdutoItem> produtos        = CarregarProdutoDB();

                var parcela = this._gerenciarPagarMe.CalcularPagamentoParcelado(ObterValorTotalCompra(frete, produtos)).Where(x => x.Numero == indexViewModel.parcelamento.Numero).FirstOrDefault();

                try
                {
                    dynamic pagarmeReposta = this._gerenciarPagarMe.GerarPagCartaoCredito(indexViewModel.cartaoCredito, parcela, enderecoEntrega, frete, produtos);
                    return(new ContentResult()
                    {
                        Content = "Sucesso!" + pagarmeReposta.TransactionId
                    });
                }
                catch (PagarMeException e)
                {
                    StringBuilder sb = new StringBuilder();

                    if (e.Error.Errors.Count() > 0)
                    {
                        sb.Append("Erro no pagamento: ");
                        foreach (var erro in e.Error.Errors)
                        {
                            sb.Append("-" + erro.Message + "<br/>");
                        }
                    }
                    TempData["MSG_E"] = sb.ToString();
                    return(Index());
                }
            }
            else
            {
                return(Index());
            }
        }
        public async Task <IActionResult> CalcularFrete(int cepDestino)
        {
            try
            {
                List <ProdutoItem> produtos = CarregarProdutoDB();

                List <Pacote> pacotes = _calcularPacote.CalcularPacotesDeProdutos(produtos);

                ValorPrazoFrete valorPAC = await _wscorreios.CalcularFrete(cepDestino.ToString(), TipoFreteConstant.PAC, pacotes);

                ValorPrazoFrete valorSEDEX = await _wscorreios.CalcularFrete(cepDestino.ToString(), TipoFreteConstant.SEDEX, pacotes);

                ValorPrazoFrete valorSEDEX10 = await _wscorreios.CalcularFrete(cepDestino.ToString(), TipoFreteConstant.SEDEX10, pacotes);

                List <ValorPrazoFrete> lista = new List <ValorPrazoFrete>();
                if (valorPAC != null)
                {
                    lista.Add(valorPAC);
                }
                if (valorSEDEX != null)
                {
                    lista.Add(valorSEDEX);
                }
                if (valorSEDEX10 != null)
                {
                    lista.Add(valorSEDEX10);
                }

                _cookieValorPrazoFrete.Cadastrar(lista);

                return(Ok(lista));
            }
            catch (Exception e)
            {
                _cookieValorPrazoFrete.Remover();

                return(BadRequest(e));
            }
        }
        public IActionResult BoletoBancario()
        {
            EnderecoEntrega    enderecoEntrega = ObterEndereco();
            ValorPrazoFrete    frete           = ObterFrete();
            List <ProdutoItem> produtos        = CarregarProdutoDB();
            var valorTotal = ObterValorTotalCompra(produtos);

            try
            {
                Transaction transaction = _gerenciarPagarMe.GerarBoleto(valorTotal, produtos, enderecoEntrega, frete);

                Pedido pedido = ProcessarPedido(produtos, transaction);

                return(new RedirectToActionResult("Index", "Pedido", new { id = pedido.Id }));
            }
            catch (PagarMeException e)
            {
                _logger.LogError(e, "PagamentoController > BoletoBancario ");
                TempData["MSG_E"] = MontarMensagensDeErro(e);
                return(RedirectToAction(nameof(Index)));
            }
        }
Exemplo n.º 17
0
        public IActionResult Index([FromForm] PagamentoViewModel pagamento)
        {
            if (ModelState.IsValid)
            {
                List <ProdutoItem> produtos = CarregarProdutoDB();
                EnderecoEntrega    endereco = ObterEndereco();
                ValorPrazoFrete    frete    = ObterFrete();
                try
                {
                    Parcela     parcela = _gerenciarPagarMe.CalcularParcelaProduto(ObterValorTotal(produtos, frete)).Where(a => a.ParcelaQuantidade == pagamento.Parcelas).First();
                    Transaction pagarMe = _gerenciarPagarMe.GerarPagCartaoCredito(parcela, pagamento.CartaoCredito, produtos, endereco, frete);

                    Pedido pedido = SalvarPedido(produtos, pagarMe);

                    return(new RedirectToActionResult("Index", "Pedido", new { id = pedido.Id }));
                }
                catch (PagarMeException e)
                {
                    TempData["MSG_E"] = MontarMensagensExceptionsPagarme(e);
                    return(RedirectToAction(nameof(Index)));
                }
            }
            return(Index());
        }
Exemplo n.º 18
0
        public async Task <IActionResult> CalcularFrete(string cepDestino)
        {
            try
            {
                Frete frete   = _cookieValorPrazoFrete.Consultar().Where(a => a.CEP == cepDestino && a.CarrinhoId == HashGenerator.CreateMD5(JsonConvert.SerializeObject(_carrinhoCompra.Consultar()))).FirstOrDefault();
                var   options = new CookieOptions()
                {
                    Expires = DateTime.Now.AddDays(7), IsEssential = true
                };

                HttpContext.Response.Cookies.Append("Carrinho.CEP", cepDestino, options);
                if (frete != null)
                {
                    return(Ok(frete));
                }
                else
                {
                    List <ProdutoItem> produtos = CarregarProdutoDB();
                    List <Pacote>      pacotes  = _pacote.CalcularPacote(produtos);

                    ValorPrazoFrete valorPAC = await _frete.CalcularFrete(cepDestino, TipoFreteConstant.PAC, pacotes);

                    ValorPrazoFrete valorSEDEX = await _frete.CalcularFrete(cepDestino, TipoFreteConstant.Sedex, pacotes);

                    ValorPrazoFrete valorSEDEX10 = await _frete.CalcularFrete(cepDestino, TipoFreteConstant.Sedex10, pacotes);

                    List <ValorPrazoFrete> lista = new List <ValorPrazoFrete>();
                    if (valorPAC != null)
                    {
                        lista.Add(valorPAC);
                    }
                    if (valorSEDEX != null)
                    {
                        lista.Add(valorSEDEX);
                    }
                    if (valorSEDEX10 != null)
                    {
                        lista.Add(valorSEDEX10);
                    }

                    if (lista.Count() == 0)
                    {
                        return(BadRequest(new { erro = "Este CEP não possui acesso ao servico dos CORREIOS" }));;
                    }

                    frete = new Frete()
                    {
                        CEP        = cepDestino,
                        CarrinhoId = HashGenerator.CreateMD5(JsonConvert.SerializeObject(_carrinhoCompra.Consultar())),
                        Valores    = lista
                    };

                    _cookieValorPrazoFrete.Cadastrar(frete);

                    return(Ok(frete));
                }
            }
            catch (Exception e)
            {
                return(BadRequest(e));
            }
        }
Exemplo n.º 19
0
        public object GerarPagCartaoCredito(CartaoCredito cartao, Parcelamento parcelamento, EnderecoEntrega enderecoEntrega, ValorPrazoFrete frete, List <ProdutoItem> produtos)
        {
            Cliente cliente = this._loginCliente.GetCliente();

            PagarMeService.DefaultApiKey        = this._configuration.GetValue <string>("Pagamento:PagarMe:ApiKey");
            PagarMeService.DefaultEncryptionKey = this._configuration.GetValue <string>("Pagamento:PagarMe:EncryptionKey");

            Card card = new Card();

            card.Number         = cartao.NumeroCartao;
            card.HolderName     = cartao.NomeNoCartao;
            card.ExpirationDate = cartao.VencimentoMM + cartao.VencimentoYY;
            card.Cvv            = cartao.CodigoSeguranca;
            card.Save();

            Transaction transaction = new Transaction();

            transaction.Amount = 2100;
            transaction.Card   = new Card
            {
                Id = card.Id
            };

            transaction.Customer = new Customer
            {
                ExternalId = cliente.Id.ToString(),
                Name       = cliente.Nome,
                Type       = CustomerType.Individual,
                Country    = "br",
                Email      = cliente.Email,
                Documents  = new[]
                {
                    new Document {
                        Type   = DocumentType.Cpf,
                        Number = Mascara.Remover(cliente.CPF)
                    },
                    new Document {
                        Type   = DocumentType.Cnpj,
                        Number = "89388916000174"
                    }
                },
                PhoneNumbers = new string[]
                {
                    "+55" + Mascara.Remover(cliente.Telefone),
                },
                Birthday = cliente.DataNasc.ToString("yyyy-MM-dd")
            };

            transaction.Billing = new Billing
            {
                Name    = cliente.Nome,
                Address = new Address()
                {
                    Country      = "br",
                    State        = cliente.Estado,
                    City         = cliente.Cidade,
                    Neighborhood = cliente.Bairro,
                    Street       = cliente.Endereco + " " + cliente.Complemento,
                    StreetNumber = cliente.Numero,
                    Zipcode      = Mascara.Remover(cliente.CEP)
                }
            };

            var Today = DateTime.Now;

            // Converter corretamente o valor para a API do pagar.me
            transaction.Shipping = new Shipping
            {
                Name         = enderecoEntrega.Nome,
                Fee          = Mascara.ConverterValorPagarMe(Convert.ToDecimal(frete.Valor)),
                DeliveryDate = Today.AddDays(this._configuration.GetValue <int>("Frete:DiasPreparo")).AddDays(frete.Prazo).ToString("yyyy-MM-dd"),
                Expedited    = false,
                Address      = new Address()
                {
                    Country      = "br",
                    State        = enderecoEntrega.Estado,
                    City         = enderecoEntrega.Cidade,
                    Neighborhood = enderecoEntrega.Bairro,
                    Street       = enderecoEntrega.Endereco + " " + enderecoEntrega.Complemento,
                    StreetNumber = enderecoEntrega.Numero,
                    Zipcode      = Mascara.Remover(enderecoEntrega.CEP)
                }
            };

            Item[] itens = new Item[produtos.Count];

            // Converter corretamente o valor para a API do pagar.me
            for (var i = 0; i < produtos.Count; i++)
            {
                var item  = produtos[i];
                var itemA = new Item()
                {
                    Id        = item.Id.ToString(),
                    Title     = item.Nome,
                    Quantity  = item.QuantidadeProdutoCarrinho,
                    Tangible  = true,
                    UnitPrice = Mascara.ConverterValorPagarMe(item.Valor)
                };

                itens[i] = itemA;
            }

            transaction.Item         = itens;
            transaction.Amount       = Mascara.ConverterValorPagarMe(parcelamento.Valor);
            transaction.Installments = parcelamento.Numero;
            transaction.Save();
            return(new { TransactionId = transaction.Id });
        }
        public Transaction GerarPagCartaoCredito(Parcela parcela, Cartao cartao, List <ProdutoItem> produtos, EnderecoEntrega enderecoEntrega, ValorPrazoFrete frete)
        {
            Cliente cliente = _loginCliente.BuscaClienteSessao();

            PagarMeService.DefaultApiKey        = _conf.GetValue <string>("PagarMe:APIKey");
            PagarMeService.DefaultEncryptionKey = _conf.GetValue <string>("PagarMe:EncriptionKey");

            Card card = new Card()
            {
                Number         = cartao.Numero,
                Cvv            = cartao.CVV,
                ExpirationDate = cartao.VencimentoMM + cartao.VencimentoYY,
                HolderName     = cartao.Nome,
            };

            card.Save();

            Transaction transaction = new Transaction();

            transaction.PaymentMethod = PaymentMethod.CreditCard;

            transaction.Card = new Card
            {
                Id = card.Id
            };

            transaction.Customer = new Customer
            {
                ExternalId = cliente.Id.ToString(),
                Name       = cliente.Nome,
                Type       = CustomerType.Individual,
                Country    = "br",
                Email      = cliente.Email,
                Documents  = new[]
                {
                    new Document {
                        Type   = DocumentType.Cpf,
                        Number = RemoverMascara(cliente.CPF)
                    },
                },
                PhoneNumbers = new string[]
                {
                    "+55" + RemoverMascara(cliente.Telefone),
                },
                Birthday = cliente.Nascimento.ToString("yyyy-MM-dd")
            };

            transaction.Billing = new Billing
            {
                Name    = cliente.Nome,
                Address = new Address()
                {
                    Country       = "br",
                    State         = cliente.Estado,
                    City          = cliente.Cidade,
                    Neighborhood  = cliente.Bairro,
                    Street        = cliente.Rua,
                    Complementary = cliente.Complemento,
                    StreetNumber  = cliente.Numero.ToString(),
                    Zipcode       = RemoverMascara(cliente.CEP)
                }
            };

            var Today = DateTime.Now;

            transaction.Shipping = new Shipping
            {
                Name         = enderecoEntrega.Nome,
                Fee          = (int)(frete.Valor * 100),
                DeliveryDate = Today.AddDays(3 + frete.Prazo).ToString("yyyy-MM-dd"),
                Expedited    = false,
                Address      = new Address()
                {
                    Country       = "br",
                    State         = enderecoEntrega.Estado,
                    City          = enderecoEntrega.Cidade,
                    Neighborhood  = enderecoEntrega.Bairro,
                    Street        = enderecoEntrega.Rua,
                    Complementary = enderecoEntrega.Complemento == null ? "SEM COMPLEMENTO" : enderecoEntrega.Complemento,
                    StreetNumber  = enderecoEntrega.Numero.ToString(),
                    Zipcode       = RemoverMascara(enderecoEntrega.CEP)
                }
            };

            transaction.Item = new Item[produtos.Count];

            for (int i = 0; i < produtos.Count; i++)
            {
                transaction.Item[i] = new Item()
                {
                    Id        = produtos[i].Id.ToString(),
                    Title     = produtos[i].Nome,
                    Quantity  = produtos[i].QuantidadeCarrinhoProduto,
                    Tangible  = true,
                    UnitPrice = (int)(produtos[i].Valor * 100)
                };
            }
            transaction.Amount       = (int)(parcela.Total * 100);
            transaction.Installments = parcela.ParcelaQuantidade;
            transaction.Save();
            transaction.Customer.Gender = cliente.Sexo == "M" ? Gender.Male : Gender.Female;
            return(transaction);
        }
Exemplo n.º 21
0
        public Transaction GerarPagCartaoCredito(CartaoCredito cartao, Parcelamento parcelamento, EnderecoEntrega enderecoEntrega, ValorPrazoFrete valorFrete, List <ItemVendaViewModel> produtos, Usuario usuario)
        {
            Usuario cliente = usuario;

            PagarMeService.DefaultApiKey        = DefaultApiKey;
            PagarMeService.DefaultEncryptionKey = DefaultEncryptionKey;

            Card card = new Card();

            card.Number         = cartao.NumeroCartao;
            card.HolderName     = cartao.NomeNoCartao;
            card.ExpirationDate = cartao.VecimentoMM + cartao.VecimentoYY;
            card.Cvv            = cartao.CodigoSeguranca;

            card.Save();

            Transaction transaction = new Transaction();

            transaction.PaymentMethod = PaymentMethod.CreditCard;
            transaction.Card          = new Card
            {
                Id = card.Id
            };

            transaction.Customer = new Customer
            {
                ExternalId = cliente.Id.ToString(),
                Name       = cliente.Nome,
                Type       = CustomerType.Individual,
                Country    = "br",
                Email      = cliente.Email,
                Documents  = new[] {
                    new Document {
                        Type   = DocumentType.Cpf,
                        Number = Mascara.Remover(cliente.CPFCNPJ)
                    }
                },
                PhoneNumbers = new string[]
                {
                    "+55" + Mascara.Remover(cliente.Telefone)
                },
                Birthday = cliente.Nascimento.ToString("yyyy-MM-dd")
            };

            transaction.Billing = new Billing
            {
                Name    = cliente.Nome,
                Address = new Address()
                {
                    Country      = "br",
                    State        = enderecoEntrega.Estado,
                    City         = enderecoEntrega.Cidade,
                    Neighborhood = enderecoEntrega.Bairro,
                    Street       = enderecoEntrega.Endereco + " " + enderecoEntrega.Complemento,
                    StreetNumber = enderecoEntrega.Numero,
                    Zipcode      = Mascara.Remover(enderecoEntrega.CEP)
                }
            };

            var Today = DateTime.Now;
            var fee   = Convert.ToDecimal(valorFrete.Valor);

            transaction.Shipping = new Shipping
            {
                Name         = enderecoEntrega.Nome,
                Fee          = Mascara.ConverterValorPagarMe(fee),
                DeliveryDate = Today.AddDays(DiasNaEmpresa).AddDays(valorFrete.Prazo).ToString("yyyy-MM-dd"),
                Expedited    = false,
                Address      = new Address()
                {
                    Country      = "br",
                    State        = enderecoEntrega.Estado,
                    City         = enderecoEntrega.Cidade,
                    Neighborhood = enderecoEntrega.Bairro,
                    Street       = enderecoEntrega.Endereco + " " + enderecoEntrega.Complemento,
                    StreetNumber = enderecoEntrega.Numero,
                    Zipcode      = Mascara.Remover(enderecoEntrega.CEP)
                }
            };

            Item[] itens = new Item[produtos.Count];

            for (var i = 0; i < produtos.Count; i++)
            {
                var item = produtos[i];
                itens[i] = new Item()
                {
                    Id        = item.Produto.ID.ToString(),
                    Title     = item.Produto.Nome,
                    Quantity  = item.Quantidade,
                    Tangible  = true,
                    UnitPrice = Mascara.ConverterValorPagarMe(item.Produto.Valor),
                };
            }

            transaction.Item         = itens;
            transaction.Amount       = Mascara.ConverterValorPagarMe(parcelamento.Valor);
            transaction.Installments = parcelamento.Numero;

            transaction.Save();

            transaction.Customer.Gender = (cliente.Sexo == Enums.Sexo.Masculino) ? Gender.Male : Gender.Female;
            return(transaction);
        }
        public Transaction GerarPagCartaoCredito(CartaoCredito cartao, Parcelamento parcelamento, EnderecoEntrega enderecoEntrega, ValorPrazoFrete valorFrete, List <ProdutoItem> produtos)
        {
            Cliente cliente = _loginCliente.GetCliente();

            PagarMeService.DefaultApiKey        = _configuration.GetValue <String>("Pagamento:PagarMe:ApiKey");
            PagarMeService.DefaultEncryptionKey = _configuration.GetValue <String>("Pagamento:PagarMe:EncryptionKey");

            Card card = new Card();

            card.Number         = cartao.NumeroCartao;
            card.HolderName     = cartao.NomeNoCartao;
            card.ExpirationDate = cartao.VencimentoMM + cartao.VencimentoYY;
            card.Cvv            = cartao.CodigoSeguranca;

            card.Save();

            Transaction transaction = new Transaction();

            transaction.PaymentMethod = PaymentMethod.CreditCard;

            /*
             * Não sera feito transaction.postbackurl
             * - Parâmetro importante para que seu site seja informado sobre todas as mudanças de status ocorridas no Pagar.Me.
             * URL 1: https://pagarme.zendesk.com/hc/pt-br/articles/205973476-Quando-o-POSTback-%C3%A9-enviado-
             * URL 2: https://docs.pagar.me/v1/reference#criar-transacao
             */

            transaction.Card = new Card
            {
                Id = card.Id
            };

            transaction.Customer = new Customer
            {
                ExternalId = cliente.Id.ToString(),
                Name       = cliente.Nome,
                Type       = CustomerType.Individual,
                Country    = "br",
                Email      = cliente.Email,
                Documents  = new[] {
                    new Document {
                        Type   = DocumentType.Cpf,
                        Number = Mascara.Remover(cliente.CPF)
                    }
                },
                PhoneNumbers = new string[]
                {
                    "+55" + Mascara.Remover(cliente.Telefone)
                },
                Birthday = cliente.Nascimento.ToString("yyyy-MM-dd")
            };

            transaction.Billing = new Billing
            {
                Name    = cliente.Nome,
                Address = new Address()
                {
                    Country      = "br",
                    State        = cliente.Estado,
                    City         = cliente.Cidade,
                    Neighborhood = cliente.Bairro,
                    Street       = cliente.Endereco + " " + cliente.Complemento,
                    StreetNumber = cliente.Numero,
                    Zipcode      = Mascara.Remover(cliente.CEP)
                }
            };

            var Today = DateTime.Now;
            var fee   = Convert.ToDecimal(valorFrete.Valor);

            transaction.Shipping = new Shipping
            {
                Name         = enderecoEntrega.Nome,
                Fee          = Mascara.ConverterValorPagarMe(fee),
                DeliveryDate = Today.AddDays(_configuration.GetValue <int>("Frete:DiasParaPostagem")).AddDays(valorFrete.Prazo).ToString("yyyy-MM-dd"),
                Expedited    = false,
                Address      = new Address()
                {
                    Country      = "br",
                    State        = enderecoEntrega.Estado,
                    City         = enderecoEntrega.Cidade,
                    Neighborhood = enderecoEntrega.Bairro,
                    Street       = enderecoEntrega.Endereco + " " + enderecoEntrega.Complemento,
                    StreetNumber = enderecoEntrega.Numero,
                    Zipcode      = Mascara.Remover(enderecoEntrega.CEP)
                }
            };

            Item[] itens = new Item[produtos.Count];

            for (var i = 0; i < produtos.Count; i++)
            {
                var item = produtos[i];

                var itemA = new Item()
                {
                    Id        = item.Id.ToString(),
                    Title     = item.Nome,
                    Quantity  = item.UnidadesPedidas,
                    Tangible  = true,
                    UnitPrice = Mascara.ConverterValorPagarMe(item.Valor)
                };


                itens[i] = itemA;
            }

            transaction.Item         = itens;
            transaction.Amount       = Mascara.ConverterValorPagarMe(parcelamento.Valor);
            transaction.Installments = parcelamento.Numero;

            transaction.Save();

            transaction.Customer.Gender = (cliente.Sexo == "M") ? Gender.Male : Gender.Female;
            return(transaction);
        }
        public Transaction GerarBoleto(decimal valor, List <ProdutoItem> produtos, EnderecoEntrega enderecoEntrega, ValorPrazoFrete valorFrete)
        {
            Cliente cliente = _loginCliente.GetCliente();

            PagarMeService.DefaultApiKey        = _configuration.GetValue <String>("Pagamento:PagarMe:ApiKey");
            PagarMeService.DefaultEncryptionKey = _configuration.GetValue <String>("Pagamento:PagarMe:EncryptionKey");
            int DaysExpire = _configuration.GetValue <int>("Pagamento:PagarMe:BoletoDiaExpiracao");

            Transaction transaction = new Transaction();

            transaction.Amount               = Mascara.ConverterValorPagarMe(valor);
            transaction.PaymentMethod        = PaymentMethod.Boleto;
            transaction.BoletoExpirationDate = DateTime.Now.AddDays(DaysExpire);
            transaction.Customer             = new Customer
            {
                ExternalId = cliente.Id.ToString(),
                Name       = cliente.Nome,
                Type       = CustomerType.Individual,
                Country    = "br",
                Email      = cliente.Email,
                Documents  = new[] {
                    new Document {
                        Type   = DocumentType.Cpf,
                        Number = Mascara.Remover(cliente.CPF)
                    }
                },
                PhoneNumbers = new string[]
                {
                    "+55" + Mascara.Remover(cliente.Telefone)
                },
                Birthday = cliente.Nascimento.ToString("yyyy-MM-dd")
            };

            var Today = DateTime.Now;
            var fee   = Convert.ToDecimal(valorFrete.Valor);

            transaction.Shipping = new Shipping
            {
                Name         = enderecoEntrega.Nome,
                Fee          = Mascara.ConverterValorPagarMe(fee),
                DeliveryDate = Today.AddDays(_configuration.GetValue <int>("Frete:DiasNaEmpresa")).AddDays(valorFrete.Prazo).ToString("yyyy-MM-dd"),
                Expedited    = false,
                Address      = new Address()
                {
                    Country      = "br",
                    State        = enderecoEntrega.Estado,
                    City         = enderecoEntrega.Cidade,
                    Neighborhood = enderecoEntrega.Bairro,
                    Street       = enderecoEntrega.Endereco + " " + enderecoEntrega.Complemento,
                    StreetNumber = enderecoEntrega.Numero,
                    Zipcode      = Mascara.Remover(enderecoEntrega.CEP)
                }
            };

            Item[] itens = new Item[produtos.Count];

            for (var i = 0; i < produtos.Count; i++)
            {
                var item = produtos[i];

                var itemA = new Item()
                {
                    Id        = item.Id.ToString(),
                    Title     = item.Nome,
                    Quantity  = item.UnidadesPedidas,
                    Tangible  = true,
                    UnitPrice = Mascara.ConverterValorPagarMe(item.Valor)
                };


                itens[i] = itemA;
            }

            transaction.Item = itens;

            transaction.Save();

            transaction.Customer.Gender = (cliente.Sexo == "M") ? Gender.Male : Gender.Female;
            return(transaction);
        }