Exemplo n.º 1
0
 private void CreatePushNotification(string notificationtext, string devicetoken)
 {
     var payload1 = new NotificationPayload(devicetoken, notificationtext,  1, "default", 1);
     var notificationList = new List<NotificationPayload> { payload1 };
     var push = new PushNotification(UseAppleSandbox, CertPath, CertPassword);
     var rejected = push.SendToApple(notificationList);
 }
        private static byte[] GeneratePayload(NotificationPayload payload)
        {
            try
            {
                //convert Devide token to HEX value.
                byte[] deviceToken = new byte[payload.DeviceToken.Length / 2];
                for (int i = 0; i < deviceToken.Length; i++)
                {
                    deviceToken[i] = byte.Parse(payload.DeviceToken.Substring(i * 2, 2), System.Globalization.NumberStyles.HexNumber);
                }

                var memoryStream = new MemoryStream();

                // Command
                memoryStream.WriteByte(1); // Changed command Type

                //Adding ID to Payload
                memoryStream.Write(Encoding.ASCII.GetBytes(payload.PayloadId.ToString()), 0, payload.PayloadId.ToString().Length);

                //Adding ExpiryDate to Payload
                int    epoch     = (int)(DateTime.UtcNow.AddMinutes(300) - new DateTime(1970, 1, 1)).TotalSeconds;
                byte[] timeStamp = BitConverter.GetBytes(epoch);
                memoryStream.Write(timeStamp, 0, timeStamp.Length);

                byte[] tokenLength = BitConverter.GetBytes((Int16)32);
                Array.Reverse(tokenLength);
                // device token length
                memoryStream.Write(tokenLength, 0, 2);

                // Token
                memoryStream.Write(deviceToken, 0, 32);

                // String length
                string apnMessage = payload.ToJson();
                Logger.Info("Payload generated for " + payload.DeviceToken + " : " + apnMessage);

                byte[] apnMessageLength = BitConverter.GetBytes((Int16)apnMessage.Length);
                Array.Reverse(apnMessageLength);

                // message length
                memoryStream.Write(apnMessageLength, 0, 2);

                // Write the message
                memoryStream.Write(Encoding.ASCII.GetBytes(apnMessage), 0, apnMessage.Length);
                return(memoryStream.ToArray());
            }
            catch (Exception ex)
            {
                Logger.Error("Unable to generate payload - " + ex.Message);
                return(null);
            }
        }
Exemplo n.º 3
0
        private static void Main(string[] args)
        {
            var payload1 = new NotificationPayload("Device Token", "Message", 1, "default");
            payload1.AddCustom("RegionID", "IDQ10150");

            var p = new List<NotificationPayload> {payload1};

            var push = new PushNotification(false, "p12 file location","password");
            var rejected = push.SendToApple(p);
            foreach (var item in rejected)
            {
                Console.WriteLine(item);
            }
            Console.ReadLine();
        }
        public void SendNotification(string deviceToken, string message, Dictionary<string, string> customValues = null)
        {

            var payload = new NotificationPayload(deviceToken, message, 0, "default");
            if (customValues != null)
                foreach (var customValue in customValues)
                {
                    payload.AddCustom(customValue.Key, customValue.Value);
                }
            //payload1.AddCustom("CustomKey", "CustomValue");
            LogWriter.Write(deviceToken + message);
            var notificationList = new List<NotificationPayload> { payload };
            var cert = Properties.Settings.Default.ApnsCertificateName;
            var pwd = Properties.Settings.Default.ApnsCertificatePassword;
            var push = new PushNotification(false, System.Web.Hosting.HostingEnvironment.MapPath(string.Format("~/bin/{0}.p12",cert)), pwd);
            push.SendToApple(notificationList);
        }
Exemplo n.º 5
0
        private static void Main(string[] args)
        {
            // var payload1 = new NotificationPayload("Device token","Message",Badge,"Sound");
            var payload1 = new NotificationPayload("Device Token", "Message", 1, "default");

            payload1.AddCustom("RegionID", "IDQ10150");

            var p = new List <NotificationPayload> {
                payload1
            };

            var push     = new PushNotification(false, "p12 file location", "password");
            var rejected = push.SendToApple(p);

            foreach (var item in rejected)
            {
                Console.WriteLine(item);
            }
            Console.ReadLine();
        }
