Exemplo n.º 1
0
        public static async Task <IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = null)]
            HttpRequest req,
            ILogger log,
            ExecutionContext context)
        {
            log.LogInformation("Request notified");

            if (!req.Method.Equals("GET") && !req.Method.Equals("POST"))
            {
                return(new BadRequestObjectResult("Unexpected " + req.Method + " request"));
            }

            // Validation token for webhook registration
            //  reply token to accept webhook subscription
            var validationToken = req.Query["validationToken"].ToString();

            if (!String.IsNullOrEmpty(validationToken))
            {
                dynamic data = JsonConvert.SerializeObject(validationToken);
                return(new ContentResult {
                    Content = data, ContentType = "application/json; charset=utf-8", StatusCode = 200
                });
            }

            // Get webhook and process it
            var requestBody = await new StreamReader(req.Body).ReadToEndAsync();
            var ev          = !String.IsNullOrEmpty(requestBody) ? JsonConvert.DeserializeObject <WebHookEvents>(requestBody) : null;

            log.LogInformation("Request notified from webhook : " + requestBody);

            // Load configuration
            var configBuilder = new ConfigurationBuilder()
                                .SetBasePath(context.FunctionAppDirectory)
                                .AddJsonFile("local.settings.json", optional: true, reloadOnChange: true)
                                .AddEnvironmentVariables()
                                .Build();
            var config           = new ConnectorConfig(configBuilder);
            var centralConnector = new BusinessCentralConnector(config, log);
            var composer         = new MessageComposer(config, log);
            var messenger        = new MessageConnector(config, log);
            var paypal           = new PayPalConnector(config, log);

            if (!(ev == null || ev.Value == null || ev.Value.Count == 0))
            {
                log.LogInformation(String.Format("Found {0} events", ev.Value.Count.ToString()));
                var wb_UpdatedEvents = ev.Value.Where(a => a.ChangeType.Equals("updated")).ToList();
                log.LogInformation(String.Format("Found {0} update events", wb_UpdatedEvents.Count().ToString()));
                foreach (var wb_event in wb_UpdatedEvents)
                {
                    log.LogInformation(String.Format("Processing event : {0}", wb_event?.Resource));

                    // Business Central is queried to get order and sale agent detail
                    var paypalPendingOrder = await centralConnector.GetPayPalOrderByWebhook(wb_event);

                    if (paypalPendingOrder != null)
                    {
                        log.LogInformation(String.Format("Order : {0} of customer {1}", paypalPendingOrder?.Number, paypalPendingOrder?.CustomerNumber));

                        var customer = await centralConnector.GetCustomerByOrder(paypalPendingOrder);

                        log.LogInformation(String.Format("Customer : {0}", customer?.Number));

                        // Create PayPal request
                        var paypalResponse = await paypal.CreateRequest(paypalPendingOrder, customer);

                        // Update order status as PayPal-pending payment
                        await centralConnector.UpdatePayPalOrderById(paypalPendingOrder, paypalResponse.Id, config.paymentTermsIdPayPal);

                        // Message is composed
                        var messageText = composer.DataBindMessage(paypalPendingOrder);
                        var messageHtml = composer.DataBindEmail(paypalPendingOrder, paypalResponse);
                        log.LogInformation(String.Format("Message : {0}", messageText));

                        // Message sent
                        //var messageSms = messenger.SendSMS(messageText, customer, config);
                        var messageEmail = messenger.SendCustomerMail(messageHtml, customer);
                        log.LogInformation(String.Format("SMS/Email Message result : {0}", messageEmail.Status));
                    }
                }
                return(new StatusCodeResult(200));
            }
            return(new StatusCodeResult(200));
        }
Exemplo n.º 2
0
        public static async Task <IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = null)]
            HttpRequest req,
            ILogger log,
            ExecutionContext context)
        {
            log.LogInformation(string.Format("start"));

            // Load configuration
            var config = new ConfigurationBuilder()
                         .SetBasePath(context.FunctionAppDirectory)
                         .AddJsonFile("local.settings.json", optional: true, reloadOnChange: true)
                         .AddEnvironmentVariables().Build();
            var hubConfig = new ConnectorConfig(config);

            // Compose message
            var message = req.Query["message"].ToString();
            var user    = req.Query["user"].ToString();

            log.LogInformation(string.Format("user: {0}", user));
            log.LogInformation(string.Format("message: {0}", message));

            if (string.IsNullOrEmpty(message))
            {
                message = string.Format(hubConfig.DefaultMessage, DateTime.Now.ToString("dd/MM/yy HH:mm:ss"));
            }
            // If you want to implement tag ..
            var tag = req.Query["tag"].ToString();

            if (string.IsNullOrEmpty(tag))
            {
                if (string.IsNullOrEmpty(user))
                {
                    tag = hubConfig.DefaultTag;
                }
                else
                {
                    var bcConnector = new BusinessCentralConnector(hubConfig, log);
                    var result      = await bcConnector.GetUser(user, "APP365TEUsers");

                    if (result != null && result.Value != null && result.Value.Count > 0)
                    {
                        tag = result.Value[0].UserCode;
                    }
                }
            }

            var hub =
                NotificationHubClient.CreateClientFromConnectionString(
                    hubConfig.ConnectionString,
                    hubConfig.NotificationHubName);

            if (hubConfig.SendApple)
            {
                log.LogInformation(string.Format("SendApple {0}", tag));
                // Create class for AzureNotification Hub (APPLE)
                var appleAps = new AppleBaseAps()
                {
                    InAppMessage = message,
                    Aps          = new AppleAps()
                    {
                        Badge = hubConfig.DefaultBadge, Sound = "default", Alert = message
                    }
                };

                // Dispatch push message (APPLE)
                if (!String.IsNullOrEmpty(tag))
                {
                    hub.SendAppleNativeNotificationAsync(JsonConvert.SerializeObject(appleAps), tag).Wait();
                }
                else
                {
                    hub.SendAppleNativeNotificationAsync(JsonConvert.SerializeObject(appleAps)).Wait();
                }
            }

            if (hubConfig.SendAndroid)
            {
                log.LogInformation(string.Format("SendAndroid {0}", tag));
                // Create class for AzureNotification Hub (GOOGLE FIREBASE FCM)
                // Dispatch push message (GOOGLE FIREBASE FCM)
                var firebaseAps = new FirebaseBaseAps()
                {
                    data = new FirebaseAps()
                    {
                        Message = message
                    }
                };

                if (!String.IsNullOrEmpty(tag))
                {
                    hub.SendFcmNativeNotificationAsync(JsonConvert.SerializeObject(firebaseAps), tag).Wait();
                }
                else
                {
                    hub.SendFcmNativeNotificationAsync(JsonConvert.SerializeObject(firebaseAps)).Wait();
                }
            }

            if (hubConfig.SendMail && !string.IsNullOrEmpty(user))
            {
                var composer  = new MessageComposer(hubConfig, log);
                var messenger = new MessageConnector(hubConfig, log);

                // Message is composed
                var messageHtml = composer.DataBindEmail(message);
                log.LogInformation(String.Format("Send Email Message : {0}", messageHtml));

                // Message sent
                var messageEmail = messenger.SendMail(messageHtml, user);
                log.LogInformation(String.Format("Email Message result : {0}", messageEmail.Status));
            }

            return(new StatusCodeResult(200));
        }