Ejemplo n.º 1
0
        public ActionResult ShowImage(string mediaId)
        {
            var smallFileName  = CustomerMessage.GetCacheSmallPathForTemporaryMedia(mediaId);
            var targetFileName = smallFileName;

            if (!System.IO.File.Exists(smallFileName))
            {                                         //如果没有小图,说明没进行缩小处理过
                var fileName = CustomerMessage.GetCachePathForTemporaryMedia(mediaId);
                if (!System.IO.File.Exists(fileName)) //如果没有原图,则需要下载下来
                {
                    var accessToken = GetAccessToken();
                    using (FileStream createFs = new FileStream(fileName, FileMode.Create))
                    {
                        MediaApi.Get(accessToken, mediaId, createFs);
                    }
                }
                try
                {
                    ResizeImage(fileName, smallFileName);
                }
                catch (Exception ex)
                {
                    _logger.LogError(ex, "缩放出错,文件名:{0}", fileName);
                    targetFileName = fileName; //显示的时候用原图显示。
                }
            }

            FileStream fs = new FileStream(targetFileName, FileMode.Open);

            return(File(fs, "image/jpeg"));
        }
Ejemplo n.º 2
0
        public MappedCustomerMessage Handle(CustomerMessage message)
        {
            var mapped = new MappedCustomerMessage()
            {
                CustomerId = message.CustomerId,
                SourceId   = message.SourceId,
                Data       = new Dictionary <string, Dictionary <string, object> >()
            };

            var sourceFieldsMaps = _fieldMaps.Where(s => s.SourceField.Source.Id == message.SourceId)
                                   .ToList();

            foreach (var data in message.Data)
            {
                var values = new Dictionary <string, object>();

                foreach (var item in sourceFieldsMaps.Where(fm => fm.SourceField.FieldName == data.Key && fm.CustomerField != null))
                {
                    values.Add(message.SourceId.ToString(), Convert.ChangeType(data.Value, item.CustomerField.FieldType));
                    mapped.Data.Add(item.CustomerField.FieldName, values);
                }
            }

            return(mapped);
        }
        private void miDelete_Click(object sender, EventArgs e)
        {
            if (dtgCustomerMessage.SelectedRows.Count > 0)
            {
                try
                {
                    object cellValue         = dtgCustomerMessage.SelectedRows[0].Cells["ID"].Value;
                    int    customerMessageID = (int)cellValue;

                    _customerMessage = _customerMessageBLL.GetById(customerMessageID);

                    DialogResult dr = MessageBox.Show(_customerMessage.Name + " " + _customerMessage.Description + " " + " adlı mesajı silmek istediğinize emin misiniz", "Dikkat", MessageBoxButtons.YesNo);


                    if (dr == DialogResult.Yes)
                    {
                        _customerMessageBLL.Remove(_customerMessage);
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }
            }
        }
Ejemplo n.º 4
0
        public async Task <APIResult> SendCustomerImage([FromBody] SendCustomerImageArgsModel args)
        {
            if (string.IsNullOrEmpty(args.OpenId))
            {
                throw new ArgumentNullException("OpenId");
            }

            var user = GetUsername();

            wechatCoreDb.EnsureIsCustomerSessionWorker(args.OpenId, user);


            string requestStrValue      = args.Data.Substring(args.Data.IndexOf(',') + 1);                              //代表 图片 的base64编码数据
            string requestFileExtension = args.Data.Split(new char[] { ';' })[0].Substring(args.Data.IndexOf('/') + 1); //获取后缀名

            var buffer     = Convert.FromBase64String(requestStrValue);
            var folderPath = $"{Directory.GetCurrentDirectory()}/App_Data/Weixin/TemporaryMedia";

            if (!Directory.Exists(folderPath))
            {
                Directory.CreateDirectory(folderPath);
            }
            var fileName = $"{folderPath}/{DateTime.Now.ToString("yyyyMMddHHhhss")}{CommonUtil.CreateNoncestr(6)}.{requestFileExtension}";

            using (FileStream fs = new FileStream(fileName, FileMode.Create))
            {
                fs.Write(buffer, 0, buffer.Length);
                ////通过代码审查说,使用了using,不需要再次调用close
                //fs.Close();
            }

            //fileName = @"C:\Xiang\Temp\1.jpg";
            var accessToken = GetAccessToken();
            //var uploadResult = Senparc.Weixin.MP.AdvancedAPIs.MediaApi.UploadTemporaryMedia(accessToken, UploadMediaFileType.image, fileName);

            var uploadResult = await WechatMediaApiProxy.UploadAsync <Senparc.Weixin.MP.AdvancedAPIs.Media.UploadTemporaryMediaResult>(accessToken, "image", fileName);

            var data = new
            {
                msgType = "image",
                mediaId = uploadResult.media_id
            };

            System.IO.File.Move(fileName, CustomerMessage.GetCachePathForTemporaryMedia(data.mediaId));
            var msg = new CustomerMessage()
            {
                FromUser = GetUsername(),
                ToUser   = args.OpenId,
                Time     = DateTime.Now,
                Content  = Newtonsoft.Json.JsonConvert.SerializeObject(data),
                ChatFlag = args.OpenId
            };

            wechatCoreDb.AddToCustomerMessage(msg);
            wechatCoreDb.UpdateCustomerSessionTime(args.OpenId);

            wechatCoreDb.SaveChanges();
            return(Success());
        }
Ejemplo n.º 5
0
        public void Handle_InvalidParam_Throws()
        {
            var mockRepository  = new Mock <IRepository <CustomerFieldSourceMap, EntityFrameworkCustomerContext> >();
            var customerMapper  = new CustomerMapper(mockRepository.Object);
            var customerMessage = new CustomerMessage();

            Assert.Throws <NullReferenceException>(() => customerMapper.Handle(customerMessage));
        }
        public CustomerResponse UpdateCustomer()
        {
            var storeScope = this.GetActiveStoreScopeConfiguration(_storeService, _workContext);
            CustomerResponse CustomerResponse = null;
            var ContaAzulMiscSettings         = _settingService.LoadSetting <ContaAzulMiscSettings>(storeScope);

            var customer           = _customerService.GetCustomerById(_workContext.CurrentCustomer.Id);
            var customerPayPalPlus = _contaAzulCustomerService.GetCustomerContaAzul(customer);
            var customerMessage    = new CustomerMessage();

            var number     = string.Empty;
            var complement = string.Empty;
            var cpfCnpj    = string.Empty;

            customerMessage.name               = customer.BillingAddress != null ? customer.BillingAddress.FirstName + " " + customer.BillingAddress.LastName : "";
            customerMessage.companyName        = customer.BillingAddress != null ? customer.BillingAddress.Company : null;
            customerMessage.email              = customer.Email;
            customerMessage.mobilePhone        = customer.BillingAddress != null ? customer.BillingAddress.PhoneNumber : null;
            customerMessage.address.city.name  = customer.BillingAddress != null ? customer.BillingAddress.City : null;
            customerMessage.address.state.name = customer.BillingAddress != null ? customer.BillingAddress.StateProvince != null ? customer.BillingAddress.StateProvince.Name : null : null;
            // customer.address.zipCode = item.BillingAddress != null ? item.BillingAddress.ZipPostalCode : null;
            customerMessage.address.street     = customer.BillingAddress != null ? customer.BillingAddress.Address1 : null;
            customerMessage.address.complement = complement;
            customerMessage.address.number     = number;
            customerMessage.document           = "";

            try
            {
                using (var customerCreation = new CustomerCreation(ContaAzulMiscSettings.UseSandbox))
                    CustomerResponse = customerCreation.CreateAsyncUpdate(customerMessage, customerPayPalPlus.ContaAzulId.ToString(), ContaAzulMiscSettings.access_token).ConfigureAwait(false).GetAwaiter().GetResult();
            }
            catch (Exception ex)
            {
                try
                {
                    var retorno = JsonConvert.DeserializeObject <MiscExecutitionResponse>(ex.Message, ConverterPaymentExecution.Settings);

                    if (retorno.StatusCode == "401")
                    {
                        RefreshToken();
                        _logger.Error("Token expirado " + ContaAzulMiscSettings.access_token, ex);
                    }
                    else
                    {
                        _logger.Error(ex.Message, ex);
                    }
                }
                catch (Exception erro)
                {
                    _logger.Error(erro.Message, erro);

                    throw;
                }
            }

            return(CustomerResponse);
        }
Ejemplo n.º 7
0
        public async Task <Customer> Handle(CreateCustomerCommand request, CancellationToken cancellationToken)
        {
            var customer = await _customerRepository.AddAsync(request.Customer);

            var customerMessage = new CustomerMessage(_serviceId, customer);

            _messageProducer.SendMessage(_queueName, customerMessage);
            _logger.Log(LogLevel.Information, $"{DateTime.Now} - Enviada mensagem pelo ServiceId: {customerMessage.ServiceId} com RequestId: {customerMessage.RequestId}");
            return(await Task.FromResult(customer));
        }
Ejemplo n.º 8
0
 public ActionResult SendMessage(CustomerMessage model)
 {
     if (ModelState.IsValid)
     {
         ViewBag.SuccessMessage = "Message Sent!";
         model = new CustomerMessage();
         ModelState.Clear();
     }
     return(PartialView("Message", model));
 }
Ejemplo n.º 9
0
        public ActionResult AboutUs()
        {
            List <CustomerMessage> customer = new List <CustomerMessage>();
            PDBC db = new PDBC("DBConnectionString", true);

            db.Connect();
            DataTable dt = db.Select(
                "SELECT [name],[Job],[message],[star],[ImagePath],[ImageValue]FROM [TSHP_PortalCMS].[dbo].[CustomersMessge_tbl]");

            for (int i = 0; i < dt.Rows.Count; i++)
            {
                var cust = new CustomerMessage()
                {
                    Name    = dt.Rows[i]["name"].ToString(),
                    Job     = dt.Rows[i]["Job"].ToString(),
                    Message = dt.Rows[i]["message"].ToString(),
                    Stars   = (int)dt.Rows[i]["star"]
                };

                customer.Add(cust);
            }


            List <TeamMembers> members = new List <TeamMembers>();

            DataTable dt2 =
                db.Select(
                    "SELECT[Name],[Job],[Tozihat],[github],[Linkedin],[Instagram],[ImagePath],[ImageValue]FROM [TSHP_PortalCMS].[dbo].[TeamMembers_tbl]");

            for (int i = 0; i < dt2.Rows.Count; i++)
            {
                var member = new TeamMembers()
                {
                    name      = dt2.Rows[i]["Name"].ToString(),
                    Job       = dt2.Rows[i]["Job"].ToString(),
                    Tozihat   = dt2.Rows[i]["Tozihat"].ToString(),
                    Github    = dt2.Rows[i]["github"].ToString(),
                    linkedin  = dt2.Rows[i]["Linkedin"].ToString(),
                    Instagram = dt2.Rows[i]["Instagram"].ToString(),
                    ImagePath = dt2.Rows[i]["ImagePath"].ToString(),
                    //  ImageValue = dt2.Rows[i]["ImageValue"].ToString()
                };

                members.Add(member);
            }


            var About__Us = new AboutUsModelView()
            {
                customerMessages = customer,
                teamMemberses    = members
            };

            return(View(About__Us));
        }
        private void btnSave_Click(object sender, EventArgs e)
        {
            _customerBusiness = new CustomerMessageBusiness();
            try
            {
                if (this.messageID > 0)
                {
                    customer             = new CustomerMessage(); // kritik unutma
                    customer.ID          = this.messageID;
                    customer.Name        = txtTitle.Text;
                    customer.Description = txtDescription.Text;
                    customer.CustomerID  = 1;



                    if (radioNotSee.Checked)
                    {
                        customer.Status = "Görülmedi";
                    }
                    else
                    {
                        customer.Status = "Görüldü";
                    }

                    _customerBusiness.Update(customer);
                }
                else
                {
                    customer             = new CustomerMessage();
                    customer.Name        = txtTitle.Text;
                    customer.Description = txtDescription.Text;

                    customer.CustomerID = 1;  // todo: Customer ıd çek buraya otomatik


                    if (radioNotSee.Checked)
                    {
                        customer.Status = "Görülmedi";
                    }
                    else
                    {
                        customer.Status = "Görüldü";
                    }

                    _customerBusiness.Add(customer);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
                DeleteTextBoxes();
            }
        }
Ejemplo n.º 11
0
        public APIResult SendCustomerNews([FromBody] SendCustomerNewsArgsModel args)
        {
            if (string.IsNullOrEmpty(args.OpenId))
            {
                throw new ArgumentNullException("OpenId");
            }
            if (string.IsNullOrEmpty(args.Description))
            {
                throw new ArgumentNullException("Description");
            }
            if (string.IsNullOrEmpty(args.Url))
            {
                throw new ArgumentNullException("Url");
            }

            var user = GetUsername();

            wechatCoreDb.EnsureIsCustomerSessionWorker(args.OpenId, user);

            var accessToken = GetAccessToken();
            var article     = new Article()
            {
                Description = args.Description,
                Title       = args.Title,
                Url         = args.Url
            };

            Senparc.Weixin.MP.AdvancedAPIs.CustomApi.SendNews(accessToken, args.OpenId, new List <Article>()
            {
                article
            }, 10000, "");
            var msg = new CustomerMessage()
            {
                FromUser = GetUsername(),
                ToUser   = args.OpenId,
                Time     = DateTime.Now,
                //Content = $"title:{args.Title},description:{args.Description},url:{args.Url}",
                ContentObject = new
                {
                    msgType     = "news",
                    title       = args.Title,
                    description = args.Description,
                    url         = args.Url
                },
                ChatFlag = args.OpenId
            };

            wechatCoreDb.AddToCustomerMessage(msg);
            wechatCoreDb.UpdateCustomerSessionTime(args.OpenId);
            wechatCoreDb.SaveChanges();
            return(Success());
        }
        public CustomerMessageForm(int messageID)
        {
            InitializeComponent();

            this.Text      = "Güncelle";
            btnSave.Text   = "Güncelle"; // todo:
            this.messageID = messageID;

            _customerBusiness = new CustomerMessageBusiness();

            customer            = _customerBusiness.GetById(messageID);
            txtTitle.Text       = customer.Name;
            txtDescription.Text = customer.Description;
        }
Ejemplo n.º 13
0
        public APIResult SendCustomerText([FromBody] SendCustomerTextArgsModel args)
        {
            if (string.IsNullOrEmpty(args.OpenId))
            {
                throw new ArgumentNullException("OpenId");
            }
            if (string.IsNullOrEmpty(args.Text))
            {
                throw new ArgumentNullException("text");
            }

            var user = GetUsername();

            wechatCoreDb.EnsureIsCustomerSessionWorker(args.OpenId, user);

            var time48 = DateTime.Now.AddHours(-47);
            var last   = wechatCoreDb.QueryCustomerMessage()
                         .OrderByDescending(m => m.Time)
                         .Select(m => m.Time)
                         .FirstOrDefault();

            if (last <= time48)
            {
                throw new Exception("最后发送信息超过48小时");
            }

            var accessToken = GetAccessToken();

            Senparc.Weixin.MP.AdvancedAPIs.CustomApi.SendText(accessToken, args.OpenId, args.Text, 10000, "");

            var msg = new CustomerMessage()
            {
                FromUser      = GetUsername(),
                ToUser        = args.OpenId,
                Time          = DateTime.Now,
                ContentObject = new
                {
                    msgType = "text",
                    text    = args.Text
                },
                ChatFlag = args.OpenId
            };

            wechatCoreDb.AddToCustomerMessage(msg);
            wechatCoreDb.UpdateCustomerSessionTime(args.OpenId);

            wechatCoreDb.SaveChanges();
            return(Success());
        }
Ejemplo n.º 14
0
        public async Task <CustomerResponse[]> CreateAsync(CustomerMessage customerMessage, string token, string filtro = null)
        {
            if (filtro != null)
            {
                var retorno = await GetAsync <CustomerResponse[]>(null, filtro, token).ConfigureAwait(false);

                return(retorno);
            }
            else
            {
                var retorno = await GetAsync <CustomerResponse[]>(customerMessage.id, null, token).ConfigureAwait(false);

                return(retorno);
            }
        }
Ejemplo n.º 15
0
        public APIResult SendCustomerTemplateMessage([FromBody] SendCustomerTemplateMessageArgsModel args)
        {
            if (args.Data == null)
            {
                throw new ArgumentNullException("Data");
            }
            if (string.IsNullOrEmpty(args.TemplateId))
            {
                throw new ArgumentNullException("TemplateId");
            }
            if (string.IsNullOrEmpty(args.OpenId))
            {
                throw new ArgumentNullException("OpenId");
            }

            var user = GetUsername();
            //暂时去掉
            //wechatCoreDb.EnsureIsCustomerSessionWorker(args.OpenId, user);

            var accessToken = GetAccessToken();

            Senparc.Weixin.MP.AdvancedAPIs.TemplateApi.SendTemplateMessage(accessToken, args.OpenId, args.TemplateId, args.Url, args.Data);

            var msg = new CustomerMessage()
            {
                FromUser      = GetUsername(),
                ToUser        = args.OpenId,
                Time          = DateTime.Now,
                Content       = "[模板消息]",
                ContentObject = new
                {
                    msgType    = "templateMessage",
                    data       = args.Data,
                    url        = args.Url,
                    templateId = args.TemplateId
                },
                ChatFlag = args.OpenId
            };

            wechatCoreDb.AddToCustomerMessage(msg);
            wechatCoreDb.UpdateCustomerSessionTime(args.OpenId);

            wechatCoreDb.SaveChanges();
            return(Success());
        }
Ejemplo n.º 16
0
        static void Main(string[] args)
        {
            CustomerMessage customerMessage = new CustomerMessage(
                "Oscar Blancarte", "*****@*****.**", "554433445566");

            Console.WriteLine("Original Message ==> " + customerMessage);

            IMessage message1 = new EncryptMessage("user", "HG58YZ3CR9123456",
                                                   new SOAPEnvelopMessage(
                                                       new XMLFormatterDecorate(customerMessage))).ProcessMessage();

            Console.WriteLine("message1 =====================================>\n"
                              + message1.GetContent() + "\n\n");

            IMessage message2 = new SOAPEnvelopMessage(
                new EncryptMessage("user", "HG58YZ3CR9123456",
                                   new XMLFormatterDecorate(customerMessage))).ProcessMessage();

            Console.WriteLine("message2 =====================================>\n"
                              + message2.GetContent());
        }
        public CustomerResponse getCustomerById(string id)
        {
            var storeScope = this.GetActiveStoreScopeConfiguration(_storeService, _workContext);
            CustomerResponse CustomerResponse = null;
            var customer = new CustomerMessage();

            customer.id = id;
            var ContaAzulMiscSettings = _settingService.LoadSetting <ContaAzulMiscSettings>(storeScope);

            try
            {
                using (var getcustomer = new GetCustomer(ContaAzulMiscSettings.UseSandbox))
                    CustomerResponse = getcustomer.CreateAsyncById(customer, ContaAzulMiscSettings.access_token).ConfigureAwait(false).GetAwaiter().GetResult();
            }
            catch (Exception ex)
            {
                try
                {
                    var retorno = JsonConvert.DeserializeObject <MiscExecutitionResponse>(ex.Message, ConverterPaymentExecution.Settings);

                    if (retorno.StatusCode == "401")
                    {
                        RefreshToken();
                        _logger.Error("Token expirado " + ContaAzulMiscSettings.access_token, ex);
                    }
                    else
                    {
                        _logger.Error(ex.Message, ex);
                    }
                }
                catch (Exception erro)
                {
                    _logger.Error(erro.Message, erro);

                    throw;
                }
            }

            return(CustomerResponse);
        }
Ejemplo n.º 18
0
        public IActionResult SendMessage([FromBody] CustomerMessage customerMessage)
        {
            try
            {
                var message = new MimeMessage();
                message.From.Add(new MailboxAddress(customerMessage.Name, customerMessage.Email));
                message.ReplyTo.Add(new MailboxAddress(customerMessage.Name, customerMessage.Email));
                message.To.Add(new MailboxAddress("DeathRaffle Support", "*****@*****.**"));
                message.Subject = "Message From DeathRaffle.com Customer";
                message.Body    = new TextPart("plain")
                {
                    Text = $@"
                        Customer Name: {customerMessage.Name}
                        Customer Email: {customerMessage.Email}
                        {Environment.NewLine}
                        Customer Said: {customerMessage.Message} 
                    "
                };

                using (var client = new SmtpClient())
                {
                    client.Connect("smtp.gmail.com", 465, true);
                    client.AuthenticationMechanisms.Remove("XOAUTH2");
                    // Note: since we don't have an OAuth2 token, disable
                    // the XOAUTH2 authentication mechanism.
                    client.Authenticate("*****@*****.**", "ownlraesbvstthqb");
                    client.Send(message);
                    client.Disconnect(true);
                }

                return(Ok());
            }
            catch (Exception e)
            {
                AppSettings.Logger.Error(e.Message);
                return(StatusCode(500, "There was a problem on the server.  Please try again later."));
            }
        }
Ejemplo n.º 19
0
        public void Handle_ValidParam_ReturnMappedCustomerMessageObject()
        {
            var mockRepository = new Mock <IRepository <CustomerFieldSourceMap, EntityFrameworkCustomerContext> >();
            var customerMapper = new CustomerMapper(mockRepository.Object);

            var customerMessage = new CustomerMessage()
            {
                CustomerId = 1,
                Data       = new Dictionary <string, string>()
                {
                    { "name", "messi" },
                    { "phone", "123123156" }
                },
                ArrayData = new Dictionary <string, string[]>()
                {
                    { "cuentas", new string[] { "905270296", "900904026", "914637420" } }
                }
            };

            var result = customerMapper.Handle(customerMessage);

            Assert.IsType <MappedCustomerMessage>(result);
        }
Ejemplo n.º 20
0
 public CustomerMessageForm(CustomerMessage message)
 {
     InitializeComponent();
     this.CustomerMessage = message;
 }
Ejemplo n.º 21
0
        /// <summary>
        /// 发送消息
        /// </summary>
        /// <param name="message">The message.</param>
        public WxError Send(CustomerMessage message)
        {
            var api = string.Format(SEND_API, accessTokenSvc.GetToken());

            return(WxHelper.Send <WxError>(api, message));
        }
Ejemplo n.º 22
0
        public void SaveMessage(CustomerMessage message)
        {
            _db.UseOnceTo().Insert(message);

            var request = new HttpRequestMessage { RequestUri = new Uri("http://localhost:50383/api/hub/ReceiveMessage") };

            request.Method = HttpMethod.Put;
            request.Content = new ObjectContent<CustomerMessage>(message, new JsonMediaTypeFormatter { SerializerSettings = { ContractResolver = new CamelCasePropertyNamesContractResolver() } });

            request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

            using (var handler = new HttpClientHandler { UseDefaultCredentials = true })
            {
                using (var client = new HttpClient(handler))
                {
                    client.Timeout = TimeSpan.FromSeconds(30);
                    var result = client.SendAsync(request).Result;
                }
            }
        }
Ejemplo n.º 23
0
 public EditCustomerMessage(CustomerMessage message)
 {
     this.message = message;
 }
        private void GetChildBasketActorForCustomer(CustomerMessage msg)
        {
            var actor = Context.Child(msg.CustomerId.ToString()) is Nobody?Context.ActorOf(Props.Create(() => new BasketForCustomerActor(msg.CustomerId, _productActorRef)), msg.CustomerId.ToString()) : Context.Child(msg.CustomerId.ToString());

            actor.Forward(msg);
        }
Ejemplo n.º 25
0
        public static async Task RunAync([QueueTrigger("customers")] CustomerMessage message, TraceWriter log)

        //#if DEBUG
        //		public static async Task RunAync([HttpTrigger(Route = "GetSubscriptions")]HttpRequestMessage req, TraceWriter log)
        //#else
        //		public static async Task RunAync([QueueTrigger("customers")]CustomerMessage message, TraceWriter log)
        //#endif

        {
            //#if DEBUG
            //			var param = req.GetQueryNameValuePairs().FirstOrDefault(s => s.Key.Equals("customerid"));
            //			CustomerMessage message = new CustomerMessage()
            //			{
            //				CustomerId = param.Value
            //			};
            //#endif
            log.Info($"Get subscriptoins function execution started at {DateTime.UtcNow} UTC");
            try
            {
                log.Info($"Database initialization started.");
                DbInitializer.init(ConfigurationHelper.GetConnectionString(ConfigurationKeys.DbConnectoinString));
                log.Info($"Database initialization completed.");

                string partnerServiceApiRoot = ConfigurationHelper.GetAppSetting(ConfigurationKeys.MPN.PartnerServiceApiRoot),
                       authority             = ConfigurationHelper.GetAppSetting(ConfigurationKeys.MPN.Authority),
                       resourceUrl           = ConfigurationHelper.GetAppSetting(ConfigurationKeys.MPN.ResourceUrl),
                       applicationId         = ConfigurationHelper.GetAppSetting(ConfigurationKeys.MPN.ApplicationId),
                       applicationSecret     = ConfigurationHelper.GetAppSetting(ConfigurationKeys.MPN.ApplicationSecret),
                       applicationDomian     = ConfigurationHelper.GetAppSetting(ConfigurationKeys.MPN.ApplicationDomain);

                log.Info($"Partner Service Api Root {partnerServiceApiRoot}");
                log.Info($"Authority is {authority}");
                log.Info($"Resource URL is {resourceUrl}");
                log.Info($"Application Id is {applicationId}");
                log.Info($"Application Secret is {new string('*', applicationSecret.Length)}");
                log.Info($"Application Domain is {applicationDomian}");

                log.Info($"Connecting to MPN network");
                MpnApiClient mpnClient = await MpnApiClient.CreateAsync(partnerServiceApiRoot
                                                                        , authority
                                                                        , resourceUrl
                                                                        , applicationId
                                                                        , applicationSecret
                                                                        , applicationDomian);

                log.Info($"Connected to MPN network");
                var subscriptions = await mpnClient.GetSubscriptionsAsync(message.CustomerId);

                if (subscriptions != null)
                {
                    await ProcessSubscriptions(subscriptions, message.CustomerId, log);
                }
                else
                {
                    log.Verbose($"0 subscriptions found");
                }
                log.Info($"Finished processing customers");
            }
            catch (Exception ex)
            {
                log.Error("Some error occured in function - 'GetSubscriptions'", ex);
            }
            log.Info($"Get subscriptoins function execution completed at {DateTime.UtcNow} UTC");
        }
        public async Task <IActionResult> SaveCustomerMessage(CustomerMessage data)
        {
            var result = await _cRepo.insertAsync(data);

            return(Ok(result));
        }
        public async Task <CustomerResponse> CreateAsyncUpdate(CustomerMessage data, string id, string token)
        {
            var retorno = await PutAsync <CustomerResponse>(data, id, token).ConfigureAwait(false);

            return(retorno);
        }
Ejemplo n.º 28
0
        public async Task <CustomerResponse> CreateAsyncById(CustomerMessage customerMessage, string token, string filtro = null)
        {
            var retorno = await GetAsync <CustomerResponse>(customerMessage.id, null, token).ConfigureAwait(false);

            return(retorno);
        }
        public void SincronizaContatos()
        {
            var customers  = _customerService.GetAllCustomers();
            var storeScope = this.GetActiveStoreScopeConfiguration(_storeService, _workContext);

            CustomerResponse[] GetCustomerResponse = null;
            CustomerResponse   CustomerResponse    = null;
            var ContaAzulMiscSettings = _settingService.LoadSetting <ContaAzulMiscSettings>(storeScope);


            var number     = string.Empty;
            var complement = string.Empty;
            var cpfCnpj    = string.Empty;

            foreach (var item in customers)
            {
                var customer = new CustomerMessage();

                new AddressHelper(_addressAttributeParser, _workContext).GetCustomNumberAndComplement(item.BillingAddress != null ? item.BillingAddress.CustomAttributes : null,
                                                                                                      out number, out complement, out cpfCnpj);

                customer.name = item.BillingAddress != null?AddressHelper.GetFullName(item.BillingAddress) : null;

                customer.companyName        = item.BillingAddress != null ? item.BillingAddress.Company : null;
                customer.email              = item.Email;
                customer.personType         = "NATURAL";
                customer.mobilePhone        = item.BillingAddress != null ? item.BillingAddress.PhoneNumber : null;
                customer.address.city.name  = item.BillingAddress != null ? item.BillingAddress.City : null;
                customer.address.state.name = item.BillingAddress != null ? item.BillingAddress.StateProvince != null ? item.BillingAddress.StateProvince.Name : null : null;
                // customer.address.zipCode = item.BillingAddress != null ? item.BillingAddress.ZipPostalCode : null;
                customer.address.street     = item.BillingAddress != null ? item.BillingAddress.Address1 : null;
                customer.address.complement = complement;
                customer.address.number     = number;
                customer.document           = cpfCnpj;

                try
                {
                    var filtro = "?search=" + cpfCnpj;
                    using (var getcustomer = new GetCustomer(ContaAzulMiscSettings.UseSandbox))
                        GetCustomerResponse = getcustomer.CreateAsync(null, ContaAzulMiscSettings.access_token, filtro).ConfigureAwait(false).GetAwaiter().GetResult();
                    //busca por cpf conta azul, se existir, verifica se já foi adicionado na tabela do banco
                    if (GetCustomerResponse != null)
                    {
                        var customerPayPalPlus = _contaAzulCustomerService.GetCustomer(GetCustomerResponse[0]);
                        //caso ele não exista na tabela relacional do banco, insere e atualiza no conta azul
                        if (customerPayPalPlus == null)
                        {
                            using (var customerCreation = new CustomerCreation(ContaAzulMiscSettings.UseSandbox))
                                CustomerResponse = customerCreation.CreateAsyncUpdate(customer, GetCustomerResponse[0].id.ToString(), ContaAzulMiscSettings.access_token).ConfigureAwait(false).GetAwaiter().GetResult();

                            if (CustomerResponse != null)
                            {
                                var customerContaAzul = new CustomerContaAzul();

                                customerContaAzul.ContaAzulId = CustomerResponse.id;
                                customerContaAzul.CustomerId  = item.Id;
                                customerContaAzul.DataCriacao = DateTime.Now;
                                _contaAzulCustomerService.InsertCustomer(customerContaAzul);
                            }
                        }
                        else
                        {
                            //se ele já existe na tabela, só faz o update no conta azul
                            using (var customerCreation = new CustomerCreation(ContaAzulMiscSettings.UseSandbox))
                                CustomerResponse = customerCreation.CreateAsyncUpdate(customer, customerPayPalPlus.ContaAzulId.ToString(), ContaAzulMiscSettings.access_token).ConfigureAwait(false).GetAwaiter().GetResult();
                        }
                    }
                    else
                    {//caso ele não exista no conta azul, faz a inserção dele no conta azul e no banco de dados
                        using (var customerCreation = new CustomerCreation(ContaAzulMiscSettings.UseSandbox))
                            CustomerResponse = customerCreation.CreateAsync(customer, ContaAzulMiscSettings.access_token).ConfigureAwait(false).GetAwaiter().GetResult();

                        if (CustomerResponse != null)
                        {
                            var customerContaAzul = new CustomerContaAzul();

                            customerContaAzul.ContaAzulId = CustomerResponse.id;
                            customerContaAzul.CustomerId  = item.Id;
                            customerContaAzul.DataCriacao = DateTime.Now;
                            _contaAzulCustomerService.InsertCustomer(customerContaAzul);
                        }
                    }
                }
                catch (Exception ex)
                {
                    try
                    {
                        var retorno = JsonConvert.DeserializeObject <MiscExecutitionResponse>(ex.Message, ConverterPaymentExecution.Settings);

                        if (retorno.StatusCode == "401")
                        {
                            RefreshToken();
                            _logger.Error("Token expirado " + ContaAzulMiscSettings.access_token, ex);
                        }
                        else
                        {
                            _logger.Error(ex.Message, ex);
                        }
                    }
                    catch (Exception erro)
                    {
                        _logger.Error(erro.Message, erro);

                        throw;
                    }

                    // ErrorNotification("O Customer com id " + item.Id + " não foi encontrado" );
                }
            }
        }
        public void Execute()
        {
            _contaAzulService.RefreshToken();

            var customers = _customerService.GetAllCustomers();

            // var storeScope = GetActiveStoreScopeConfiguration(_storeService, _workContext);
            CustomerResponse[] GetCustomerResponse = null;
            CustomerResponse   CustomerResponse    = null;
            var ContaAzulMiscSettings = _settingService.LoadSetting <ContaAzulMiscSettings>();

            var number     = string.Empty;
            var complement = string.Empty;
            var cpfCnpj    = string.Empty;

            foreach (var item in customers)
            {
                var customer = new CustomerMessage();

                new AddressHelper(_addressAttributeParser, _workContext).GetCustomNumberAndComplement(item.BillingAddress != null ? item.BillingAddress.CustomAttributes : null,
                                                                                                      out number, out complement, out cpfCnpj);

                customer.name = item.BillingAddress != null?AddressHelper.GetFullName(item.BillingAddress) : null;

                customer.companyName           = item.BillingAddress != null ? item.BillingAddress.Company : null;
                customer.email                 = item.Email;
                customer.personType            = "NATURAL";
                customer.stateRegistrationType = "NO_CONTRIBUTOR";
                customer.mobilePhone           = item.BillingAddress != null ? item.BillingAddress.PhoneNumber : null;
                customer.address.city.name     = item.BillingAddress != null ? item.BillingAddress.City : null;
                customer.address.state.name    = item.BillingAddress != null ? item.BillingAddress.StateProvince != null ? item.BillingAddress.StateProvince.Name : null : null;
                customer.address.zipCode       = item.BillingAddress != null ? item.BillingAddress.ZipPostalCode : null;
                customer.address.street        = item.BillingAddress != null ? item.BillingAddress.Address1 : null;
                customer.address.complement    = complement;
                customer.address.number        = number;
                customer.document              = cpfCnpj == "" ? null : cpfCnpj;

                try
                {
                    var filtro = "?search=";
                    if (cpfCnpj == string.Empty)
                    {
                        filtro = filtro + item.Email;
                    }
                    else
                    {
                        filtro = filtro + cpfCnpj;
                    }
                    using (var getcustomer = new GetCustomer(ContaAzulMiscSettings.UseSandbox))
                        GetCustomerResponse = getcustomer.CreateAsync(null, ContaAzulMiscSettings.access_token, filtro).ConfigureAwait(false).GetAwaiter().GetResult();
                    //busca por cpf conta azul, se existir, verifica se já foi adicionado na tabela do banco
                    if (GetCustomerResponse.Count() > 0)
                    {
                        var customerTable = _contaAzulCustomerService.GetCustomer(GetCustomerResponse[0]);
                        //caso ele não exista na tabela relacional do banco, insere e atualiza no conta azul
                        if (customerTable == null)
                        {
                            var customerContaAzul = new CustomerContaAzul();

                            customerContaAzul.ContaAzulId = GetCustomerResponse[0].id;
                            customerContaAzul.CustomerId  = item.Id;
                            customerContaAzul.DataCriacao = DateTime.Now;
                            _contaAzulCustomerService.InsertCustomer(customerContaAzul);

                            customer.id = customerTable.ContaAzulId.ToString();
                            customer.address.city.name = null;

                            var data1 = JsonConvert.SerializeObject(GetCustomerResponse[0]);
                            var data2 = JsonConvert.SerializeObject(customer);


                            // var data = data2.Equals(data1);

                            if (!data1.Equals(data2))
                            {
                                //se ele já existe na tabela, só faz o update no conta azul
                                using (var customerCreation = new CustomerCreation(ContaAzulMiscSettings.UseSandbox))
                                    CustomerResponse = customerCreation.CreateAsyncUpdate(customer, GetCustomerResponse[0].id.ToString(), ContaAzulMiscSettings.access_token).ConfigureAwait(false).GetAwaiter().GetResult();
                            }
                        }
                        else
                        {
                            customer.id = customerTable.ContaAzulId.ToString();
                            customer.address.city.name = null;

                            var data1 = JsonConvert.SerializeObject(GetCustomerResponse[0]);
                            var data2 = JsonConvert.SerializeObject(customer);


                            var data = data2.Equals(data1);

                            if (!data1.Equals(data2))
                            {
                                //se ele já existe na tabela, só faz o update no conta azul
                                using (var customerCreation = new CustomerCreation(ContaAzulMiscSettings.UseSandbox))
                                    CustomerResponse = customerCreation.CreateAsyncUpdate(customer, customerTable.ContaAzulId.ToString(), ContaAzulMiscSettings.access_token).ConfigureAwait(false).GetAwaiter().GetResult();
                            }
                        }
                    }
                    else
                    {//caso ele não exista no conta azul, faz a inserção dele no conta azul e no banco de dados
                        var data2 = JsonConvert.SerializeObject(customer);
                        using (var customerCreation = new CustomerCreation(ContaAzulMiscSettings.UseSandbox))
                            CustomerResponse = customerCreation.CreateAsync(customer, ContaAzulMiscSettings.access_token).ConfigureAwait(false).GetAwaiter().GetResult();

                        if (CustomerResponse != null)
                        {
                            var customerContaAzul = new CustomerContaAzul();

                            customerContaAzul.ContaAzulId = CustomerResponse.id;
                            customerContaAzul.CustomerId  = item.Id;
                            customerContaAzul.DataCriacao = DateTime.Now;
                            _contaAzulCustomerService.InsertCustomer(customerContaAzul);
                        }
                    }
                }
                catch (Exception ex)
                {
                    _logger.Error(ex.Message, ex);
                }
            }
        }
Ejemplo n.º 31
0
        /// <summary>
        /// 发送消息
        /// </summary>
        /// <param name="message">The message.</param>
        public async Task <WxError> Send(CustomerMessage message)
        {
            var api = string.Format(SEND_API, await tokenSvc.GetToken());

            return(await wxHelper.Send <WxError>(api, message));
        }