public string Post([FromBody] JObject data, string transactionId, string type)
        {
            _Logger.LogInformation("[UIController] - POST - api/ui - [STARTS]");

            JObject uiDataResponseJson = null;
            string  uiResponse         = string.Empty;

            if (data != null)
            {
                // the partner will do their own authentication and authorization here
                // this is just a demo
                if (data["userName"] != null && data.GetValue("userName").ToString() == "*****@*****.**" && data["password"] != null && data.GetValue("password").ToString() == "Elli3M@e")
                {
                    if (MockResponseHelper.GetUIDataResponse() != null)
                    {
                        uiDataResponseJson = MockResponseHelper.GetUIDataResponse();

                        // Sanitizing the response payload here for any html or script tags and escaping them.
                        var settings = new JsonSerializerSettings()
                        {
                            StringEscapeHandling = StringEscapeHandling.EscapeHtml
                        };

                        uiResponse = JsonConvert.SerializeObject(uiDataResponseJson, settings);
                    }
                }
            }

            _Logger.LogInformation("[UIController] - POST - api/ui - [ENDS]");

            return(uiResponse);
        }
        public void Post([FromBody] JObject data)
        {
            _Logger.LogInformation("[" + _ClassName + "] - POST - api/webhook - [STARTS]");

            // Checking if the request payload is null
            if (data != null)
            {
                _Logger.LogInformation("[" + _ClassName + "]  - POST - api/webhook -  Received Webhook Notification at ");

                var webhookSecret      = _AppSettings.WebhookSecret;
                var requestSignature   = Request.Headers["Elli-Signature"].ToString();
                var requestEnvironment = Request.Headers["Elli-Environment"].ToString();

                _Logger.LogInformation("[" + _ClassName + "] - POST - api/webhook - Request Elli-Signature - " + requestSignature);
                _Logger.LogInformation("[" + _ClassName + "] - POST - api/webhook - Request Elli-Environment - " + requestEnvironment);

                // generate the webhook token from the payload and secret using HMACSHA
                var webHookToken = WebHookHelper.GetWebhookNotificationToken(data.ToString(Formatting.None), webhookSecret);

                _Logger.LogInformation("[" + _ClassName + "] - POST - api/webhook - WebHook Data - " + data.ToString(Formatting.Indented));
                _Logger.LogInformation("[" + _ClassName + "] - POST - api/webhook - WebHook Token - " + webHookToken);

                // Check if the generated WebHook token is similar to the request signature received in the header.
                if (WebHookHelper.IsValidWebhookToken(requestSignature, webHookToken))
                {
                    var webHookBody = new WebhookNotificationBody()
                    {
                        eventId   = data.GetValue <string>("eventId"),
                        eventTime = data.GetValue <DateTime>("eventTime"),
                        eventType = data.GetValue <string>("eventType"),
                        meta      = data.GetValue <Meta>("meta")
                    };

                    var transactionId = webHookBody.meta != null ? webHookBody.meta.resourceId : string.Empty;

                    _Logger.LogInformation("[" + _ClassName + "] - POST - api/webhook - Transaction ID - " + transactionId);

                    var partnerAPIWrapper = new PartnerAPIWrapper(this._AppSettings);

                    // executing the Get Request Partner API Call here
                    var requestData = partnerAPIWrapper.GetRequest(transactionId);

                    if (requestData != null)
                    {
                        _Logger.LogInformation("[" + _ClassName + "] - POST - api/webhook - Get Request Data is not null ");

                        var loanInformation = requestData;

                        // if the requestData is not null then the Partner will validate it against their business rules and if it is valid then they have to build their request here and submit it
                        // the response that they receive from their request will go back into the Partner API as a CreateResponse Partner API call

                        var validationInfo = MockResponseHelper.ValidateLoanData(requestData);

                        if (validationInfo != null && validationInfo["success"] != null)
                        {
                            var response = MockRequestHelper.SubmitToPartner(requestData, transactionId);

                            // This method will build the payload required for Creating Response in the Partner API
                            SubmitAcknowledgementToPartnerAPI(response, loanInformation, transactionId);
                        }
                        else
                        {
                            TransactionStatusCache.Instance.Add(transactionId, validationInfo);
                        }
                    }
                }
                else
                {
                    _Logger.LogInformation("[" + _ClassName + "] - POST - api/webhook - WebHook Token is Invalid ");
                }
            }

            _Logger.LogInformation("[" + _ClassName + "] - POST - api/webhook - [ENDS]");
        }
        /// <summary>
        /// This method will be called when the order is fulfilled on the partners end.
        /// it will do a POST Response to Partner API
        /// </summary>
        /// <param name="response"></param>
        /// <param name="transactionId"></param>
        private void SubmitResponseToPartnerAPI(JObject response, string transactionId)
        {
            try
            {
                _Logger.LogInformation("[ResponseController] - SubmitResponseToPartnerAPI - Inside Method - ");

                // Getting the relevant Loan Information for the given Transaction
                var transactionLoanInformation = TransactionInformationCache.Instance.GetValue(transactionId);

                if (response != null)
                {
                    _Logger.LogInformation("[ResponseController] - SubmitResponseToPartnerAPI - response is not null - ");

                    if (transactionLoanInformation != null && response.SelectToken("status").ToString() == "Completed" && response.SelectToken("$.result") != null)
                    {
                        _Logger.LogInformation("[ResponseController] - SubmitResponseToPartnerAPI - TransactionLoanInformation is not null - ");

                        // build payload for Partner API Create Response
                        dynamic responsePayload = new JObject();

                        dynamic loanObject = new JObject();

                        loanObject.VaLoanData         = MockResponseHelper.GetVALoanData();
                        loanObject.UnderwriterSummary = MockResponseHelper.GetUnderWritterSummaryData();
                        loanObject.Uldd            = MockResponseHelper.GetUIDData();
                        loanObject.Tsum            = MockResponseHelper.GetTSumData();
                        loanObject.Property        = MockResponseHelper.GetPropertyData();
                        loanObject.HudLoanData     = MockResponseHelper.GetHUDLoanData();
                        loanObject.Hmda            = MockResponseHelper.GetHMDAData();
                        loanObject.Fees            = MockResponseHelper.GetLoanFeesData();
                        loanObject.Contacts        = MockResponseHelper.GetLoanContactsData();
                        loanObject.CommitmentTerms = MockResponseHelper.GetCommitmentTermsData();
                        loanObject.ClosingDocument = MockResponseHelper.GetClosingDocumentData();
                        loanObject.PropertyAppraisedValueAmount = 566000;

                        dynamic orders = new JArray();
                        dynamic order  = new JObject();

                        var result = response.SelectToken("$.result");

                        if (result != null)
                        {
                            order.id            = result["trackingId"];
                            order.orderDateTime = result["orderDate"];
                            order.orderStatus   = response["status"];
                            order.orderMessage  = result["orderMessage"];
                        }

                        order.product   = transactionLoanInformation.ProductName;
                        order.documents = GetDocumentsFromResponse(response, transactionId);

                        orders.Add(order);

                        responsePayload.LoanData = loanObject;
                        responsePayload.orders   = orders;

                        var partnerAPIWrapper = new PartnerAPIWrapper(this._AppSettings);
                        partnerAPIWrapper.CreateResponse(responsePayload.ToString(Formatting.None), transactionId);

                        _Logger.LogInformation("[ResponseController] - SubmitResponseToPartnerAPI - before adding response to TransactionStatus cache - ");
                        TransactionStatusCache.Instance.Add(transactionId, response);
                        _Logger.LogInformation("[ResponseController] - SubmitResponseToPartnerAPI - After adding response to TransactionStatus cache - ");
                    }
                }
            }
            catch (Exception ex)
            {
                _Logger.LogError("[ResponseController] - SubmitResponseToPartnerAPI - Exception - " + ex.Message);
            }
        }
        public IActionResult Post(string transactionId, string orderId)
        {
            JObject status = new JObject();

            try
            {
                _Logger.LogInformation("[StatusController] - POST - api/status - [STARTS]");

                // partner will check their systems/repository to check the status of the current order and return the documents if it is completed.
                var mockResponseHelper  = new MockResponseHelper(_AppSettings);
                var checkStatusResponse = mockResponseHelper.GetResponseForCheckStatus(transactionId, orderId);

                if (checkStatusResponse != null)
                {
                    var partnerAPIWrapper = new PartnerAPIWrapper(this._AppSettings);
                    var responseString    = Convert.ToString(checkStatusResponse);

                    // This is the POST call to the Partner API (Create Response call) | partner/v1/transactions/{{transactionId}}/response
                    var isResponseCreated = partnerAPIWrapper.CreateResponse(responseString, transactionId);

                    if (isResponseCreated)
                    {
                        _Logger.LogInformation("[StatusController] - POST - api/status - Response was created.");

                        // building success response for UI
                        var result    = new JObject();
                        var orderDate = DateTime.Now;

                        status.Add("status", checkStatusResponse["status"]);
                        result.Add("trackingId", orderId);
                        result.Add("orderDate", orderDate.ToString("yyyy-MM-ddTHH:mm-ss:ff"));
                        result.Add("orderMessage", "Order has been completed successfully.");

                        status.Add("result", result);

                        // updating the transaction status in the memory cache so that the status check polling method on the UI gets the updated status of the transaction.
                        TransactionStatusCache.Instance.Add(transactionId, status);
                    }
                    else
                    {
                        _Logger.LogInformation("[StatusController] - POST - api/status - Response was not Created. isResponseCreate flag is false.");

                        // return Internal Server Error
                        return(StatusCode(500));
                    }
                }
                else
                {
                    _Logger.LogInformation("[StatusController] - POST - api/status - checkStatusResponse is null.");

                    // return Internal Server Error
                    return(StatusCode(500));
                }
            }
            catch (Exception ex)
            {
                _Logger.LogError("[StatusController] - POST - Error - " + ex.Message);
                return(StatusCode(500));
            }

            _Logger.LogInformation("[StatusController] - POST - api/status - [ENDS]");
            return(Ok(status));
        }
