Ejemplo n.º 1
0
        public async Task ProcessPaymentRequestSendResult(EservicePaymentRequest request, string jsonResult)
        {
            if (request == null)
            {
                throw new Exception("EservicePaymentRequest not found for sent status update!");
            }

            if (String.IsNullOrWhiteSpace(jsonResult))
            {
                throw new Exception("EservicePaymentRequest received empty result!");
            }

            Log.Information($"EPaymentService/ProcessPaymentRequestSendResult - jsonResult: {jsonResult}");

            object resultModel = JsonConvert.DeserializeObject(jsonResult, typeof(PaymentRequestSendResultModel));

            if (resultModel != null)
            {
                PaymentRequestSendResultModel model = resultModel as PaymentRequestSendResultModel;
                if (model.AcceptedReceipt != null && model.AcceptedReceipt.Id == request.PaymentRequest.AisPaymentId)
                {
                    DateTime timestamp = DateTime.SpecifyKind(DateTime.Now, DateTimeKind.Utc);
                    string   status    = Shared.Enums.PaymentRequestStatus.ACCEPTED.ToString();
                    request.UpdatedAt  = timestamp;
                    request.StatusCode = status;

                    _context.EservicePaymentRequest.Update(request);
                    await _context.SaveChangesAsync();

                    DateTime serviceTimestamp = DateTime.SpecifyKind(model.AcceptedReceipt.RegistrationTime, DateTimeKind.Utc);
                    await AddEServicePaymentRequestStatusHistory(request.Id, status, timestamp, serviceTimestamp, null);
                }
                else
                {
                    if (model.UnacceptedReceipt != null)
                    {
                        DateTime timestamp = DateTime.SpecifyKind(DateTime.Now, DateTimeKind.Utc);
                        string   status    = Shared.Enums.PaymentRequestStatus.REJECTED.ToString();
                        request.UpdatedAt  = timestamp;
                        request.StatusCode = status;

                        _context.EservicePaymentRequest.Update(request);
                        await _context.SaveChangesAsync();

                        DateTime serviceTimestamp = DateTime.SpecifyKind(model.UnacceptedReceipt.ValidationTime, DateTimeKind.Utc);
                        string   errors           = String.Join("; ", model.UnacceptedReceipt.Errors);
                        await AddEServicePaymentRequestStatusHistory(request.Id, status, timestamp, serviceTimestamp, errors);
                    }
                    else
                    {
                        throw new Exception("Json send result is not recognized as valid accepted/rejected model!");
                    }
                }
            }
            else
            {
                throw new Exception("Json send result is not recognized as valid model!");
            }
        }
Ejemplo n.º 2
0
        public async Task <PaymentRequestSendResultModel> SendEpaymentRequestAsync(EPaymentRequestModel dataModel)
        {
            JsonSerializerSettings settings = new JsonSerializerSettings
            {
                DateFormatHandling = DateFormatHandling.IsoDateFormat,
                NullValueHandling  = NullValueHandling.Include
            };

            string dataJson = JsonConvert.SerializeObject(dataModel, settings);

            (string data, string hmac) = ComputeBodyProps(dataJson, _settings.UseTestEnv);

            // Ако се извика услуга с несъществуващ clientId или ако при извикване на услуга калкулирания
            // от средата HMAC-SHA256 не съответства на подадения в полето hmac се връща грешка HTTP 401 Unauthorized.
            using (HttpClient client = new HttpClient())
            {
                string serviceVerison = "v1";
                string postUri        = $"api/{serviceVerison}/eService/paymentJson";
                client.BaseAddress = new Uri(_settings.UseTestEnv ? _settings.TestEnvUrl : _settings.Url);

                // Параметрите се подават в HTTPS POST заявката в Internet media type формат "application/x-www-form-urlencoded; charset=UTF-8".
                client.DefaultRequestHeaders.Accept.Clear();
                client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/x-www-form-urlencoded"));

                // Извикването на услуги на средата се извършва чрез HTTP POST заявка на адрес посочен в полето URL на услугата.
                // При всяко извикване на услуга се подават три параметъра:
                // 1.	clientId – уникален идентификатор на клиента на средата
                // 2.	hmac – hmac-sha256 код изчислен върху полето data
                // 3.	data – данни за предаваното съобщение.

                var encodedHttpBody = $"clientId={HttpUtility.UrlEncode(_settings.UseTestEnv ? _settings.TestEnvClientId : _settings.ClientId)}&hmac={HttpUtility.UrlEncode(hmac)}&data={HttpUtility.UrlEncode(data)}";
                ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(ValidateRemoteCertificate);

                var response = await client.PostAsync(postUri, new StringContent(encodedHttpBody, Encoding.UTF8, "application/x-www-form-urlencoded"));

                // При невалидна структура на документ "ЗАЯВКА ЗА ПЛАЩАНЕ" се връща грешка HTTP 400 BAD REQUEST

                PaymentRequestSendResultModel resultModel;
                if (response.IsSuccessStatusCode)
                {
                    string responseContent = await response.Content.ReadAsStringAsync();

                    resultModel = GetResultModel(responseContent);
                }
                else
                {
                    resultModel = new PaymentRequestSendResultModel();
                    string responseContent = await response.Content.ReadAsStringAsync();

                    resultModel.ErrorMessage = responseContent;
                }

                resultModel.IsSuccessStatusCode = response.IsSuccessStatusCode;
                resultModel.StatusCode          = (int)response.StatusCode;

                return(resultModel);
            }
        }
        private async Task <PaymentRequestSendResultModel> CreateTaxMeRequest(int certificateOfDistraintOfPropertyRequestId)
        {
            EServicePaymentRequestCreateModel result = await _ePaymentService.GeneratePaymentRequestAsync(Shared.Enums.EServiceType.SEIZEDPROPERTYCERTIFICATE, certificateOfDistraintOfPropertyRequestId);

            PaymentRequest request = await _context.PaymentRequest.Where(x => x.AisPaymentId == result.PaymentRequestId).SingleOrDefaultAsync();

            EPaymentRequestModel          model           = request.ToEpaymentModel();
            PaymentRequestSendResultModel sendResultModel = await _ePaymentService.SendEpaymentRequestAsync(model ?? throw new ArgumentNullException(nameof(result)));

            return(sendResultModel);
        }
