Ejemplo n.º 1
0
        /// <summary>
        /// Retrieve shipping rate
        /// </summary>
        /// <param name="zipcode"></param>
        /// <param name="peso"></param>
        /// <returns></returns>
        public Decimal GetShippingPriceUPS(String zipcode, Decimal peso)
        {
            if (String.IsNullOrWhiteSpace(zipcode))
            {
                return new Decimal(0);
            }
            //recupera os valores dos parametros para UPS
            var parameters = new ParametroService().GetByParameterType((int)TipoParametro.TipoDeEntrega);
            var login = parameters.Where(x => x.Nome == "UPS Login ID").FirstOrDefault().Valor;
            var password = parameters.Where(x => x.Nome == "UPS Password").FirstOrDefault().Valor;
            var access = parameters.Where(x => x.Nome == "UPS Access").FirstOrDefault().Valor;
            var service = parameters.Where(x => x.Nome == "UPS Service").FirstOrDefault().Valor;

            var ups = new UPS(access, login, password, service, Settings.WebServiceUPS);
            decimal minimumWeight = (decimal)0.100;
            peso = peso < minimumWeight ? minimumWeight : peso;
            var totalShipping = ups.GetShipRate(zipcode, peso);

            return totalShipping;
        }
Ejemplo n.º 2
0
        /// <summary>
        /// Form to submit values to gateway
        /// </summary>
        /// <param name="id">idPedido</param>
        /// <returns></returns>
        public ActionResult Payment(int id)
        {
            if (User.Identity.IsAuthenticated)
            {
                ViewBag.Title = Resources.Resource.Pagamento_Titulo;

                //get order details
                var idPedido = new PedidoService().GetRecords(x => x.NumeroPedido == id).FirstOrDefault().IdPedido;
                var pedido = new PedidoService().GetById(idPedido, GetCurrentIdIdioma());

                if (pedido.Status == StatusPedido.AguardandoPagamento &&
                    FormsAuthenticationUtil.UserAuthenticated.IdCliente.HasValue &&
                    FormsAuthenticationUtil.UserAuthenticated.IdCliente.Value == pedido.IdCliente)
                {
                    //get shipping address details
                    var endereco = new EnderecoService().GetShippingAddress(pedido.IdPedido);

                    var cultureInfo = new CultureInfo("en-US");

                    var rgService = new RequestGatewayService();
                    rgService.Model = new RequestGatewayModel
                    {
                        PedidoNumero = pedido.Numero.HasValue ? pedido.Numero.Value.ToString(CultureInfo.InvariantCulture) : string.Empty,
                        PedidoValorFrete = pedido.ValorFrete.ToString(cultureInfo),
                        PedidoValorTaxas = pedido.ValorTaxa.ToString(cultureInfo),
                        PedidoValorManuseio = pedido.ValorManuseio.ToString(cultureInfo),
                        PedidoSubTotal = pedido.Subtotal.ToString(cultureInfo),
                        PedidoTotal = pedido.Total.ToString(cultureInfo),

                        ClienteId = pedido.IdCliente.ToString(CultureInfo.InvariantCulture),
                        ClienteSobrenome = pedido.NomeCliente.Trim().Split(' ').Length > 1 ? pedido.NomeCliente.Trim().Split(' ')[0] : pedido.NomeCliente.Trim(),
                        ClienteNome = pedido.NomeCliente.Trim().Split(' ').Length > 1 ? pedido.NomeCliente.Trim().Substring(pedido.NomeCliente.IndexOf(' '), pedido.NomeCliente.Trim().Length - pedido.NomeCliente.Trim().IndexOf(' ')) : string.Empty,

                        EnderecoCep = endereco.Cep,
                        EnderecoLogradouro = endereco.Logradouro,
                        EnderecoCidade = endereco.IdCidade != null ? endereco.Cidade1.Nome : endereco.Cidade,
                        EnderecoEstado = endereco.IdEstado != null ? endereco.Estado.Nome : string.Empty,
                        EnderecoEmail = endereco.EmailEntrega,
                        EnderecoTelefone = endereco.TelefoneEntrega
                    };

                    switch (pedido.FormaPagamento)
                    {
                        case FormaPagamento.Authorize:
                            var parameters = new ParametroService().GetByParameterType((int)TipoParametro.FormaDePagamento);
                            var apiLogin = parameters.Where(x => x.Nome == "Login ApI").FirstOrDefault();
                            var transKey = parameters.Where(x => x.Nome == "Transaction Key").FirstOrDefault();
                            var urlResponse = parameters.Where(x => x.Nome == "Url de retorno Authorize").FirstOrDefault();

                            if (apiLogin != null && transKey != null && urlResponse != null)
                            {
                                rgService.QueryString = Settings.AuthorizeQueryString;
                                rgService.Model.GatewayUsuario = apiLogin.Valor;
                                rgService.Model.GatewayUrlRequest = Settings.AuthorizeRequest;
                                rgService.Model.GatewayUrlResponse = urlResponse.Valor;

                                rgService.AdicionalParameters = new Dictionary<String, String>();
                                var timeStamp = ((int)(DateTime.UtcNow - new DateTime(1970, 1, 1)).TotalSeconds).ToString();
                                string fingerprint = WebHelpers.HMAC_MD5(transKey.Valor, rgService.Model.GatewayUsuario + "^" + rgService.Model.PedidoNumero + "^" + timeStamp + "^" + rgService.Model.PedidoTotal + "^");

                                rgService.AdicionalParameters.Add("timeStamp", timeStamp);
                                rgService.AdicionalParameters.Add("fingerprint", fingerprint);
                            }

                            return View(rgService);
                        case FormaPagamento.Paypal:
                            var parametros = new ParametroService().GetByParameterType((int)TipoParametro.FormaDePagamento);
                            var business = parametros.Where(x => x.Nome == "Business").FirstOrDefault().Valor;
                            var urlRetorno = parametros.Where(x => x.Nome == "Url de retorno Paypal").FirstOrDefault().Valor;
                            var urlNotificacao = parametros.Where(x => x.Nome == "Url de notificação").FirstOrDefault().Valor;
                            var urlImagem = parametros.Where(x => x.Nome == "Url da Imagem").FirstOrDefault().Valor;

                            rgService.QueryString = Settings.PaypalQueryString;
                            rgService.Model.GatewayUsuario = business;
                            rgService.Model.GatewayUrlRequest = Settings.PaypalRequest;
                            rgService.Model.GatewayUrlResponse = urlRetorno;

                            rgService.AdicionalParameters = new Dictionary<string, string>();
                            rgService.AdicionalParameters.Add("lc", "PT");// CultureInfo.CurrentUICulture.TextInfo.CultureName.Split('-')[1]
                            rgService.AdicionalParameters.Add("image_url", urlImagem);
                            rgService.AdicionalParameters.Add("notify_url", urlNotificacao);

                            return View(rgService);
                        case FormaPagamento.BoletoBradesco:
                            var paramBoleto = new ParametroService().GetByParameterType((int)TipoParametro.FormaDePagamento);
                            var urlBoleto = paramBoleto.FirstOrDefault(m => m.Nome == "Boleto Bradesco URL") ?? new Parametro();
                            var numLoja = paramBoleto.FirstOrDefault(m => m.Nome == "Boleto Bradesco Numero Loja") ?? new Parametro();

                            rgService.Model.PedidoNumero = idPedido.ToString(CultureInfo.InvariantCulture);
                            rgService.Model.GatewayUrlRequest = string.Format(urlBoleto.Valor, numLoja.Valor, id);
                            rgService.QueryString = string.Format(Settings.BoletoBradescoQueryString, numLoja.Valor, id);

                            return View("PaymentBoleto", rgService);
                        default:
                            return AccessDenied();
                    }
                }
            }
            return AccessDenied();
        }