Exemplo n.º 6
0
    private static byte[] GeneratePayload(NotificationPayload payload)
    {
      try
      {
        //convert Devide token to HEX value.
        byte[] deviceToken = new byte[payload.DeviceToken.Length / 2];
        for (int i = 0; i < deviceToken.Length; i++)
            deviceToken[i] = byte.Parse(payload.DeviceToken.Substring(i * 2, 2), System.Globalization.NumberStyles.HexNumber);

        var memoryStream = new MemoryStream();

        // Command
        memoryStream.WriteByte(1); // Changed command Type 

        //Adding ID to Payload
        memoryStream.Write(Encoding.ASCII.GetBytes(payload.PayloadId.ToString()), 0, payload.PayloadId.ToString().Length);

        //Adding ExpiryDate to Payload
        int epoch = (int) (DateTime.UtcNow.AddMinutes(300) - new DateTime(1970, 1, 1)).TotalSeconds;
        byte[] timeStamp = BitConverter.GetBytes(epoch);
        memoryStream.Write(timeStamp, 0, timeStamp.Length);

        byte[] tokenLength = BitConverter.GetBytes((Int16) 32);
        Array.Reverse(tokenLength);
        // device token length
        memoryStream.Write(tokenLength, 0, 2);

        // Token
        memoryStream.Write(deviceToken, 0, 32);

      // String length
        string apnMessage = payload.ToJson();
        Logger.Info("Payload generated for " + payload.DeviceToken + " : " + apnMessage);

        byte[] apnMessageLength = BitConverter.GetBytes((Int16) apnMessage.Length);
        Array.Reverse(apnMessageLength);

        // message length
        memoryStream.Write(apnMessageLength, 0, 2);

        // Write the message
        memoryStream.Write(Encoding.ASCII.GetBytes(apnMessage), 0, apnMessage.Length);
        return memoryStream.ToArray();
      }
      catch (Exception ex)
      {
        Logger.Error("Unable to generate payload - " + ex.Message);
        return null;
      }
    }
