Пример #1
0
        public async Task <Message> CreateMessage(Channel bc, ZaloMessage fm, Customer customer, bool real_time_update)
        {
            var business_id = bc.business_id;
            var message_id  = MessageService.FormatId01(business_id, fm.msgid);
            var message     = _messageService.GetById(business_id, message_id);

            if (message == null)
            {
                message = await BuildMessage(bc, fm, customer);
            }
            else
            {
                if (!string.IsNullOrWhiteSpace(fm.message) && fm.message != message.message)
                {
                    message.message = fm.message;
                }

                if (!string.IsNullOrWhiteSpace(fm.href) && fm.href != message.url)
                {
                    var imageUri = fm.href;
                    if (!fm.href.Contains("hibaza") && !fm.href.Contains("firebase"))
                    {
                        try
                        {
                            imageUri = await DownloadToLocalAsync(fm.href);
                        }
                        catch { }
                    }
                    message.url  = imageUri;
                    message.urls = "[]";
                }
            }

            return(message);
        }
Пример #2
0
        public IActionResult webhook(ZaloMessage obj)
        {
            var tt = Request.QueryString.Value;

            try
            {
                // add remove like image
                //var p = JsonConvert.SerializeObject(obj);
                // p = p.Replace(_appSettings.Value.BaseUrls.Api, "");
                // obj = JsonConvert.DeserializeObject<FacebookWebhookData>(p);
                _logService.Create(new Log {
                    name = "zalo ", message = "zalo " + tt, details = JsonConvert.SerializeObject(obj)
                });
                // _facebookService.SaveWebhookData("", "", obj, true);
                _zaloService.SaveWebhookData(obj, true);
                return(Ok());
            }
            catch (Exception ex)
            {
                _logService.Create(new Log {
                    name = "Webhook zalo error calledback", message = ex.Message + tt, details = JsonConvert.SerializeObject(ex.StackTrace)
                });
                throw ex;
            }
        }
Пример #3
0
        public async Task <ApiResponse> SendIntereste(Channel channel, string phone)
        {
            var response = new ApiResponse();

            try
            {
                var timestame = Core.Helpers.CommonHelper.DateTimeToUnixTimestamp(DateTime.UtcNow);

                var newPhone = phone;
                if (newPhone.Substring(0, 1) == "0")
                {
                    newPhone = "84" + newPhone.Substring(1, newPhone.Length - 1);
                }

                //var templatedata = new Dictionary<string, string>();
                //templatedata.Add("DAY", "20");
                //templatedata.Add("TIME_24HR", "24h");

                var data = new Dictionary <string, object>();
                data.Add("phone", newPhone);
                data.Add("templateid", "c8754d9b71de9880c1cf");
                data.Add("templatedata", "{}");
                data.Add("callbackdata", _appSettings.Value.BaseUrls.Api + "brands/zalos/webhook");

                var mac = Core.Helpers.CommonHelper.sha256(channel.ext_id + JsonConvert.SerializeObject(data) + timestame + channel.token);
                var uri = "https://openapi.zaloapp.com/oa/v1/sendmessage/phone/invite_v2?oaid=" + channel.ext_id + "&data=" + JsonConvert.SerializeObject(data) + "&timestamp=" + timestame + "&mac=" + mac;
                var rs  = Core.Helpers.WebHelper.HttpPostAsync <JObject>(uri, null).Result;

                var timestamp = Core.Helpers.CommonHelper.DateTimeToUnixTimestamp(DateTime.UtcNow);
                var zalo      = new ZaloMessage();
                zalo.oaid      = Convert.ToInt64(channel.ext_id);
                zalo.touid     = Convert.ToInt64(phone);
                zalo.timestamp = timestamp;
                zalo.@event    = "sendmsg";
                zalo.message   = "Đã gửi yêu cầu kết bạn tới " + phone;
                zalo.msgid     = DateTime.Now.ToString("yyyyMMddHHmmssfff");// (string)rs["data"]["msgId"];
                response.ok    = true;

                BackgroundJob.Enqueue <ZaloConversationService>(x => x.SaveWebhookMessaging(zalo, null, true, channel));
                return(response);
            }
            catch (Exception ex)
            {
                response.ok = false;
                //BackgroundJob.Enqueue<ZaloConversationService>(x => x.SaveWebhookMessaging(zalo, recipient_id, true, channel));
                _logService.Create(new Log {
                    name = "send zalo error 2", message = ex.Message + JsonConvert.SerializeObject(ex.StackTrace).ToString(), details = ""
                });
                return(response);
            }
        }
