/// <summary>
        /// Retorna todos os boletos informando o cliente e status.
        /// </summary>
        /// <param name="cliente"></param>
        /// <param name="dominio"></param>
        /// <param name="statusBoleto"></param>
        /// <returns></returns>
        public async Task <JsonResultDictionaryBoleto> GetBoletosClienteByStatus(
            DadosCliente cliente,
            DadosDominio dominio,
            StatusBoleto statusBoleto)
        {
            if (cliente == null)
            {
                throw new ArgumentNullException("cliente");
            }

            if (dominio == null)
            {
                throw new ArgumentNullException("dominio");
            }

            string url = string.Format("https://api.kinghost.net/boleto/{0}/{1}/{2}",
                                       cliente.IdCliente,
                                       dominio.Id,
                                       statusBoleto.ToString());

            HttpResponseMessage response = await this.HttpClient.GetAsync(url);

            if (response.IsSuccessStatusCode)
            {
                var boletos = await response.Content.ReadAsStringAsync();

                return(new JavaScriptSerializer().Deserialize <JsonResultDictionaryBoleto>(boletos.ToString()));
            }

            return(null);
        }
        /// <summary>
        /// Cria um novo boleto no banco de dados.
        /// </summary>
        /// <param name="cliente"></param>
        /// <param name="dominio"></param>
        /// <param name="vencimento"></param>
        /// <param name="valor"></param>
        /// <param name="instrucao"></param>
        /// <param name="descricao"></param>
        public async Task <JsonResultBoleto> CreateNewBoleto(
            DadosCliente cliente,
            DadosDominio dominio,
            DateTime vencimento,
            Double valor,
            string instrucao,
            string descricao)
        {
            if (cliente == null)
            {
                throw new ArgumentNullException("cliente");
            }

            if (dominio == null)
            {
                throw new ArgumentNullException("dominio");
            }

            // Prepara os valores que serão postados.
            var postData = new List <KeyValuePair <string, string> >();

            postData.Add(new KeyValuePair <string, string>("idCliente", Convert.ToString(cliente.IdCliente)));
            postData.Add(new KeyValuePair <string, string>("idDominio", Convert.ToString(dominio.Id)));
            postData.Add(new KeyValuePair <string, string>("idBanco", "3"));
            postData.Add(new KeyValuePair <string, string>("vencimento", vencimento.ToString("yyyy-MM-dd")));
            postData.Add(new KeyValuePair <string, string>("valor", Convert.ToString(valor)));
            postData.Add(new KeyValuePair <string, string>("instrucao", instrucao));
            postData.Add(new KeyValuePair <string, string>("desc", descricao));

            HttpContent content = new FormUrlEncodedContent(postData);

            HttpResponseMessage response = await this.HttpClient.PostAsync("https://api.kinghost.net/boleto/", content);

            if (response.IsSuccessStatusCode)
            {
                var boletos = await response.Content.ReadAsStringAsync();

                return(new JavaScriptSerializer().Deserialize <JsonResultBoleto>(boletos.ToString()));
            }

            return(null);
        }
Esempio n. 3
0
        public void EnviaBoletos()
        {
            ThreadPool.QueueUserWorkItem(x =>
            {
                while (true)
                {
                    try
                    {
                        // Busca os clientes que devem enviar boletos.
                        var clientesEnvioBoleto = this.DbUtils.GetClientesParaEnvio();

                        foreach (var cliente in clientesEnvioBoleto)
                        {
                            // Se o boleto já foi enviado no dia atual, não deve ser enviado novamente.
                            if (cliente.DtHrUltimoEnvio != null && cliente.DtHrUltimoEnvio.Value.Date.Equals(DateTime.Now.Date))
                            {
                                continue;
                            }

                            // Verifica se a data de envio já passou e verifica se o boleto não foi enviado no mês atual.
                            if ((cliente.DiaEnvio <= DateTime.Now.Day) && (cliente.DtHrUltimoEnvio == null || cliente.DtHrUltimoEnvio.Value.Month != DateTime.Now.Month))
                            {
                                // Gera o boleto.
                                using (var cmd = new KingHostCommands())
                                {
                                    var dadosCliente = new DadosCliente()
                                    {
                                        IdCliente = cliente.CodigoCliente
                                    };
                                    var dadosDominio = new DadosDominio()
                                    {
                                        Id = cliente.CodigoDominio
                                    };

                                    var resultBoleto = cmd.CreateNewBoleto(
                                        dadosCliente,
                                        dadosDominio,
                                        DateTime.Now.AddDays(7),
                                        cliente.Valor,
                                        "Instrução de teste",
                                        "Descrição de teste");

                                    // Espera o boleto ser gerado.
                                    resultBoleto.Wait();

                                    if (!resultBoleto.Result.Success)
                                    {
                                        throw new Exception("Algum problema aconteceu ao gerar o boleto.");
                                    }

                                    // Envia o e-mail.
                                    {
                                        string subject = string.Format(
                                            "Boleto para pagamento da hospedagem do domínio: {0}",
                                            cliente.Dominio);

                                        string body = string.Format(@"
                                            Prezado(a) {0},
                                            <br><br>
                                            Seguem os dados para pagamento de sua fatura. Boleto bancário disponível para impressão em:<br>
                                            <a href='{1}'>{1}</a>
                                            <br><br>
                                            VALOR A PAGAR: R$ {2}<br>
                                            DOMÍNIO: {3}
                                            <br><br>
                                            Atenciosamente,<br>
                                            Financeiro Agência WD7
                                            <br><br>
                                            [email protected]<br>
                                            www.agenciawd7.com.br", cliente.Nome, resultBoleto.Result.Body.Url, cliente.Valor, cliente.Dominio);

                                        string to = string.Format("{0}; [email protected]", cliente.Email);

                                        Email.Send(to, subject, body);
                                    }

                                    // Atualiza a data de envio.
                                    this.DbUtils.AtualizaDataEnvio(cliente.IdBoleto);

                                    // Salva no histórico que o boleto foi enviado.
                                    this.DbUtils.InsereHistorico(cliente.IdBoleto, resultBoleto.Result.Body);
                                }
                            }
                        }

                        Thread.Sleep(600000);
                    }
                    catch (Exception ex)
                    {
                        this.SaveError(ex);
                        Thread.Sleep(600000);
                    }
                }
            });
        }