Exemplo n.º 7
0
    /// <summary>
    /// Initialize a connection the the Apple Push Notification Service (APNS) and deliver a new deal notification
    /// payload to all registered devices in the database.
    /// </summary>
    /// <param name="currentHeadline">The headline to be sent in the push notification payload</param>
    private void SendNotifications(int id, string headline)
    {
        //configure and start Apple APNS
        PushNotification push;
        try {
            push = new PushNotification(false, Path.Combine(AppDomain.CurrentDomain.BaseDirectory, this.key), ConfigurationManager.AppSettings["certPassword"]);
        }
        catch (Exception e) {
            LogError("!Failed to start service.", e);
            return;
        }

        IList<DeviceToken> deviceTokens = null;
        try {
            //get a list of all registered device tokens
            using (PushModelContainer context = new PushModelContainer())
            {
                var q = (from dt in context.DeviceTokens
                         //where dt.Development.Equals(true)
                         where dt.Development.Equals(this.isDevelopment)
                         where dt.AppName.Equals(this.appName)
                         where dt.Active.Equals(true)
                         select dt);
                deviceTokens = q.ToList<DeviceToken>();

                foreach (DeviceToken deviceToken in deviceTokens) {
                    if (deviceToken.BadgeCount > 50) {
                        deviceToken.BadgeCount = 0;
                    } else {
                        deviceToken.BadgeCount++;
                    }
                }

                context.SaveChanges();
            }
        }
        catch (Exception e) {
            LogError("!Failed to fetch device tokens.", e);
            return;
        }

        //hold a list of payloads to be pushed
        var payloads = new List<NotificationPayload> {};

        //loop for every registered device token
        foreach (DeviceToken deviceToken in deviceTokens) {
            //add the payload to the list
            var payload = new NotificationPayload(deviceToken.Token, ModifyHeadline(headline), deviceToken.BadgeCount, "default");
            payload.AddCustom("id", id);
            payloads.Add(payload);
        }

        //send the payloads and get a list of rejected payloads for deletion
        Logger.Info(@" >Delivering payloads...");
        var rejectedTokens = push.SendToApple(payloads);
        if (rejectedTokens.Count > 0) {
            //deactivate all rejected device tokens
            using (PushModelContainer context = new PushModelContainer())
            {
                foreach (var rejectedToken in rejectedTokens) {
                    Logger.Warn(@"Deactivating token: " + rejectedToken);

                    DeviceToken deviceToken = (from dt in context.DeviceTokens
                                               where dt.Token.Equals(rejectedToken)
                                               select dt).FirstOrDefault();
                    if (deviceToken != null) {
                        deviceToken.Active = false;
                    }
                }
                context.SaveChanges();
            }
        }
        Logger.Info(@" >All payloads delivered.");
        Logger.Info(@"");
    }
        public bool Process(Message message)
        {
            _formattingService = new FormattingServices();
            _transactionBatchService = new TransactionBatchService(_ctx, _logger);
            _validationService = new ValidationService(_logger);
            _smsService = new SMSService(_ctx);
            _emailService = new EmailService(_ctx);
            _userService = new UserService(_ctx);
            _messageService = new MessageServices(_ctx);

            string fromAddress = "*****@*****.**";
            URIType recipientType = _messageService.GetURIType(message.RecipientUri);

            _logger.Log(LogLevel.Info, String.Format("Processing Payment Message to {0}", message.RecipientUri));

            _logger.Log(LogLevel.Info, String.Format("URI Type {0}", recipientType));

            string smsMessage;
            string emailSubject;
            string emailBody;

            var sender = message.Sender;
            var recipient = _userService.GetUser(message.RecipientUri);
            message.Recipient = recipient;

            var senderName = _userService.GetSenderName(sender);
            var recipientName = message.RecipientUri;
            //check to see if recipient uri is mobile #, email address, or ME code

            //Validate Payment

            //Batch Transacations
            _logger.Log(LogLevel.Info, String.Format("Batching Transactions for message {0}", message.Id));

            try
            {
                _transactionBatchService.BatchTransactions(message);
            }
            catch (Exception ex)
            {
                _logger.Log(LogLevel.Error, String.Format("Unable to process message {0}. {1}", message.Id, ex.Message));

                throw ex;
            }

            //Attempt to assign payment to Payee
            if (recipient != null)
            {
                recipientName = recipient.UserName;

                if (!String.IsNullOrEmpty(recipient.SenderName))
                    recipientName = recipient.SenderName;
                else if (!String.IsNullOrEmpty(recipient.MobileNumber))
                    recipientName = _formattingService.FormatMobileNumber(recipient.MobileNumber);

                //Send out SMS Message to recipient
                if (!String.IsNullOrEmpty(recipient.MobileNumber))
                {
                    _logger.Log(LogLevel.Info, String.Format("Send SMS to Recipient"));

                    smsMessage = String.Format(_recipientSMSMessage, message.Amount, senderName, _mobileWebSiteUrl);
                    _smsService.SendSMS(message.ApiKey, recipient.MobileNumber, smsMessage);
                }
                //Send SMS Message to sender
                if (!String.IsNullOrEmpty(sender.MobileNumber))
                {
                    _logger.Log(LogLevel.Info, String.Format("Send SMS to Sender"));

                    smsMessage = String.Format(_senderSMSMessage, message.Amount, recipientName, _mobileWebSiteUrl);
                    _smsService.SendSMS(message.ApiKey, sender.MobileNumber, smsMessage);

                }
                //Send confirmation email to sender
                if (!String.IsNullOrEmpty(sender.EmailAddress))
                {
                    _logger.Log(LogLevel.Info, String.Format("Sending Email Confirmation to Sender"));

                    emailSubject = String.Format(_senderConfirmationEmailSubject, recipientName);
                    emailBody = String.Format(_senderConfirmationEmailBody, recipientName, message.Amount, _mobileWebSiteUrl);

                    _emailService.SendEmail(message.ApiKey, fromAddress, sender.EmailAddress, emailSubject, emailBody);
                }
                //Send confirmation email to recipient
                if (!String.IsNullOrEmpty(recipient.EmailAddress))
                {
                    _logger.Log(LogLevel.Info, String.Format("Sending Email Confirmation to Recipient"));

                    emailSubject = String.Format(_recipientConfirmationEmailSubject, senderName, message.Amount);

            //Payment Registered Recipient
            //first_name
            //last_name
            //rec_amount
            //rec_sender
            //rec_sender_photo_url
            //rec_datetime formatted dddd, MMMM dd(rd) at hh:mm tt
            //rec_comments
            //app_user
            //link_registration - empty
                    _emailService.SendEmail(recipient.EmailAddress, emailSubject, _paymentReceivedRecipientRegisteredTemplate, new List<KeyValuePair<string, string>>()
                    {
                        new KeyValuePair<string, string>("first_name", recipient.FirstName),
                        new KeyValuePair<string, string>("last_name", recipient.LastName),
                        new KeyValuePair<string, string>("rec_amount",  String.Format("{0:C}", message.Amount)),
                        new KeyValuePair<string, string>("rec_sender", senderName),
                        new KeyValuePair<string, string>("rec_sender_photo_url", ""),
                        new KeyValuePair<string, string>("rec_datetime", message.CreateDate.ToString("dddd, MMMM dd at hh:mm tt")),
                        new KeyValuePair<string, string>("rec_comments", message.Comments),
                        new KeyValuePair<string, string>("link_registration", ""),
                        new KeyValuePair<string, string>("app_user", "false")
                    });
                }
                if (recipient.DeviceToken.Length > 0)
                {
                    _logger.Log(LogLevel.Info, String.Format("Sending iOS Push Notification to Recipient"));

                    // We need to know the number of pending requests that the user must take action on for the application badge #
                    // The badge number is the number of PaymentRequests in the Messages database with the Status of (1 - Pending)
                    //      If we are processing a payment, we simply add 1 to the number in this list. This will allow the user to
                    //      Be notified of money received, but it will not stick on the application until the users looks at it. Simplyt
                    //      Opening the application is sufficient
                    var numPending = _ctx.Messages.Where(p => p.MessageTypeValue.Equals((int)Domain.MessageType.PaymentRequest) && p.MessageStatusValue.Equals((int)Domain.MessageStatus.Pending));

                    _logger.Log(LogLevel.Info, String.Format("iOS Push Notification Num Pending: {0}", numPending.Count()));

                    NotificationPayload payload = null;
                    String notification;

                    // Send a mobile push notification
                    if (message.MessageType == Domain.MessageType.Payment)
                    {
                        notification = String.Format(_recipientWasPaidNotification, senderName, message.Amount);
                        payload = new NotificationPayload(recipient.DeviceToken, notification, numPending.Count()+1);
                        payload.AddCustom("nType", "recPCNF");
                    }
                    else if (message.MessageType == Domain.MessageType.PaymentRequest)
                    {
                        notification = String.Format(_recipientRequestNotification, senderName, message.Amount);
                        payload = new NotificationPayload(recipient.DeviceToken, notification, numPending.Count());
                        payload.AddCustom("nType", "recPRQ");
                    }

                    /*
                     *  Payment Notification Types:
                     *      Payment Request [recPRQ]
                     *          - Recipient receives notification that takes them to the
                     *                 paystream detail view about that payment request
                     *      Payment Confirmation [recPCNF]
                     *          - Recipient receices notification that takes them to the paysteam detail view about the payment request
                     */

                    payload.AddCustom("tID", message.Id);
                    var notificationList = new List<NotificationPayload>() { payload };

                    List<string> result;

                    try
                    {
                        var push = new PushNotification(true, @"C:\APNS\DevKey\aps_developer_identity.p12", "KKreap1566");
                        result = push.SendToApple(notificationList); // You are done!
                    }
                    catch (Exception ex)
                    {
                        _logger.Log(LogLevel.Fatal, String.Format("Exception sending iOS push notification. {0}", ex.Message));
                        var exception = ex.InnerException;

                        while (exception != null)
                        {
                            _logger.Log(LogLevel.Fatal, String.Format("Exception sending iOS push notification. {0}", exception.Message));

                        }
                    }

                }
                if (recipient.FacebookUser != null)
                {
                    //Send Facebook Message
                    // I don't think we can do this through the server. Nice try though.
                    // We should, however, publish something to the user's page that says sender sent payment

                }
            }
            else
            {

                _logger.Log(LogLevel.Info, String.Format("Send SMS to Payee not found"));

                var link = String.Format("{0}{1}", _mobileWebSiteUrl, message.Id.ToString());

                //Send out SMS message to sender
                if (!String.IsNullOrEmpty(sender.MobileNumber))
                {
                    _logger.Log(LogLevel.Info, String.Format("Send SMS to Sender (Recipient is not an registered user)."));

                    smsMessage = String.Format(_senderSMSMessageRecipientNotRegistered, message.Amount, message.RecipientUri, link);
                    _smsService.SendSMS(message.ApiKey, sender.MobileNumber, smsMessage);
                }
                if (!String.IsNullOrEmpty(sender.EmailAddress))
                {
                    emailSubject = String.Format(_senderConfirmationEmailSubjectRecipientNotRegistered, message.RecipientUri);
                    emailBody = String.Format(_senderConfirmationEmailBodyRecipientNotRegistered, message.Amount, message.RecipientUri);

                    //Send confirmation email to sender
                    _logger.Log(LogLevel.Info, String.Format("Send Email to Sender (Recipient is not an registered user)."));

                    _emailService.SendEmail(message.ApiKey, fromAddress, sender.EmailAddress, emailSubject, emailBody);
                }
                if (recipientType == URIType.MobileNumber)
                {
                    //Send out SMS message to recipient
                    _logger.Log(LogLevel.Info, String.Format("Send SMS to Recipient (Recipient is not an registered user)."));

                    smsMessage = String.Format(_recipientSMSMessageRecipientNotRegistered, senderName, message.Amount, link);
                    _smsService.SendSMS(message.ApiKey, message.RecipientUri, smsMessage);
                }

                emailSubject = String.Format(_recipientConfirmationEmailSubject, senderName, message.Amount);

                //Payment Registered Recipient
                //first_name
                //last_name
                //rec_amount
                //rec_sender
                //rec_sender_photo_url
                //rec_datetime formatted DayOfWeek, MM dd(rd) at hh:mm:tt
                //rec_comments
                //app_user
                //link_registration - empty
                if (recipientType == URIType.EmailAddress)
                {
                    //Send confirmation email to recipient
                    _logger.Log(LogLevel.Info, String.Format("Send Email to Recipient (Recipient is not an registered user)."));

                    _emailService.SendEmail(message.RecipientUri, emailSubject, _paymentReceivedRecipientNotRegisteredTemplate, new List<KeyValuePair<string, string>>()
                    {
                        new KeyValuePair<string, string>("first_name", ""),
                        new KeyValuePair<string, string>("last_name", ""),
                        new KeyValuePair<string, string>("rec_amount",  String.Format("{0:C}", message.Amount)),
                        new KeyValuePair<string, string>("rec_sender", senderName),
                        new KeyValuePair<string, string>("rec_sender_photo_url", ""),
                        new KeyValuePair<string, string>("rec_datetime", message.CreateDate.ToString("MM, dd yyyy hh:mm tt")),
                        new KeyValuePair<string, string>("rec_comments", message.Comments),
                        new KeyValuePair<string, string>("link_registration", link),
                        new KeyValuePair<string, string>("app_user", "false")
                    });
                }

            }

            _logger.Log(LogLevel.Info, String.Format("Updating Payment"));

            message.MessageStatus = MessageStatus.Pending;
            message.LastUpdatedDate = System.DateTime.Now;

            _ctx.SaveChanges();

            return true;
        }