Пример #4
0
 public void SaveWebhookData(ZaloMessage data, bool real_time_update)
 {
     // Make sure this is a page subscription
     //if (data.@event == "sendmsg" || data.@event == "sendimagemsg" || data.@event == "sendlinkmsg" || data.@event== "2691206174905801178")
     //{
     try
     {
         BackgroundJob.Enqueue <ZaloConversationService>(x => x.SaveWebhookMessaging(data, null, real_time_update, null));
         //ZaloConversationService conversationService = new ZaloConversationService(_channelService, _threadService, _agentService, _customerService, _messageService, _appSettings, _logService);
         //conversationService.SaveWebhookMessaging(data, null, real_time_update, null).Wait();
     }
     catch (Exception ex)
     {
         // BackgroundJob.Enqueue<ZaloConversationService>(x => x.SaveWebhookMessaging(data, null, real_time_update, null));
         _logService.Create(new Log {
             name = "Webhook zalo calledback 2", message = ex.Message + JsonConvert.SerializeObject(ex.StackTrace).ToString(), details = JsonConvert.SerializeObject(data).ToString()
         });
         throw ex;
     }
     // }
 }
Пример #5
0
        private static ZaloMessage[] ParseZaloMessage(string text)
        {
            var messages = new List <ZaloMessage>();
            var values   = text.Split("\r\n".ToCharArray());

            foreach (var value in values)
            {
                if (string.IsNullOrWhiteSpace(value))
                {
                    continue;
                }

                var zaloMessage = new ZaloMessage
                {
                    Type  = value.StartsWith("%") ? ZaloMessageType.Image : ZaloMessageType.Text,
                    Value = value
                };
                try
                {
                    if (zaloMessage.Type == ZaloMessageType.Image)
                    {
                        var f = new FileInfo(zaloMessage.Value.Substring(1));
                        zaloMessage.Value = f.FullName;
                    }
                }
                catch (Exception ex)
                {
                    Output("Không tìm thấy hình ảnh ở đường dẫn: " + zaloMessage.Value);
                    continue;
                }

                messages.Add(zaloMessage);
            }

            return(messages.ToArray());
        }
Пример #6
0
        public async Task <ApiResponse> SendMessage(dynamic para, Channel channel, MessageFormData form)
        {
            var response = new ApiResponse();

            try
            {
                var recipient_id = form.recipient_id;
                var type         = form.channel_format;

                if (string.IsNullOrWhiteSpace(recipient_id) || string.IsNullOrWhiteSpace(type) || string.IsNullOrWhiteSpace(form.business_id) || string.IsNullOrWhiteSpace(form.channel_id))
                {
                    return(response);
                }

                JObject rs        = null;
                var     timestamp = Core.Helpers.CommonHelper.DateTimeToUnixTimestamp(DateTime.UtcNow);

                var zalo = new ZaloMessage();
                zalo.oaid      = Convert.ToInt64(channel.ext_id);
                zalo.touid     = Convert.ToInt64(recipient_id);
                zalo.timestamp = timestamp;
                zalo.@event    = type == "text" || type == "message" ? "sendmsg" : "sendimagemsg";

                if (type == "text" || type == "message")
                {
                    rs = await SendText(form.message, recipient_id, channel.ext_id, channel.token, timestamp);

                    if ((string)rs["errorCode"] == "1")
                    {
                        zalo.message = form.message;
                        zalo.msgid   = (string)rs["data"]["msgId"];
                        response.ok  = true;

                        try
                        {
                            BackgroundJob.Enqueue <ZaloConversationService>(x => x.SaveWebhookMessaging(zalo, recipient_id, true, channel));
                            //ZaloConversationService conversationService = new ZaloConversationService(_channelService, _threadService, _agentService, _customerService, _messageService, _appSettings, _logService);
                            //conversationService.SaveWebhookMessaging(zalo, recipient_id, true, channel).Wait();
                        }
                        catch (Exception ex)
                        {
                            //BackgroundJob.Enqueue<ZaloConversationService>(x => x.SaveWebhookMessaging(zalo, recipient_id, true, channel));
                            _logService.Create(new Log {
                                name = "send zalo error 1", message = ex.Message + JsonConvert.SerializeObject(ex.StackTrace).ToString(), details = JsonConvert.SerializeObject(zalo).ToString()
                            });
                            throw ex;
                        }
                    }
                }
                else
                {
                    List <payloadFb> elements = JsonConvert.DeserializeObject <List <payloadFb> >(JsonConvert.SerializeObject(para.message.attachment.payload.elements));
                    for (var i = 0; i < elements.Count; i++)
                    {
                        var imageByte = await Core.Helpers.WebHelper.HttpGetAsyncByte(elements[i].image_url);

                        rs = await SendImage(imageByte, elements[i].title, recipient_id, channel.ext_id, channel.token, timestamp);

                        if ((string)rs["errorCode"] == "1")
                        {
                            response.ok  = true;
                            zalo.message = elements[i].title;
                            zalo.href    = elements[i].image_url;
                            zalo.msgid   = (string)rs["data"]["msgId"];

                            try
                            {
                                BackgroundJob.Enqueue <ZaloConversationService>(x => x.SaveWebhookMessaging(zalo, recipient_id, true, channel));
                            }
                            catch (Exception ex)
                            {
                                //BackgroundJob.Enqueue<ZaloConversationService>(x => x.SaveWebhookMessaging(zalo, recipient_id, true, channel));
                                _logService.Create(new Log {
                                    name = "send zalo error 2", message = ex.Message + JsonConvert.SerializeObject(ex.StackTrace).ToString(), details = JsonConvert.SerializeObject(zalo).ToString()
                                });
                                throw ex;
                            }
                        }
                    }
                }
            }
            catch { }
            return(response);
        }