Example #5
0
        /// <summary>
        /// This method will process the webhook request
        /// </summary>
        public void ProcessWebhookRequest()
        {
            var transactionId     = this._WebhookBody.meta != null ? _WebhookBody.meta.resourceId : string.Empty;
            var partnerAPIWrapper = new PartnerAPIWrapper(this._AppSettings);

            _Logger.LogInformation("[" + _ClassName + "] - POST - api/webhook - Transaction ID - " + transactionId);

            // This is for the Transaction messaging flow. if the eventType is NewMessage then the Lender has sent a message to the Partner and the partner has to retreive it
            if (_WebhookBody.eventType == "NewMessage")
            {
                //Dump message body into cache.

                var resourceRefURL = _WebhookBody.meta.resourceRef;
                var messageId      = resourceRefURL.Substring(resourceRefURL.LastIndexOf('/') + 1, resourceRefURL.Length - resourceRefURL.LastIndexOf('/') - 1);

                var messageBody = partnerAPIWrapper.GetMessage(transactionId, messageId);
                if (messageBody != null)
                {
                    _Logger.LogInformation("[" + _ClassName + "] - POST - api/webhook - Message is not null ");
                    MessageCache.Instance.Add(transactionId, messageBody.ToString());
                }
            }
            else if (_WebhookBody.eventType == "CreateRequest")
            {
                // executing the Get Request Partner API Call here
                var requestData = partnerAPIWrapper.GetRequest(transactionId);

                if (requestData != null)
                {
                    _Logger.LogInformation("[" + _ClassName + "] - POST - api/webhook - Get Request Data is not null ");

                    var loanInformation = requestData;

                    // if the requestData is not null then the Partner will validate it against their business rules and if it is valid then they have to build their request here and submit it
                    // the response that they receive from their request will go back into the Partner API as a CreateResponse Partner API call

                    var mockResponseHelper = new MockResponseHelper(_AppSettings);
                    var validationInfo     = mockResponseHelper.ValidateLoanData(requestData);

                    if (validationInfo != null && validationInfo["success"] != null)
                    {
                        // This will get the type of Integration (e.g. Appraisal, Flood, Verification etc.)
                        var integrationCategory = _AppSettings.IntegrationType == null ? "Appraisal" : _AppSettings.IntegrationType;

                        var response = _MockRequestHelper.SubmitToPartner(requestData, transactionId);

                        // This method will build and submit the payload required for Creating the response in EPC
                        var responseParser = new ResponseProcessor(_WebhookBody, _Logger, _AppSettings);

                        // For Data & Docs flow, validating the credentials.
                        if (string.Compare(_AppSettings.IntegrationType, "DataDocs", true) == 0)
                        {
                            // use password manager and do validation.
                            if (requestData.SelectToken("$.credentials") != null)
                            {
                                var userName = requestData.GetValueByPath <string>("$.credentials.userName");
                                var password = requestData.GetValueByPath <string>("$.credentials.password");

                                // partner will validate the credentials returned from GetRequest with their system and submit the acknowledgement. here we're validating against a mock username and password.
                                if (userName == "datadocs" && password == "#######")
                                {
                                    responseParser.SubmitAcknowledgementToEPC(response, loanInformation, "Delivered");
                                }
                                else
                                {
                                    responseParser.SubmitAcknowledgementToEPC(response, loanInformation, "Rejected"); // if the credentials are invalid or null then send Rejected status
                                }
                            }
                            else
                            {
                                responseParser.SubmitAcknowledgementToEPC(response, loanInformation, "Rejected"); // if the credentials are invalid or null then send Rejected status
                            }
                        }
                        else
                        {
                            responseParser.SubmitAcknowledgementToEPC(response, loanInformation); // This is for the other categories.
                        }
                    }
                    else
                    {
                        TransactionStatusCache.Instance.Add(transactionId, validationInfo);
                    }
                }
            }
        }