public static async Task <IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = null)]
            HttpRequest req,
            ILogger log,
            ExecutionContext context)
        {
            // Load configuration
            var config = new ConfigurationBuilder()
                         .SetBasePath(context.FunctionAppDirectory)
                         .AddJsonFile("local.settings.json", optional: true, reloadOnChange: true)
                         .AddEnvironmentVariables()
                         .Build();

            // Sentence and destinatio language
            string sentence = req.Query["sentence"];
            string language = req.Query["language"];

            // Business Central is queried
            var bcConfig = new ConnectorConfig(config);
            BusinessCentralConnector centraConnector = new BusinessCentralConnector(bcConfig);
            var translation = await centraConnector.GetTranslation(sentence, language);

            // Reply with the translation
            if (translation == null || translation.Value == null || translation.Value.Count == 0)
            {
                return(new BadRequestObjectResult("Translation not found"));
            }
            string translatedText = translation.Value[0].TranslatedText;

            return(new OkObjectResult(translatedText));
        }
        public static async Task <IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = null)]
            HttpRequest req,
            ILogger log,
            ExecutionContext context)
        {
            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 webhoob subcriprion
            string validationToken = req.Query["validationToken"];

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

            // Webhook
            string requestBody = await new StreamReader(req.Body).ReadToEndAsync();
            var    ev          = !String.IsNullOrEmpty(requestBody) ? JsonConvert.DeserializeObject <WebHookEvent>(requestBody) : null;

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

            // Business Central is queried to get order and sale agent detail
            var config = new ConnectorConfig(configBuilder);
            BusinessCentralConnector centraConnector = new BusinessCentralConnector(config);
            var order = await centraConnector.GetOrderByWebhook(ev);

            var saleAgents = await centraConnector.GetSaleagentByOrder(order);

            var saleAgent = (saleAgents != null && saleAgents.Value != null && saleAgents.Value.Count > 0) ? saleAgents.Value[0] : null;

            // Message is composed
            MessageComposer composer    = new MessageComposer();
            var             messageText = composer.DataBindMessage(order);

            // Message sent
            TwilioMessage twilioMessage = new TwilioMessage();
            var           message       = twilioMessage.SendMessage(messageText, saleAgent, config);

            return(new StatusCodeResult(200));
        }
示例#3
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));
        }
        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("PayPalPaymentWebHook - 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
                });
            }

            // 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 composer         = new MessageComposer(config, log);
            var messenger        = new MessageConnector(config, log);
            var centralConnector = new BusinessCentralConnector(config, log);

            // Get webhook and process it
            var requestBody = await new StreamReader(req.Body).ReadToEndAsync();

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

            // Message sent
            var messageEmail = messenger.SendTestMail(requestBody);

            log.LogInformation(String.Format(TAG + " SMS/Email Message result : {0}", messageEmail.Status));

            // Get webhook and process it
            var ev = !String.IsNullOrEmpty(requestBody) ? JsonConvert.DeserializeObject <PayPalWebHook>(requestBody) : null;

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

            // If the webhook signals a payment
            if (ev.EventType.Equals("PAYMENT.CAPTURE.COMPLETED"))
            {
                log.LogInformation(String.Format(TAG + " PAYMENT.CAPTURE.COMPLETED : {0}", ev.Resource.Id));
                var order = await centralConnector.GetPayPalOrderByExternalDocumentNumber(ev.Resource.Id);

                if (order != null)
                {
                    log.LogInformation(String.Format(TAG + " GetPayPalOrderByExternalDocumentNumber : {0}", order.Number));
                    await centralConnector.UpdatePayPalOrderById(order, order.ExternalDocumentNumber, config.paymentTermsIdPayPalPaid);

                    log.LogInformation(String.Format(TAG + " Order updated : {0}", order.Number));

                    var html = composer.DataBindEmailPayment(order);
                    await messenger.SendAdminMail(html);
                }
                else
                {
                    log.LogError(String.Format(TAG + " PAYMENT.CAPTURE.COMPLETED Order not found {0}", ev.Resource.Id));
                }
            }
            return(new StatusCodeResult(200));
        }
        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));
        }
示例#6
0
        public static async Task <IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = null)]
            HttpRequest req,
            ILogger log,
            ExecutionContext context)
        {
            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 webhoob subcriprion
            var validationToken = req.Query["validationToken"].ToString();

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

            // Webhook
            log.LogInformation("WebHook received");
            var requestBody = await new StreamReader(req.Body).ReadToEndAsync();

            log.LogInformation("WebHook : " + requestBody);
            var ev = !String.IsNullOrEmpty(requestBody) ? JsonConvert.DeserializeObject <WebHookEvents>(requestBody) : null;

            // 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 centraConnector   = new BusinessCentralConnector(config, log);
            var customerConverter = new CustomerConverter();
            var shopifyConnector  = new ShopifyConnector(config, log);

            if (!(ev == null || ev.Value == null || ev.Value.Count == 0))
            {
                foreach (var customer in ev.Value.Where(a => a.ChangeType.Equals("created")))
                {
                    // Business Central is queried to get customer detail
                    log.LogInformation("Get customer");
                    var bcCustomer = await centraConnector.GetCustomerByWebhook(customer);

                    if (bcCustomer == null)
                    {
                        log.LogError("Cannot get customer from BC");
                    }

                    // Conversion between BC and Shopify customer entity
                    log.LogInformation("Convert entity");
                    var shopifyCustomer = customerConverter.ToShopify(bcCustomer);
                    if (shopifyCustomer == null)
                    {
                        log.LogError("Cannot convert customer");
                    }

                    // Post new customer to Shopify
                    log.LogInformation("Post customer");
                    if (shopifyCustomer != null)
                    {
                        await shopifyConnector.PostShopifyCustomers(shopifyCustomer);
                    }
                }
            }
            return(new StatusCodeResult(200));
        }