public async Task <string> GetFolderListAsync(ConnectorConfig config, string publicUrl, string macEvaluatedUrl) { var returnValue = string.Empty; var requestDateString = DateTime.UtcNow.ToString("R", CultureInfo.InvariantCulture); using (var httpClient = new HttpClient()) { using (var request = new HttpRequestMessage(HttpMethod.Get, publicUrl)) { request.Headers.Clear(); request.Headers.TryAddWithoutValidation("x-ms-version", "2017-11-09"); request.Headers.TryAddWithoutValidation("x-ms-date", requestDateString); var authorizationSharedKey = GetSharedKey(config.accountName, config.accountKey, request); request.Headers.TryAddWithoutValidation("Authorization", "SharedKey " + authorizationSharedKey); var responseMessage = await httpClient.SendAsync(request); if (responseMessage.IsSuccessStatusCode) { returnValue = await responseMessage.Content.ReadAsStringAsync(); } } return(returnValue); } }
public PayPalConnector(ConnectorConfig config, ILogger log) { this.config = config; this.log = log; this.ApiOrderEndpoint = String.Format("{0}checkout/orders", config.paypalBaseEndpoint); this.AuthInfo = Convert.ToBase64String(Encoding.Default.GetBytes(String.Format("{0}:{1}", config.payPalClientId, config.paypalSecret))); }
public async Task <IActionResult> Run( [HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequest req, ILogger log, ExecutionContext context) { log.LogInformation("C# HTTP trigger function processed a request."); #region Load configuration var configBuilder = new ConfigurationBuilder() .SetBasePath(context.FunctionAppDirectory) .AddJsonFile("local.settings.json", optional: true, reloadOnChange: true) .AddEnvironmentVariables() .Build(); var config = new ConnectorConfig(configBuilder); #endregion #region GetSharedKeyLite var sb = new StringBuilder(); var publicUrl = String.Format("{0}/{1}?restype=directory&comp=list", config.azurePublicUrl, config.workingFolder); var urlForMacEvaluation = String.Format("/{0}/{1}/{2}?comp=list", config.accountName, config.shareName, config.workingFolder); sb.Append(await _azurestorage.GetFolderListAsync(config, publicUrl, urlForMacEvaluation)); return(new OkObjectResult(sb.ToString())); #endregion }
public async Task UploadAsync(ConnectorConfig config, string fullFileName, MemoryStream stream) { var dirName = Path.GetDirectoryName(fullFileName).ToString(); var fileName = Path.GetFileName(fullFileName).ToString(); ShareClient share = new ShareClient(config.connectionString, config.shareName); if (!share.Exists()) { await share.CreateAsync(); } ShareDirectoryClient directory = share.GetDirectoryClient(dirName); if (!directory.Exists()) { await directory.CreateAsync(); } ShareFileClient file = directory.GetFileClient(fileName); await file.CreateAsync(stream.Length); await file.UploadAsync(stream); /* * await file.UploadRange( * ShareFileRangeWriteType.Update, * new HttpRange(0, stream.Length), * stream);*/ }
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 BusinessCentralConnector(ConnectorConfig config) { this.config = config; this.ApiWebHookEndPoint = String.Format("https://api.businesscentral.dynamics.com/{0}/{1}/", config.apiVersion1, config.tenant); this.ApiEndPoint = String.Format("https://api.businesscentral.dynamics.com/{0}/{1}/api/{2}/companies({3})/", config.apiVersion1, config.tenant, config.apiVersion2, config.companyID); this.AuthInfo = Convert.ToBase64String(Encoding.Default.GetBytes(config.authInfo)); }
public BusinessCentralConnector(ConnectorConfig config, ILogger log) { this.config = config; this.log = log; this.ApiEndPoint = string.Format("https://api.businesscentral.dynamics.com/{0}/{1}/api/{2}/{3}/companies({4})/", config.BCApiVersion, config.BCTenant, config.BCApiPrefix, config.BCApiVersion, config.BCCompanyID); this.AuthInfo = Convert.ToBase64String(Encoding.Default.GetBytes(config.BCAuthInfo)); }
public ShopifyConnector(ConnectorConfig config, ILogger log) { this.config = config; this.log = log; this.ShopifyBaseApi = String.Format("https://{0}{1}", config.shopifyShopName, config.shopifyApiUrl); this.ShopifyAuthInfo = String.Format("{0}:{1}", config.shopifyApiKey, config.shopifyApiPassword); this.ShopifyAuthInfo = Convert.ToBase64String(Encoding.Default.GetBytes(this.ShopifyAuthInfo)); }
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)); }
public async Task <MemoryStream> DownloadAsync(ConnectorConfig config, string fullFileName) { var dirName = Path.GetDirectoryName(fullFileName).ToString(); var fileName = Path.GetFileName(fullFileName).ToString(); ShareClient share = new ShareClient(config.connectionString, config.shareName); ShareDirectoryClient directory = share.GetDirectoryClient(dirName); ShareFileClient file = directory.GetFileClient(fileName); ShareFileDownloadInfo download = await file.DownloadAsync(); var stream = new MemoryStream(); await download.Content.CopyToAsync(stream); return(stream); }
public async Task <IActionResult> Run( [HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequest req, ILogger log, ExecutionContext context) { log.LogInformation("C# HTTP trigger function processed a request."); #region Process parameters string fileName = req.Query["fileName"]; if (String.IsNullOrEmpty(fileName)) { log.LogInformation("Mandatory parameter omitted."); return(new BadRequestResult()); } log.LogInformation($"Uploading file {fileName}"); #endregion #region Load configuration var configBuilder = new ConfigurationBuilder() .SetBasePath(context.FunctionAppDirectory) .AddJsonFile("local.settings.json", optional: true, reloadOnChange: true) .AddEnvironmentVariables() .Build(); var config = new ConnectorConfig(configBuilder); #endregion #region Download file string requestBody = await new StreamReader(req.Body).ReadToEndAsync(); byte[] byteArray = Encoding.ASCII.GetBytes(requestBody); MemoryStream stream = new MemoryStream(byteArray); await _azurestorage.UploadAsync(config, fileName, stream); var responseMessage = string.IsNullOrEmpty(fileName) ? "This HTTP triggered function executed successfully. Pass a name in the query string and the file in the request body." : $"Hello, This HTTP triggered function executed successfully {fileName}."; return(new OkObjectResult(responseMessage)); #endregion }
public async Task <IActionResult> Run( [HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequest req, ILogger log, ExecutionContext context) { log.LogInformation("C# HTTP trigger function processed a request."); #region Process parameters var fileName = req.Query["fileName"].ToString(); var contentType = req.Query["contentType"].ToString(); if (String.IsNullOrEmpty(fileName)) { log.LogInformation("Mandatory parameter omitted."); return(new BadRequestResult()); } log.LogInformation($"Downloading file {fileName}"); if (String.IsNullOrEmpty(contentType)) { contentType = "application/binary"; } #endregion #region Load configuration var configBuilder = new ConfigurationBuilder() .SetBasePath(context.FunctionAppDirectory) .AddJsonFile("local.settings.json", optional: true, reloadOnChange: true) .AddEnvironmentVariables() .Build(); var config = new ConnectorConfig(configBuilder); #endregion #region Download var outputStream = await _azurestorage.DownloadAsync(config, fileName); return(new FileContentResult(outputStream.ToArray(), contentType)); #endregion }
public async Task <IActionResult> Run( [HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequest req, ILogger log, ExecutionContext context) { log.LogInformation("C# HTTP trigger function processed a request."); #region Load configuration var configBuilder = new ConfigurationBuilder() .SetBasePath(context.FunctionAppDirectory) .AddJsonFile("local.settings.json", optional: true, reloadOnChange: true) .AddEnvironmentVariables() .Build(); var config = new ConnectorConfig(configBuilder); #endregion #region GetSharedKeyLite var sb = new StringBuilder(); var urlForMacEvaluationGetFileExist = String.Format("/{0}/{1}/{2}/sample3.txt", config.accountName, config.shareName, config.workingFolder); var urlForMacEvaluationGetDontExist = String.Format("/{0}/{1}/{2}/dontexist.txt", config.accountName, config.shareName, config.workingFolder); var urlForMacEvaluationGetFolderExist = String.Format("/{0}/{1}/{2}", config.accountName, config.shareName, config.workingFolder); var urlForMacEvaluationGetFolderDoesNotExist = String.Format("/{0}/{1}/{2}", config.accountName, config.shareName, "nofoo"); var contentUrl = string.Empty; sb.AppendLine("-----------------------------------------------------------------------------"); sb.AppendLine("FILE EXISTS"); sb.AppendLine(_azurestorage.GetSharedKeyLiteHead(config, urlForMacEvaluationGetFileExist, contentUrl)); sb.AppendLine("-----------------------------------------------------------------------------"); sb.AppendLine("FILE DOES NOT EXISTS"); sb.AppendLine(_azurestorage.GetSharedKeyLiteHead(config, urlForMacEvaluationGetDontExist, contentUrl)); sb.AppendLine("-----------------------------------------------------------------------------"); sb.AppendLine("FOLDER EXISTS"); sb.AppendLine(_azurestorage.GetSharedKeyLiteHead(config, urlForMacEvaluationGetFolderExist, contentUrl)); sb.AppendLine("-----------------------------------------------------------------------------"); sb.AppendLine("FOLDER DOES NOT EXISTS"); sb.AppendLine(_azurestorage.GetSharedKeyLiteHead(config, urlForMacEvaluationGetFolderDoesNotExist, contentUrl)); return(new OkObjectResult(sb.ToString())); #endregion }
public MessageResource SendMessage(string text, Employee salesAgent, ConnectorConfig config) { // Find your Account Sid and Token at twilio.com/console var accountSid = config.twilioSID; var authToken = config.twilioToken; var toNumber = salesAgent == null || String.IsNullOrEmpty(salesAgent.PhoneNumber) ? config.twilioDefaultNumber : salesAgent.PhoneNumber; TwilioClient.Init(accountSid, authToken); // Twilio allow sending messages only to verified numbers // Number verification procedure available at this link: // twilio.com/user/account/phone-numbers/verified var message = MessageResource.Create( body: text, from: new Twilio.Types.PhoneNumber(config.twilioFromNumber), to: new Twilio.Types.PhoneNumber(toNumber) ); return(message); }
public async Task <IActionResult> Run( [HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequest req, ILogger log, ExecutionContext context) { log.LogInformation("C# HTTP trigger function processed a request."); #region Load configuration var configBuilder = new ConfigurationBuilder() .SetBasePath(context.FunctionAppDirectory) .AddJsonFile("local.settings.json", optional: true, reloadOnChange: true) .AddEnvironmentVariables() .Build(); var config = new ConnectorConfig(configBuilder); #endregion #region GetSharedKeyLite var sb = new StringBuilder(); var urlForMacEvaluationRange = String.Format("/{0}/{1}/{2}?comp=range", config.accountName, config.shareName, "foo/foo_rest_api.txt"); var urlForMacEvaluationInit = String.Format("/{0}/{1}/{2}", config.accountName, config.shareName, "foo/foo_rest_api.txt"); var urlForMacCopyInit = String.Format("/{0}/{1}/{2}", config.accountName, config.shareName, "foo/copy_of_dyn3.jpg"); var contentUrl = string.Empty; sb.AppendLine("-----------------------------------------------------------------------------"); sb.AppendLine("FILE PUT"); sb.AppendLine(_azurestorage.GetSharedKeyLitePut(config, urlForMacEvaluationInit, contentUrl, 999, "init", string.Empty)); sb.AppendLine("-----------------------------------------------------------------------------"); sb.AppendLine("FILE PUT RANGE"); sb.AppendLine(_azurestorage.GetSharedKeyLitePut(config, urlForMacEvaluationRange, contentUrl, 999, "range", string.Empty)); sb.AppendLine("-----------------------------------------------------------------------------"); sb.AppendLine("FILE PUT COPY"); var fileName = string.Format("{0}/{1}/{2}", config.azurePublicUrl, "foo", "dyn3.jpg"); sb.AppendLine(_azurestorage.GetSharedKeyLitePut(config, urlForMacCopyInit, contentUrl, 0, "copyfile", fileName)); return(new OkObjectResult(sb.ToString())); #endregion }
public static async Task <HttpResponseMessage> Run( [HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = null)] HttpRequest req, ILogger log, ExecutionContext context) { log.LogInformation("Request notified"); // Load configuration var configBuilder = new ConfigurationBuilder() .SetBasePath(context.FunctionAppDirectory) .AddJsonFile("local.settings.json", optional: true, reloadOnChange: true) .AddEnvironmentVariables() .Build(); var config = new ConnectorConfig(configBuilder); if (!req.Method.Equals("GET")) { throw new HttpResponseException(HttpStatusCode.BadRequest); } var orderID = req.Query["orderID"].ToString(); if (String.IsNullOrEmpty(orderID)) { throw new HttpResponseException(HttpStatusCode.BadRequest); } var composer = new MessageComposer(config, log); var html = composer.DataBindPayPalPage(orderID); var response = new HttpResponseMessage(HttpStatusCode.OK); response.Content = new StringContent(html); response.Content.Headers.ContentType = new MediaTypeHeaderValue("text/html"); return(response); }
public string GetSharedKeyLiteHead(ConnectorConfig config, string url, string contentType) { return(GetSharedKeyLite(HttpMethod.Head, config, url, contentType, 0, string.Empty, string.Empty)); }
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(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)); }
public BusinessCentralConnector(ConnectorConfig config) { this.config = config; }
public string GetSharedKeyLitePut(ConnectorConfig config, string url, string contentType, int contentLength, string subType, string fileSource) { return(GetSharedKeyLite(HttpMethod.Put, config, url, contentType, contentLength, subType, fileSource)); }
public MessageComposer(ConnectorConfig config, ILogger log) { this.config = config; this.log = log; }
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 string GetSharedKeyLite(HttpMethod method, ConnectorConfig config, string url, string contentType, int contentLength, string subType, string fileSource) { var StorageAccountName = config.accountName; var StorageKey = config.accountKey; var requestDateString = DateTime.UtcNow.ToString("R", CultureInfo.InvariantCulture); var canonicalizedStringToBuild = String.Format("{0}\n{1}\n{2}\n{3}\n{4}\n{5}\n{6}", method.ToString(), String.Empty, contentType, string.Empty, "x-ms-date:" + requestDateString, "x-ms-version:2017-11-09", url); if (method == HttpMethod.Put) { if (subType.Equals("init")) { canonicalizedStringToBuild = String.Format("{0}\n{1}\n{2}\n{3}\n{4}\n{5}\n{6}\n{7}\n{8}", method.ToString(), String.Empty, contentType, string.Empty, "x-ms-content-length:" + contentLength.ToString(), "x-ms-date:" + requestDateString, "x-ms-type:file", "x-ms-version:2017-11-09", url); } else if (subType.Equals("copyfile")) { canonicalizedStringToBuild = String.Format("{0}\n{1}\n{2}\n{3}\n{4}\n{5}\n{6}\n{7}\n{8}", method.ToString(), String.Empty, contentType, string.Empty, "x-ms-copy-source:" + fileSource, "x-ms-date:" + requestDateString, "x-ms-type:file", "x-ms-version:2017-11-09", url); } else { canonicalizedStringToBuild = String.Format("{0}\n{1}\n{2}\n{3}\n{4}\n{5}\n{6}\n{7}\n{8}\n{9}\n{10}", method.ToString(), String.Empty, contentType, string.Empty, "x-ms-content-length:" + contentLength.ToString(), "x-ms-date:" + requestDateString, "x-ms-range:bytes=0-554", "x-ms-type:file", "x-ms-version:2017-11-09", "x-ms-write:update", url); } } var signature = string.Empty; using (var hmac = new HMACSHA256(Convert.FromBase64String(StorageKey))) { byte[] dataToHmac = Encoding.UTF8.GetBytes(canonicalizedStringToBuild); signature = Convert.ToBase64String(hmac.ComputeHash(dataToHmac)); } var sharedKeyLite = string.Format("SharedKeyLite " + $"{StorageAccountName}:" + signature); return(sharedKeyLite + "\n" + requestDateString + "\n" + canonicalizedStringToBuild); }
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)); }