Ejemplo n.º 4
0
        public async Task <IActionResult> TestPaymentRequest()
        {
            try
            {
                PaymentRequestSendResultModel result = await _ePaymentService.TestPaymentRequestAsync();

                return(Ok(result));
            }
            catch (Exception e)
            {
                string msg = e.GetInnerMostException()?.Message ?? "";
                Log.Error(e, msg);
                return(BadRequest(msg));
            }
        }
        public async Task <(bool hasToPay, PaymentRequestSendResultModel paymentRequestModel, RequestForCertificateOfDistraintOfProperty request)> CreateAsync(RequestModel model, string currentUserId)
        {
            using (var tran = _context.Database.BeginTransaction())
            {
                try
                {
                    RequestForCertificateOfDistraintOfProperty entry = await SaveRequestForCertificateOfDistraintOfProperty(model);

                    bool hasToPay = HasToPay(model, currentUserId);
                    if (!HasToPay(model, currentUserId))
                    {
                        // Не се изисква плащане. Връщаме резултат
                        return(hasToPay, paymentRequestModel : null, entry);
                    }

                    PaymentRequestSendResultModel paymentRequestModel = await CreateTaxMeRequest(entry.Id);

                    if (paymentRequestModel == null)
                    {
                        // Неуспешено изпращане на заявка за ел.плащане в системата за ел.плащане.
                        await tran.RollbackAsync();

                        return(hasToPay, paymentRequestModel, entry);
                    }

                    var eservicePaymentRequest = await _context.EservicePaymentRequest.Where(x => x.SeizedPropertyCertificateRequestId == entry.Id).FirstOrDefaultAsync();

                    if (eservicePaymentRequest != null)
                    {
                        // Запис на резултат от изпращането на заявка за ел.плащане.
                        DateTime utcNow = DateTime.UtcNow;
                        EservicePaymentRequestStatusHistory historyRecord = new EservicePaymentRequestStatusHistory
                        {
                            RequestId = eservicePaymentRequest.Id,
                            UpdatedAt = utcNow
                        };
                        eservicePaymentRequest.UpdatedAt = utcNow;

                        if (!paymentRequestModel.IsSuccessStatusCode)
                        {
                            eservicePaymentRequest.StatusCode = Shared.Enums.PaymentRequestStatus.ERROR.ToString();
                            historyRecord.StatusCode          = Shared.Enums.PaymentRequestStatus.ERROR.ToString();
                            historyRecord.Errors = paymentRequestModel.ErrorMessage;
                        }
                        else
                        {
                            if (paymentRequestModel.UnacceptedReceipt != null)
                            {
                                eservicePaymentRequest.StatusCode = Shared.Enums.PaymentRequestStatus.REJECTED.ToString();
                                historyRecord.StatusCode          = Shared.Enums.PaymentRequestStatus.REJECTED.ToString();
                                historyRecord.EserviceTime        = paymentRequestModel.UnacceptedReceipt.ValidationTime;
                            }
                            else
                            {
                                eservicePaymentRequest.StatusCode   = Shared.Enums.PaymentRequestStatus.PENDING.ToString();
                                eservicePaymentRequest.AisPaymentId = paymentRequestModel.AcceptedReceipt.Id;
                                historyRecord.StatusCode            = Shared.Enums.PaymentRequestStatus.PENDING.ToString();
                                historyRecord.EserviceTime          = paymentRequestModel.AcceptedReceipt.RegistrationTime;
                            }
                        }

                        _context.EservicePaymentRequestStatusHistory.Add(historyRecord);
                        await _context.SaveChangesAsync();
                    }

                    await tran.CommitAsync();

                    return(hasToPay, paymentRequestModel, entry);
                }
                catch (Exception e)
                {
                    await tran.RollbackAsync();

                    throw e;
                }
            }
        }