Beispiel #1
0
        public async Task <NotificationResultEN> PushTopupRequestIOs(string pPersonEmail, string pNickname, string pRequester, string pAmount, string pFirstName)
        {
            NotificationResultEN operationResult = new NotificationResultEN();

            operationResult.Platform    = "IOS";
            operationResult.Result      = false;
            operationResult.ServiceName = "OneSignal";

            try
            {
                HttpClient client = new HttpClient();
                client.BaseAddress = new Uri(Constants.OneSignalURL);
                client.DefaultRequestHeaders.Add("authorization", "Basic " + Constants.KEY_ONESIGNAL_YVR_IOS);
                string url = string.Format("/api/v1/notifications");

                var filter = new
                {
                    field    = "tag",
                    key      = "userid",
                    relation = "=",
                    value    = pPersonEmail
                };
                var notificationContent = new
                {
                    app_id            = Constants.APPID_ONESIGNAL_YVR_IOS,
                    headings          = new { en = "¡Nueva solicitud de recarga!" },
                    contents          = new { en = String.Format("Hola {0}, {1} te ha pedido una recarga de {2} al número {3}. Revisa el listado de solicitudes de recarga.", pFirstName, pNickname, pAmount, pRequester, pAmount) },
                    content_available = true,
                    ios_badgeType     = "Increase",
                    ios_badgeCount    = 1,
                    category          = "",
                    collapse_id       = "",
                    filters           = new object[] { filter }
                };

                var           jsonPost = JsonConvert.SerializeObject(notificationContent);
                StringContent _content = new StringContent(jsonPost, Encoding.UTF8, "application/json");

                var response = await client.PostAsync(url, _content);

                if (response.IsSuccessStatusCode)
                {
                    var result             = response.Content.ReadAsStringAsync().Result;
                    var notificationResult = JsonConvert.DeserializeObject <CreateResultOneSignal>(result);

                    if (notificationResult.errors == null && notificationResult.recipients > 0)
                    {
                        operationResult.CodeResult = "scheduled";
                        operationResult.Result     = true;
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.InnerException);
                EventViewerLoggerSVC.LogError("PushTopupRequest: " + ex.Message);
            }

            return(operationResult);
        }
Beispiel #2
0
        public async Task <NotificationResultEN> PushTopupRequest(string pPersonEmail, string pRequester, string pAmount)
        {
            NotificationResultEN operationResult = new NotificationResultEN();

            operationResult.Platform    = "ANDROID";
            operationResult.Result      = false;
            operationResult.ServiceName = "Engagement";

            try
            {
                var credentials = await ApplicationTokenProvider.LoginSilentAsync(Constants.TENANT_ID, Constants.CLIENT_ID, Constants.CLIENT_SECRET);

                engagementClient = new EngagementManagementClient(credentials)
                {
                    SubscriptionId = Constants.SUBSCRIPTION_ID
                };

                engagementClient.ResourceGroupName = Constants.RESOURCE_GROUP;
                engagementClient.AppCollection     = Constants.APP_COLLECTION_NAME;
                engagementClient.AppName           = Constants.APP_RESOURCE_NAME_ANDROID;

                Device userDevice = await engagementClient.Devices.GetByUserIdAsync(pPersonEmail);

                Campaign campaign = new Campaign();
                campaign.Type                  = "only_notif";
                campaign.DeliveryTime          = "any";
                campaign.PushMode              = "manual";
                campaign.NotificationType      = "system";
                campaign.NotificationCloseable = true;
                campaign.NotificationTitle     = "¡Nueva solicitud de recarga!";
                campaign.NotificationMessage   = "Hola ${userFirstName}, el número: " + pRequester + " te ha pedido una recarga de " + pAmount + ". Revisa el listado de solicitudes de recarga.";

                List <string> devices = new List <string>();
                devices.Add(userDevice.DeviceId);

                CampaignPushParameters parameters = new CampaignPushParameters(devices, campaign);
                CampaignPushResult     pushResult = await engagementClient.Campaigns.PushAsync(CampaignKinds.Announcements, Constants.TopupRequestCampaign, parameters);

                if (pushResult.InvalidDeviceIds.Count <= 0)
                {
                    //Success
                    operationResult.CodeResult = "Success";
                    operationResult.Result     = true;
                }
            }
            catch (ApiErrorException apiEx)
            {
                if (String.Equals(apiEx.Body.Error.Code, "Conflict"))
                {
                    operationResult.CodeResult = "conflict";
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.InnerException);
            }

            return(operationResult);
        }
Beispiel #3
0
        public async Task <NotificationResultEN> PushDepositNotificationAndroid(CampaignEN pCampaign, string pUserEmail, string pFirstName, string pContent)
        {
            NotificationResultEN operationResult = new NotificationResultEN();

            operationResult.Platform    = "ANDROID";
            operationResult.Result      = false;
            operationResult.ServiceName = "OneSignal";

            try
            {
                HttpClient client = new HttpClient();
                client.BaseAddress = new Uri(Constants.OneSignalURL);
                client.DefaultRequestHeaders.Add("authorization", "Basic " + Constants.KEY_ONESIGNAL_YVR_ANDROID);
                string url = string.Format("/api/v1/notifications");


                OneSignalFilter filter = new OneSignalFilter();
                filter.field    = "tag";
                filter.key      = "userid";
                filter.relation = "=";
                filter.value    = (!SingleTestModeActive()) ? pUserEmail : ConfigurationManager.AppSettings["OneSignal_SingleUserTest_Android"].ToString();


                var notificationContent = new
                {
                    app_id      = Constants.APPID_ONESIGNAL_YVR_ANDROID,
                    headings    = new { en = pCampaign.NotificationTitle },
                    contents    = new { en = String.Format("Hola {0}. {1}", pFirstName, pContent) },
                    category    = "",
                    collapse_id = "",
                    filters     = new object[] { filter }
                };

                var           jsonPost = JsonConvert.SerializeObject(notificationContent);
                StringContent _content = new StringContent(jsonPost, Encoding.UTF8, "application/json");

                var response = await client.PostAsync(url, _content);

                if (response.IsSuccessStatusCode)
                {
                    var result             = response.Content.ReadAsStringAsync().Result;
                    var notificationResult = JsonConvert.DeserializeObject <CreateResultOneSignal>(result);

                    if (notificationResult.errors == null && notificationResult.recipients > 0)
                    {
                        operationResult.CodeResult = "scheduled";
                        operationResult.Result     = true;
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.InnerException);
                EventViewerLoggerSVC.LogError("PushDepositNotification: " + ex.Message);
            }

            return(operationResult);
        }
Beispiel #4
0
        public async Task <NotificationResultEN> CreateMassiveCampaignAndroidRGO(CampaignEN pCampaignContent)
        {
            NotificationResultEN operationResult = new NotificationResultEN();

            operationResult.Platform    = "ANDROID";
            operationResult.Result      = false;
            operationResult.ServiceName = "OneSignal";

            try
            {
                HttpClient client = new HttpClient();
                client.BaseAddress = new Uri(Constants.OneSignalURL);
                client.DefaultRequestHeaders.Add("authorization", "Basic " + Constants.KEY_ONESIGNAL_RGO_ANDROID); //antes era OneSignalKey_Android_Yvr //TODO: REcomendacion: Cambiar nombre a RG!
                string url = string.Format("/api/v1/notifications");

                OneSignalFilter filter = new OneSignalFilter();

                if (RecarGOMassiveTestModeActive())
                {
                    filter.field    = "tag";
                    filter.key      = "userid";
                    filter.relation = "=";
                    filter.value    = ConfigurationManager.AppSettings["OneSignal_SingleUserTest_RGO_Android"].ToString();
                }
                else
                {
                    filter.field = "country";
                    filter.value = pCampaignContent.CountryISO2Code;
                }

                var notificationContent = new
                {
                    app_id      = Constants.APPID_ONESIGNAL_RGO_ANDROID,
                    headings    = new { en = pCampaignContent.NotificationTitle },
                    contents    = new { en = pCampaignContent.NotificationMessage },
                    big_picture = (pCampaignContent.ImageURL != null) ? pCampaignContent.ImageURL : null,
                    category    = "",
                    collapse_id = "",
                    filters     = new object[] { filter }
                };


                var           jsonPost = JsonConvert.SerializeObject(notificationContent);
                StringContent _content = new StringContent(jsonPost, Encoding.UTF8, "application/json");

                var response = await client.PostAsync(url, _content);

                if (response.IsSuccessStatusCode)
                {
                    var result             = response.Content.ReadAsStringAsync().Result;
                    var notificationResult = JsonConvert.DeserializeObject <CreateResultOneSignal>(result);

                    if (notificationResult.errors == null)
                    {
                        operationResult.CodeResult = "scheduled";
                        operationResult.Result     = true;
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.InnerException);
                EventViewerLoggerSVC.LogError("CreateMassiveCampaign: " + ex.Message);
            }
            return(operationResult);
        }
Beispiel #5
0
        //------------------------ANDROID
        #region Android
        public NotificationResultEN PushSingleUserAndroid(string pTitle, string pMessage, string pImageURL, string pUserID)
        {
            NotificationResultEN operationResult = new NotificationResultEN();

            operationResult.Platform    = "ANDROID";
            operationResult.Result      = false;
            operationResult.ServiceName = "OneSignal";

            var request = WebRequest.Create(Constants.OneSignalNotifications) as HttpWebRequest;

            request.KeepAlive   = true;
            request.Method      = "POST";
            request.ContentType = "application/json; charset=utf-8";

            request.Headers.Add("authorization", "Basic " + Constants.KEY_ONESIGNAL_RGO_ANDROID);

            var serializer = new JavaScriptSerializer();
            var filter     = new
            {
                field    = "tag",
                key      = "userid",
                relation = "=",
                value    = pUserID
            };
            var notificationContent = new
            {
                app_id            = Constants.APPID_ONESIGNAL_RGO_ANDROID,
                headings          = new { en = pTitle },
                contents          = new { en = pMessage },
                content_available = true,
                category          = "",
                big_picture       = (pImageURL != null) ? pImageURL : null,
                collapse_id       = "",
                filters           = new object[] { filter }
            };



            var param = serializer.Serialize(notificationContent);

            byte[] byteArray = Encoding.UTF8.GetBytes(param);

            string responseContent = null;

            try
            {
                using (var writer = request.GetRequestStream())
                {
                    writer.Write(byteArray, 0, byteArray.Length);
                }

                using (var response = request.GetResponse() as HttpWebResponse)
                {
                    using (var reader = new StreamReader(response.GetResponseStream()))
                    {
                        responseContent = reader.ReadToEnd();
                        var serializedResult = serializer.Deserialize <CreateResultOneSignal>(responseContent);

                        if (serializedResult.errors == null)
                        {
                            operationResult.Result     = true;
                            operationResult.CodeResult = "scheduled";
                        }
                    }
                }
            }
            catch (WebException ex)
            {
                operationResult.Result     = false;
                operationResult.CodeResult = "error";
                Console.WriteLine(ex.InnerException);
                System.Diagnostics.Debug.WriteLine(new StreamReader(ex.Response.GetResponseStream()).ReadToEnd());
                EventViewerLoggerSVC.LogError("PushSingleUserAndroid: " + ex.Message);
            }

            return(operationResult);
        }
Beispiel #6
0
        public async Task <NotificationResultEN> CreateMassiveCampaignIOs(CampaignEN pCampaignContent)
        {
            NotificationResultEN operationResult = new NotificationResultEN();

            operationResult.Platform    = "IOS";
            operationResult.Result      = false;
            operationResult.ServiceName = "OneSignal";

            try
            {
                HttpClient client = new HttpClient();
                client.BaseAddress = new Uri(Constants.OneSignalURL);
                client.DefaultRequestHeaders.Add("authorization", "Basic " + Constants.KEY_ONESIGNAL_YVR_IOS);
                string url = string.Format("/api/v1/notifications");

                #region Target Filter
                OneSignalFilter filter = new OneSignalFilter();

                if (MassiveTestModeActive())
                {
                    filter.field    = "tag";
                    filter.key      = "userid";
                    filter.relation = "=";
                    filter.value    = ConfigurationManager.AppSettings["OneSignal_SingleUserTest"].ToString();
                }
                else
                {
                    filter.field = "country";
                    filter.value = pCampaignContent.CountryISO2Code;
                }
                #endregion

                var attachment = new
                {
                    id = (pCampaignContent.ImageURL != null) ? pCampaignContent.ImageURL : null
                };

                var notificationContent = new
                {
                    app_id            = Constants.APPID_ONESIGNAL_YVR_IOS,
                    headings          = new { en = pCampaignContent.NotificationTitle },
                    contents          = new { en = pCampaignContent.NotificationMessage },
                    content_available = true,
                    ios_badgeType     = "Increase",
                    ios_badgeCount    = 1,
                    category          = "",
                    collapse_id       = "",
                    ios_attachments   = (pCampaignContent.ImageURL != null) ? attachment : null,
                    filters           = new object[] { filter }
                };



                var           jsonPost = JsonConvert.SerializeObject(notificationContent);
                StringContent _content = new StringContent(jsonPost, Encoding.UTF8, "application/json");

                var response = await client.PostAsync(url, _content);

                if (response.IsSuccessStatusCode)
                {
                    var result             = response.Content.ReadAsStringAsync().Result;
                    var notificationResult = JsonConvert.DeserializeObject <CreateResultOneSignal>(result);

                    if (notificationResult.errors == null)
                    {
                        operationResult.CodeResult = "scheduled";
                        operationResult.Result     = true;
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.InnerException);
                EventViewerLoggerSVC.LogError("CreateMassiveCampaign: " + ex.Message);
            }

            return(operationResult);
        }
Beispiel #7
0
        public async Task <NotificationResultEN> CreateMassiveCampaign(CampaignEN pCampaignContent)
        {
            NotificationResultEN operationResult = new NotificationResultEN();

            operationResult.Platform    = "ANDROID";
            operationResult.Result      = false;
            operationResult.ServiceName = "Engagement";

            int engagementCampaignID = 0;

            try
            {
                var credentials = await ApplicationTokenProvider.LoginSilentAsync(Constants.TENANT_ID, Constants.CLIENT_ID, Constants.CLIENT_SECRET);

                engagementClient = new EngagementManagementClient(credentials)
                {
                    SubscriptionId = Constants.SUBSCRIPTION_ID
                };

                engagementClient.ResourceGroupName = Constants.RESOURCE_GROUP;
                engagementClient.AppCollection     = Constants.APP_COLLECTION_NAME;
                engagementClient.AppName           = Constants.APP_RESOURCE_NAME_ANDROID;

                #region Campaign Audience
                //Campaign audience
                CampaignAudience audience = new CampaignAudience();

                if (YVRMassiveTestModeActive())
                {
                    string userTest = ConfigurationManager.AppSettings["Engagement_SingleUserTest"].ToString();

                    Dictionary <string, Criterion> stringTagCriteria = new Dictionary <string, Criterion>();
                    stringTagCriteria.Add("StringTag", new StringTagCriterion("userid", userTest));
                    audience.Expression = "StringTag";
                    audience.Criteria   = stringTagCriteria;
                }
                else
                {
                    Dictionary <string, Criterion> locationCriteria = new Dictionary <string, Criterion>();
                    locationCriteria.Add("CarrierCountry", new CarrierCountryCriterion(pCampaignContent.CountryISO2Code));
                    audience.Expression = "CarrierCountry";
                    audience.Criteria   = locationCriteria;
                }
                #endregion

                NotificationOptions notificationOptions = new NotificationOptions();
                notificationOptions.BigPicture = (pCampaignContent.ImageURL != null) ? pCampaignContent.ImageURL : null;


                Campaign campaigne = new Campaign(
                    name: pCampaignContent.Title,
                    notificationTitle: pCampaignContent.NotificationTitle,
                    notificationMessage: pCampaignContent.NotificationMessage,
                    type: "text/plain",
                    deliveryTime: "any",
                    notificationType: "system",
                    pushMode: "one-shot",
                    title: pCampaignContent.NotificationTitle,
                    body: pCampaignContent.NotificationMessage,
                    actionButtonText: "ACEPTAR",
                    notificationOptions: (pCampaignContent.ImageURL != null) ? notificationOptions : null, //If imageURL is null or empty, sets an object's null value
                    audience: audience);

                CampaignStateResult campaignResultState = await engagementClient.Campaigns.CreateAsync(CampaignKinds.Announcements, campaigne);

                if (String.Equals(campaignResultState.State, "draft"))
                {
                    engagementCampaignID = campaignResultState.Id;

                    var campaignStatus = await engagementClient.Campaigns.ActivateAsync(CampaignKinds.Announcements, engagementCampaignID);

                    operationResult.CodeResult = campaignStatus.State;

                    if (!String.Equals(campaignStatus.State, "scheduled") || !String.Equals(campaignStatus.State, "in-progress"))
                    {
                        operationResult.Result = true;
                    }
                }
            }
            catch (ApiErrorException apiEx)
            {
                if (String.Equals(apiEx.Body.Error.Code, "Conflict"))
                {
                    operationResult.CodeResult = "conflict";
                }

                EventViewerLoggerSVC.LogError("CreateMassiveCampaign: " + apiEx.Message);
            }
            catch (Exception ex)
            {
                operationResult.CodeResult = "error";
                Console.WriteLine(ex.InnerException);
                EventViewerLoggerSVC.LogError("CreateMassiveCampaign: " + ex.Message);
            }

            return(operationResult);
        }
Beispiel #8
0
        public async Task <NotificationResultEN> PushDepositNotification(CampaignEN pCampaign, string pUserEmail, string pFirstName, string pContent)
        {
            NotificationResultEN operationResult = new NotificationResultEN();

            operationResult.Platform    = "ANDROID";
            operationResult.Result      = false;
            operationResult.ServiceName = "Engagement";
            int campaignID = Constants.DepositConfCampaign;

            try
            {
                var credentials = await ApplicationTokenProvider.LoginSilentAsync(Constants.TENANT_ID, Constants.CLIENT_ID, Constants.CLIENT_SECRET);

                engagementClient = new EngagementManagementClient(credentials)
                {
                    SubscriptionId = Constants.SUBSCRIPTION_ID
                };

                engagementClient.ResourceGroupName = Constants.RESOURCE_GROUP;
                engagementClient.AppCollection     = Constants.APP_COLLECTION_NAME;
                engagementClient.AppName           = Constants.APP_RESOURCE_NAME_ANDROID;


                string userIdentifier = (!YVRSingleTestModeActive()) ? pUserEmail : ConfigurationManager.AppSettings["Engagement_SingleUserTest"].ToString();

                Device userDevice = await engagementClient.Devices.GetByUserIdAsync(userIdentifier);

                Campaign campaign = new Campaign();
                campaign.Type                  = "text/plain";
                campaign.DeliveryTime          = "any";
                campaign.PushMode              = "manual";
                campaign.NotificationType      = "system";
                campaign.NotificationCloseable = true;
                campaign.NotificationTitle     = pCampaign.NotificationTitle;
                campaign.NotificationMessage   = String.Format("Hola {0}, tu deposito fue validado de forma exitosa, haz click aquí para más detalles.", pFirstName);
                campaign.Title                 = pCampaign.Title;
                campaign.Body                  = pContent;
                campaign.ActionButtonText      = "ACEPTAR";


                List <string> devices = new List <string>();
                devices.Add(userDevice.DeviceId);

                CampaignPushParameters parameters = new CampaignPushParameters(devices, campaign);
                CampaignPushResult     pushResult = await engagementClient.Campaigns.PushAsync(CampaignKinds.Announcements, campaignID, parameters);

                if (pushResult.InvalidDeviceIds.Count <= 0)
                {
                    //Success
                    operationResult.Result = true;
                }
            }
            catch (ApiErrorException apiEx)
            {
                if (String.Equals(apiEx.Body.Error.Code, "Conflict"))
                {
                    operationResult.CodeResult = "conflict";
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.InnerException);
            }

            return(operationResult);
        }