Ejemplo n.º 3
0
        /// <summary>
        /// Confirma o pedido do Paypal e salva os detalhes
        /// </summary>
        /// <param name="transactionId"></param>
        /// <returns></returns>
        protected PedidoModel ConfirmPaypalOrder(string transactionId)
        {
            var parameters = new ParametroService().GetByParameterType((int)TipoParametro.FormaDePagamento);
            var token = parameters.Where(x => x.Nome == "Token").FirstOrDefault().Valor;

            //Build a url to call Paypal and get data about the Transaction
            //ex. url?cmd=_notify-synch&tx=[TransactionID]&at=[PDTIdentityToken]
            var query = string.Format("cmd=_notify-synch&tx={0}&at={1}", transactionId, token);
            var urlRequest = Settings.PaypalRequest;
            var requestUrl = string.Format("{0}?{1}", urlRequest, query);

            var req = (HttpWebRequest)WebRequest.Create(requestUrl);
            req.Method = "POST";
            req.ContentType = "application/x-www-form-urlencoded";
            req.ContentLength = query.Length;

            var stOut = new StreamWriter(req.GetRequestStream(), Encoding.ASCII);
            stOut.Write(query);
            stOut.Close();

            // Do the request to PayPal and get the response
            var stIn = new StreamReader(req.GetResponse().GetResponseStream());
            var strResponse = stIn.ReadToEnd();
            stIn.Close();

            // If response was SUCCESS, parse response string and output details
            if (strResponse.StartsWith("SUCCESS"))
            {
                //Verify order
                var idPedido = UpdatePaypalTransaction(strResponse);

                try
                {
                    //Generate Comission
                    bool resultComission = new WS.Commissions.Commissions().GenerateCommissions(Settings.AutenticationKeyEarningSystem, idPedido, GetIdClientCookie(this));
                }
                catch (Exception ex)
                {
                    LogService.Log("WS.Commissions.Commissions().GenerateCommissions()", ex.Message, TipoLog.Erro);
                }

                if (idPedido != 0)
                {
                    var pedido = new PedidoService().GetById(idPedido, GetCurrentIdIdioma());
                    return pedido;
                }
                throw new Exception(Resources.Resource.Msg_Order_PedidoNaoEncontrado);
            }
            throw new Exception(Resources.Resource.Msg_Order_MensagemNaoValidadaPaypal);
        }