Пример #7
0
        public async System.Threading.Tasks.Task SaveWebhookMessaging(ZaloMessage data, string agent_id, bool real_time_update, Channel channel)
        {
            var is_new = false;

            if (channel == null)
            {
                var channels = await _channelService.GetChannelsByExtId(data.oaid.ToString());

                if (channels.Count > 0)
                {
                    channel = channels[0];
                }
            }
            if (channel == null)
            {
                return;
            }

            var customer_ext_id = "";

            if (Convert.ToInt64(data.fromuid) > 0 && data.fromuid.ToString() != channel.ext_id)
            {
                customer_ext_id = data.fromuid.ToString();
            }
            else
            {
                customer_ext_id = data.touid.ToString();
            }

            var customer_id = CustomerService.FormatId01(channel.business_id, customer_ext_id);

            Customer customer = _customerService.GetById(channel.business_id, customer_id);

            if (customer == null)
            {
                is_new = true;
            }

            if (string.IsNullOrWhiteSpace(data.message) && string.IsNullOrWhiteSpace(data.href))
            {
                return;
            }

            customer = await GetCustomer(channel, data, customer, customer_ext_id);


            //if (is_new && string.IsNullOrWhiteSpace(data.message) && string.IsNullOrWhiteSpace(data.href))
            //    data.message = customer.name + " cần hỗ trợ";

            var message = await CreateMessage(channel, data, customer, true);

            var thread = await CreateThread(channel, message, customer, true);

            //customer.unread = false;
            //customer.nonreply = false;
            customer.active_thread = JsonConvert.SerializeObject(thread);
            customer.agent_id      = agent_id;

            _customerService.CreateCustomer(customer, true);
            _messageService.CreateMessage(customer.business_id, message, true);
            _threadService.CreateThread(thread, true);
        }
