コード例 #1
0
        public async Task InvokeAsync(HttpContext context)
        {
            if (!context.Request.Path.Value.StartsWith("/api/"))
            {
                await _next(context);
            }
            else
            {
                var logId = Guid.NewGuid().ToString();
                var sign  = context.Request.Headers[GlobalConstants.SignHeader];
                var auth  = context.Request.Headers[GlobalConstants.AuthHeader];
                _logger.LogInformation($"REQUEST - [{logId}] auth - [{MaskHelper.MaskHeader(auth)}] sign - [{MaskHelper.MaskHeader(sign)}] body - [{MaskHelper.MaskApiRequest(HttpContextHelper.GetBody(context.Request))}]");

                string responseContent;

                var originalBodyStream = context.Response.Body;
                await using (var fakeResponseBody = new MemoryStream())
                {
                    context.Response.Body = fakeResponseBody;

                    await _next(context);

                    fakeResponseBody.Seek(0, SeekOrigin.Begin);
                    using var reader = new StreamReader(fakeResponseBody);
                    responseContent  = await reader.ReadToEndAsync();

                    fakeResponseBody.Seek(0, SeekOrigin.Begin);

                    await fakeResponseBody.CopyToAsync(originalBodyStream);
                }

                _logger.LogInformation($"RESPONSE -[{logId}] body - [{responseContent}]");
            }
        }
コード例 #2
0
        public void ItCanUnmaskSlice()
        {
            sbyte[] payload = Converter.ToTrits(
                "AAMESSAGEFORYOU9AMESSAGEFORYOU9AMESSAGEFORYOU9AMESSAGEFORYOU9AMESSAGEFORYOU9AMESSAGEFORYOU9AMESSAGEFORYOU9AMESSAGEFORYOU9AMESSAGEFORYOU9AMESSAGEFORYOU9AMESSAGEFORYOU9AMESSAGEFORYOU9AMESSAGEFORYOU9AMESSAGEFORYOU9AMESSAGEFORYOU9AMESSAGEFORYOU9AMESSAGEFORYOU9AMESSAGEFORYOU9AMESSAGEFORYOU9AMESSAGEFORYOU9MESSAGEFORYOU9");
            ICurl curl = new Curl(SpongeFactory.Mode.CURLP27);

            sbyte[] cipher = new sbyte[payload.Length];
            Array.Copy(payload, cipher, payload.Length);

            MaskHelper.MaskSlice(cipher, curl);
            curl.Reset();
            MaskHelper.UnMaskSlice(cipher, curl);

            Assert.AreEqual(Converter.ToTrytes(cipher), Converter.ToTrytes(payload));
        }
コード例 #3
0
        public async Task <PaymentResponseModel> ProcessAsync(PaymentRequestModel request, MerchantModel merchant)
        {
            _paymentRequestModelValidator.ValidateAndThrow(request);
            _merchantModelValidator.ValidateAndThrow(merchant);

            var merchantAcquirer = await _merchantAcquirerRepository.GetByMerchantIdAsync(merchant.Id);

            if (merchantAcquirer == null)
            {
                throw new GatewayException($"No acquirer setup for merchant '{ merchant.Name }'.");
            }

            // Get the appropriate processor from the AcquirerName.
            var enumAsString = (ProcessorList)Enum.Parse(typeof(ProcessorList), merchantAcquirer.AcquirerName);

            _processor = _processors[enumAsString];

            // Create and insert payment details
            var payment = BuildPaymentEntity(request, merchantAcquirer);
            await _paymentRepository.InsertAsync(payment);

            // Create processor request
            var processorRequest = new ProcessorRequest
            {
                PaymentId       = payment.PaymentId.ToString(),
                PaymentDetails  = _mapper.Map <PaymentDetails>(request),
                AcquirerDetails = _mapper.Map <AcquirerDetails>(merchantAcquirer)
            };

            var processorResponse = await _processor.ProcessPaymentAsync(processorRequest);

            var responseCodeMapping = await _acquirerResponseCodeMappingRepository.GetByAcquirerResponseCodeAsync(processorResponse.AcquirerResponseCode);

            var response = _mapper.Map <PaymentResponseModel>(processorResponse);

            response.TrackId      = request.TrackId;
            response.ResponseCode = responseCodeMapping?.GatewayResponseCode ?? Constants.FailResponseCode;
            response.Status       = response.ResponseCode.Equals(Constants.SuccessResponseCode) ? Constants.SuccessStatus : Constants.FailStatus;
            response.Card.Number  = MaskHelper.MaskCardNumber(response.Card.Number);

            // Map response details to the payment and update data store
            _mapper.Map(response, payment);
            await _paymentRepository.UpdateAsync(payment);

            return(response);
        }