Ejemplo n.º 4
0
        public ActionResult ConfirmationAuthorize(int? id)
        {
            try
            {
                if (Request.RequestType == "POST")
                {
                    int invoiceNumber = 0;
                    if (Request.Params["x_invoice_num"] != null)
                        invoiceNumber = Convert.ToInt32(Request.Params["x_invoice_num"]);

                    var pedido = new PedidoService().GetRecords(x => x.NumeroPedido == invoiceNumber).FirstOrDefault();

                    //Verify order
                    if (pedido != null)
                    {
                        var parameters = new ParametroService().GetByParameterType((int)TipoParametro.FormaDePagamento);
                        var authorizeHashMD5 = parameters.Where(x => x.Nome == "MD5 Hash").FirstOrDefault();
                        var apiLogin = parameters.Where(x => x.Nome == "Login ApI").FirstOrDefault();
                        var transKey = parameters.Where(x => x.Nome == "Transaction Key").FirstOrDefault();
                        var urlResponse = parameters.Where(x => x.Nome == "Url de retorno Authorize").FirstOrDefault();

                        var transId = Request.Params["x_trans_id"] != null ? Request.Params["x_trans_id"] : string.Empty;
                        var ammount = Request.Params["x_amount"] != null ? Convert.ToDecimal(Request.Params["x_amount"]) : 0;

                        var md5HashValidator = HashValueToMD5(authorizeHashMD5.Valor + apiLogin.Valor + transId + ammount);

                        var md5HashFromAuthorize = Request.Params["x_MD5_Hash"] != null ? Request.Params["x_MD5_Hash"] : string.Empty;
                        if (md5HashFromAuthorize == md5HashValidator)
                        {
                            if (pedido.IdFormaPagamento == (int)FormaPagamento.Authorize)
                            {
                                var retorno = new Ecommerce_RetornoPagamento
                                {
                                    IdPedido = pedido.IdPedido,
                                    DataInclusao = DateTime.Now,
                                    IdFormaPagamento = pedido.IdFormaPagamento.Value,
                                    Resultado = Request.Params.ToString() //TODO: Serializar e salvar em XML (rvsm)
                                };
                                new PedidoService().InsertRetornoPagamento(retorno);
                            }
                            else
                            {
                                var ex = new Exception(Resources.Resource.Msg_Order_MetodoPagamentoInvalido);
                                LogService.Log("Order.ConfirmationAuthorize()", ex.Message, TipoLog.Erro);
                                throw ex;
                            }

                            //Atualiza o status do pedido
                            pedido.StatusPedido = (int)StatusPedido.EmProcessamento;
                            new PedidoService().UpdateObject(pedido);
                            return PartialView("ConfirmationAuthorize", pedido.IdPedido);
                        }
                        throw new Exception(Resources.Resource.Msg_Order_TransacaoNaoValidada);
                    }
                    throw new Exception(Resources.Resource.Msg_Order_TransacaoNaoDetectada);
                }
                throw new Exception(Resources.Resource.Msg_Order_NaoHouveResposta);
            }
            catch (Exception ex)
            {
                LogService.Log("Order.ConfirmationAuthorize()", ex.Message, TipoLog.Erro);
                throw ex;
            }
        }