Пример #8
0
        public async Task <Message> BuildMessage(Channel channel, ZaloMessage msg, Customer customer)
        {
            var message_id       = MessageService.FormatId01(channel.business_id, msg.msgid);
            var sender_ext_id    = "";
            var recipient_ext_id = "";

            if (Convert.ToInt64(msg.fromuid) > 0 && msg.fromuid.ToString() != channel.ext_id)
            {
                sender_ext_id    = msg.fromuid.ToString();
                recipient_ext_id = msg.oaid.ToString();
            }
            else
            {
                sender_ext_id    = msg.oaid.ToString();
                recipient_ext_id = msg.touid.ToString();
            }
            if (sender_ext_id.Length < 5)
            {
                return(null);
            }

            var thread_id = ThreadService.FormatId01(channel.business_id, customer.ext_id);

            var timestamp    = msg.timestamp > 9999999999 ? msg.timestamp / 1000 : msg.timestamp;
            var created_time = Core.Helpers.CommonHelper.UnixTimestampToDateTime(timestamp);

            var imageUrl = msg.href;

            if (!string.IsNullOrWhiteSpace(imageUrl) && !imageUrl.Contains("hibaza") && !imageUrl.Contains("firebase"))
            {
                imageUrl = await DownloadToLocalAsync(imageUrl);
            }

            var message = new Domain.Entities.Message
            {
                //"sendmsg"  "sendimagemsg")
                id                  = message_id,
                parent_id           = "",
                parent_ext_id       = "",
                root_ext_id         = "",
                conversation_ext_id = sender_ext_id,
                ext_id              = msg.msgid,
                thread_id           = thread_id,
                thread_type         = "message",
                sender_id           = CustomerService.FormatId01(channel.business_id, sender_ext_id),
                sender_ext_id       = sender_ext_id,
                sender_name         = sender_ext_id == customer.ext_id ? customer.name : channel.name,
                sender_avatar       = sender_ext_id == customer.ext_id ? customer.avatar : "",
                recipient_id        = CustomerService.FormatId01(channel.business_id, recipient_ext_id),
                recipient_ext_id    = recipient_ext_id,
                recipient_name      = recipient_ext_id == channel.ext_id ? channel.name : customer.name,
                recipient_avatar    = recipient_ext_id == channel.ext_id ? "" : customer.avatar,
                author              = CustomerService.FormatId01(channel.business_id, sender_ext_id),
                customer_id         = customer.id,
                message             = msg.message,
                tag                 = "",
                template            = "",
                url                 = imageUrl,
                timestamp           = timestamp,
                updated_time        = created_time,
                created_time        = created_time,
                business_id         = channel.business_id,
                channel_id          = channel.id,
                channel_ext_id      = channel.ext_id,
                channel_type        = channel.type,
                owner_id            = sender_ext_id,
                agent_id            = customer.agent_id,
                type                = msg.@event == "sendimagemsg" ? "image" : "text",
                liked               = false,
                hidden              = false,
                deleted             = false,
                urls                = "[]"
            };

            return(message);
        }
Пример #9
0
        public async Task <Customer> GetCustomer(Channel channel, ZaloMessage msg, Customer customer, string customer_ext_id)
        {
            string  business_id = channel.business_id;
            string  channel_id  = channel.id;
            var     timestamp   = msg.timestamp;
            var     time        = Core.Helpers.CommonHelper.UnixTimestampToDateTime(timestamp);
            dynamic profile     = null;

            if (customer == null)
            {
                var customer_id = CustomerService.FormatId01(business_id, customer_ext_id);

                profile = await GetProfile(customer_ext_id, Convert.ToInt64(channel.ext_id), channel.token);

                if (profile == null)
                {
                    return(null);
                }
                DateTime birthDate = DateTime.MinValue;
                try
                {
                    var birth = (long)profile.data.birthDate;
                    birthDate = Core.Helpers.CommonHelper.UnixTimestampToDateTime(birth);
                }
                catch { }
                customer = new Domain.Entities.Customer
                {
                    id           = customer_id,
                    global_id    = customer_id,
                    ext_id       = customer_ext_id,
                    app_id       = msg.appid.ToString(),
                    business_id  = business_id,
                    channel_id   = channel_id,
                    status       = "pending",
                    created_time = time,
                    updated_time = time,
                    unread       = true,
                    nonreply     = true,
                    birthdate    = birthDate,
                    timestamp    = timestamp
                };
            }

            if ((string.IsNullOrWhiteSpace(customer.name) || string.IsNullOrWhiteSpace(customer.avatar) || string.IsNullOrWhiteSpace(customer.sex)))
            {
                if (profile != null)
                {
                    customer.updated_time = time;
                    customer.timestamp    = timestamp;
                    if (string.IsNullOrWhiteSpace(customer.avatar))
                    {
                        customer.avatar = string.IsNullOrWhiteSpace(customer.avatar) ? profile.data.avatar : customer.avatar;
                    }

                    var url = customer.avatar;
                    if (!string.IsNullOrWhiteSpace(url) && !url.Contains("hibaza") && !url.Contains("firebase"))
                    {
                        try
                        {
                            customer.avatar = await DownloadToLocalAsync(url);
                        }
                        catch { }
                    }
                    if (string.IsNullOrWhiteSpace(customer.name))
                    {
                        customer.name = profile.data.displayName;
                    }
                    if (string.IsNullOrWhiteSpace(customer.sex))
                    {
                        customer.sex = (string)profile.data.userGender == "1" ? "male" : "female";
                    }
                }
            }
            return(customer);
        }