コード例 #4
0
ファイル: BankService.cs プロジェクト: wl0akh/PaymentGateway
        /// <summary>
        /// PayOutAsync method pay the payment
        /// </summary>
        /// <param name="payment"></param>
        /// <returns>BankPayOutResponse</returns>
        public async Task <BankPayOutResponse> PayOutAsync(Payment payment)
        {
            var request = new HttpRequestMessage(HttpMethod.Post, this._url);

            request.Content = new StringContent(
                JsonConvert.SerializeObject(payment),
                Encoding.UTF8,
                "application/json"
                );

            var client = _clientFactory.CreateClient();

            try
            {
                var response = await client.SendAsync(request);

                var body = await response.Content.ReadAsStringAsync();

                var bankResponse = JsonConvert.DeserializeObject <BankPayOutResponse>(body);
                this._logger.LogInformation($@"RequestId:{this._requestTrackingService.RequestTraceId} 
                    Bank Payout finished with status:{bankResponse.PaymentStatus}
                    for Card ending: {MaskHelper.Mask(payment.CardNumber)}");

                return(bankResponse);
            }
            catch (JsonException jsonException)
            {
                this._logger.LogError(jsonException, $@"RequestId:{this._requestTrackingService.RequestTraceId} 
                Bank Service Incompatible");

                throw new BankServiceException("Bank Service Incompatible", jsonException)
                      {
                          RequestTraceId = Guid.NewGuid().ToString()
                      };
            }
            catch (HttpRequestException httpRequestException)
            {
                this._logger.LogError(httpRequestException, $@"RequestId:{this._requestTrackingService.RequestTraceId} 
                Bank Service Unavailable");

                throw new BankServiceException("Bank Service Unavailable", httpRequestException)
                      {
                          RequestTraceId = Guid.NewGuid().ToString()
                      };
            }
        }
コード例 #5
0
        public void ItCanUnmask()
        {
            sbyte[] payload = Converter.ToTrits(
                "AAMESSAGEFORYOU9AMESSAGEFORYOU9AMESSAGEFORYOU9AMESSAGEFORYOU9AMESSAGEFORYOU9AMESSAGEFORYOU9AMESSAGEFORYOU9AMESSAGEFORYOU9AMESSAGEFORYOU9AMESSAGEFORYOU9AMESSAGEFORYOU9AMESSAGEFORYOU9AMESSAGEFORYOU9AMESSAGEFORYOU9AMESSAGEFORYOU9AMESSAGEFORYOU9AMESSAGEFORYOU9AMESSAGEFORYOU9AMESSAGEFORYOU9AMESSAGEFORYOU9MESSAGEFORYOU9");
            sbyte[] keys = Converter.ToTrits("MYMERKLEROOTHASH");

            //int index = 5;
            ICurl curl = new Curl(SpongeFactory.Mode.CURLP27);

            //add_assign(&mut keys, index as isize);
            sbyte[] cipher = new sbyte[payload.Length];
            Array.Copy(payload, cipher, payload.Length);

            MaskHelper.Mask(cipher, keys, curl);
            curl.Reset();
            MaskHelper.UnMask(cipher, keys, curl);

            Assert.AreEqual(Converter.ToTrytes(cipher), Converter.ToTrytes(payload));
        }
コード例 #6
0
        public async Task <PaymentResponseModel> GetByIdAsync(Guid paymentId, MerchantModel merchant)
        {
            Guard.IsNotNull(paymentId, nameof(paymentId));
            _merchantModelValidator.ValidateAndThrow(merchant);

            var payment = await _paymentRepository.GetByIdAsync(paymentId);

            if (payment == null)
            {
                throw new ObjectNotFoundException($"No payment with id '{ paymentId } was found.'");
            }

            // This check should normally return a Not Found exception for security purposes. Unauthorized used for testing purposes only.
            if (payment.MerchantId != merchant.Id)
            {
                throw new UnauthorizedException($"Merchant is not authorised to retrieve this payment.");
            }

            var response = _mapper.Map <PaymentResponseModel>(payment);

            response.Card.Number = MaskHelper.MaskCardNumber(_cryptor.Decrypt(response.Card.Number));

            return(response);
        }
コード例 #7
0
 private string Prepare(string num)
 {
     return(MaskHelper.RemoveMask(num));
 }
コード例 #8
0
        protected override ValidationResult IsValid(object value, ValidationContext validationContext)
        {
            var stringValue = (string)value;

            return(!string.IsNullOrEmpty(stringValue) && PanRegex.IsMatch(stringValue) ? ValidationResult.Success : new ValidationResult($"Invalid PAN-[{MaskHelper.MaskPan(stringValue)}]"));
        }
コード例 #9
0
        public void MaskValidLengthTest(string cardnumber, string masked)
        {
            var result = MaskHelper.Mask(cardnumber);

            Assert.AreEqual(masked, result);
        }
コード例 #10
0
        private ProceedStatus InnerSimpleOperation(Merchant merchant, Session session, PaymentData paymentData, OperationType operationType, long amount)
        {
            var actualAmount  = amount != 0 ? amount : session.Amount;
            var operationList = _dbContext.Operation.OrderByDescending(x => x.Id).Where(x => x.SessionId == session.Id).ToList();

            if (operationList.Count == 0 && session.ExpireTime < DateTime.Now)
            {
                return new ProceedStatus {
                           InnerError = InnerError.SessionExpired
                }
            }
            ;
            var lastOperation = operationList.OrderByDescending(x => x.Id)
                                .FirstOrDefault(x => x.OperationStatus == OperationStatus.Success);

            CheckPossibility(session, operationList, operationType, actualAmount);
            var terminal = _terminalSelector.Select(merchant, operationList, operationType, amount);

            var processing = _processingFactory.GetProcessing(terminal.Id, _dbContext);

            var operation = new Operation
            {
                SessionId       = session.Id,
                OperationStatus = OperationStatus.Created,
                TerminalId      = terminal.Id,
                Amount          = actualAmount,
                InvolvedAmount  = 0,
                ExternalId      = IdHelper.GetOperationId(),
                OperationType   = operationType,
                CreateDate      = DateTime.UtcNow,
                ExpireMonth     = paymentData?.ExpireMonth ?? lastOperation?.ExpireMonth,
                ExpireYear      = paymentData?.ExpireYear ?? lastOperation?.ExpireYear,
                MaskedPan       = paymentData != null?MaskHelper.MaskPan(paymentData.Pan) : lastOperation?.MaskedPan
            };

            _dbContext.Operation.Add(operation);
            _dbContext.SaveChanges();
            ProceedStatus response;

            try
            {
                IProcessingResponse processingResponse;

                switch (operationType)
                {
                case OperationType.Credit:
                    if (!processing.Properties.AllowCredit)
                    {
                        throw new OuterException(InnerError.OperationNotSupportedByProcessing);
                    }
                    processingResponse = processing.Credit(session, operation, terminal, paymentData);
                    break;

                case OperationType.Deposit:
                    if (!processing.Properties.AllowDebit)
                    {
                        throw new OuterException(InnerError.OperationNotSupportedByProcessing);
                    }
                    processingResponse = processing.Debit(session, operation, terminal, paymentData);
                    break;

                case OperationType.Hold:
                    if (!processing.Properties.AllowHold)
                    {
                        throw new OuterException(InnerError.OperationNotSupportedByProcessing);
                    }
                    processingResponse = processing.Hold(session, operation, terminal, paymentData);
                    break;

                case OperationType.Charge:
                    if (!processing.Properties.AllowHold || actualAmount != session.Amount && !processing.Properties.AllowPartialCharge)
                    {
                        throw new OuterException(InnerError.OperationNotSupportedByProcessing);
                    }
                    processingResponse = processing.Charge(session, operation, terminal);
                    break;

                default:
                    throw new OuterException(InnerError.NotImplemented);
                }

                operation.ProcessingOrderId = processingResponse.ProcessingOrderId;
                operation.OperationStatus   = processingResponse.Status;
                AdditionalAuth auth = null;
                switch (processingResponse.Status)
                {
                case OperationStatus.Success:
                    operation.InvolvedAmount = operation.Amount;
                    break;

                case OperationStatus.AdditionalAuth:
                    auth = processingResponse.AuthData;
                    var operation3ds = new Operation3ds
                    {
                        LocalMd         = IdHelper.GetMd(),
                        OperationId     = operation.Id,
                        RemoteMd        = auth.Md,
                        SaveCredentials = processingResponse.SavePaymentData
                    };
                    _dbContext.Add(operation3ds);
                    auth.Md = operation3ds.LocalMd;
                    if (operation3ds.SaveCredentials)
                    {
                        _remoteContainer.Set(operation3ds.LocalMd, paymentData);
                    }
                    break;
                }
                response = new ProceedStatus {
                    OperationStatus = operation.OperationStatus, AdditionalAuth = auth
                };
            }
            catch (Exception exc)
            {
                _logger.LogError(exc.Message);
                operation.OperationStatus = OperationStatus.Error;
                response = new ProceedStatus {
                    OperationStatus = OperationStatus.Error
                };
            }
            finally
            {
                _dbContext.SaveChanges();
            }
            return(response);
        }