Ejemplo n.º 1
0
        public ProcessPaymentResponse ProcessPayment(ProcessPaymentRequest request)
        {
            var toReturn = new ProcessPaymentResponse
            {
                Success = true
            };

            try
            {
                var newItem = new PaymentList
                {
                    CreditCardNumber = request.CreditCardNumber,
                    CardHolder       = request.CardHolder,
                    ExpirationDate   = request.ExpirationDate,
                    Amount           = request.Amount,
                    SecurityCode     = request.SecurityCode,
                    PaymentAgent     = "Premium"
                };

                _unitOfWork.ExpensivePaymentGateway.AddExpensivePayment(newItem);
                _unitOfWork.Commit();
            }
            catch (Exception cex)
            {
                toReturn.Success = false;
                toReturn.Errors  = new List <string>
                {
                    cex.Message
                };

                toReturn.Message = cex.StackTrace;
            }

            return(toReturn);
        }
Ejemplo n.º 2
0
        public void RegisterAcuirerResponse_RegistersPaymentInformation()
        {
            var transactionId     = "transa";
            var resultCode        = "ok";
            var resultDescription = "Result";

            var aquirerResponse = new ProcessPaymentResponse
            {
                TransactionId     = transactionId,
                ResultCode        = resultCode,
                ResultDescription = resultDescription,
                IsSuccess         = true,
            };

            var payment = new Payment();

            payment.RegisterAcquirerResponse(aquirerResponse);

            payment.AcquirerResponse.Should().BeEquivalentTo(new AcquirerResponse
            {
                TransactionId     = transactionId,
                ResultCode        = resultCode,
                ResultDescription = resultDescription,
                IsSuccess         = true,
            }, opt => opt.Excluding(f => f.CreatedDate));
        }
Ejemplo n.º 3
0
        public ProcessPaymentResponse ProcessPayment(ProcessPaymentRequest processPaymentRequest)
        {
            var result = new ProcessPaymentResponse();

            result.AllowStoringCreditCardNumber = false;
            switch (_codPaymentSettings.TransactMode)
            {
            case TransactMode.Pending:
                result.NewPaymentStatus = PaymentStatus.Pending;
                break;

            case TransactMode.Authorize:
                result.NewPaymentStatus = PaymentStatus.Authorized;
                break;

            case TransactMode.AuthorizeAndCapture:
                result.NewPaymentStatus = PaymentStatus.Paid;
                break;

            default:
            {
                result.AddError("Not supported transaction type");
                return(result);
            }
            }
            return(result);
        }
Ejemplo n.º 4
0
        public void ProcessPayment()
        {
            var response = new ProcessPaymentResponse()
            {
                Approved       = "1",
                Eci            = "12f",
                Signature      = "asdokasokdas",
                Stan           = "Stan",
                Token          = "Token",
                ApprovalCode   = "123",
                DateTime       = "1212",
                ErrorMessage   = null,
                PaymentType    = "123",
                ShopId         = "REGULAR",
                TokenNumber    = "asd",
                TotalAmount    = "122",
                ShoppingCartId = "cartId",
                WSPayOrderId   = "orderId"
            };

            var service = BuildServiceWithSuccessResponse("api/services/ProcessPayment", response);

            var asyncResult = service.ProcessPaymentAsync("cartId", 15.50, "token", "tokenNumer").WaitTask();

            asyncResult.Should().BeEquivalentTo(response);

            var syncResult = service.ProcessPayment("cartId", 15.50, "token", "tokenNumer");

            syncResult.Should().BeEquivalentTo(response);
        }
Ejemplo n.º 5
0
 public Processing_Failed_At_Bank(TestFixture fixture) : base(fixture)
 {
     _request                = RequestGenerator.Generate();
     _request.MerchantId     = "FailMerchant";
     _httpResponseMessage    = HttpClient.PostAsJsonAsync("/payments", _request).Result;
     _processPaymentResponse = DeserializeJson <ProcessPaymentResponse>(_httpResponseMessage.Content.ReadAsStringAsync().Result);
 }
 public static PaymentResponse ToPaymentResponse(this ProcessPaymentResponse processPaymentResponse)
 {
     return(new PaymentResponse
     {
         PaymentId = processPaymentResponse.PaymentId,
         Status = processPaymentResponse.PaymentStatus.ToViewModels()
     });
 }
Ejemplo n.º 7
0
        /// <summary>
        /// Returns exemplary api response of bank.
        /// </summary>
        ProcessPaymentResponse IBankRequest.ProcessPayment(BankRequestPayload content)
        {
            var paymentResponse = new ProcessPaymentResponse();

            paymentResponse.PaymentId = Guid.NewGuid().ToString();
            paymentResponse.Success   = true;

            return(paymentResponse);
        }
Ejemplo n.º 8
0
 public void RegisterAcquirerResponse(ProcessPaymentResponse acquirerResponse)
 {
     AcquirerResponse = new AcquirerResponse
     {
         ResultCode        = acquirerResponse.ResultCode,
         ResultDescription = acquirerResponse.ResultDescription,
         TransactionId     = acquirerResponse.TransactionId,
         IsSuccess         = acquirerResponse.IsSuccess
     };
 }
Ejemplo n.º 9
0
        public async Task ProcessPaymentReturnsProcessPaymentResponse()
        {
            //Arrange
            var model = new ProcessPaymentRequestDto()
            {
                CardNumber      = "5500000000000004",
                CardHolder      = "Test Account",
                CardType        = CardType.MasterCard,
                ExpirationMonth = DateTime.Now.ToString("MM"),
                ExpirationYear  = DateTime.Now.AddYears(1).ToString("yy"),
                PaymentAmount   = 100.00M,
                Currency        = SupportedCurrencies.GBP,
                Cvv             = "123"
            };

            var bankingRequestDto = new BankProcessPaymentRequestDto()
            {
                CardNumber      = "5500000000000004",
                CardHolder      = "Test Account",
                CardType        = CardType.MasterCard,
                ExpirationMonth = DateTime.Now.ToString("MM"),
                ExpirationYear  = DateTime.Now.AddYears(1).ToString("yy"),
                PaymentAmount   = 100.00M,
                Currency        = SupportedCurrencies.GBP,
                Cvv             = "123"
            };

            var transactionId      = "aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa";
            var bankingResponseDto = new BankProcessPaymentResponseDto()
            {
                TransactionId = transactionId,
                PaymentStatus = PaymentStatus.Success
            };

            var guid = new Guid(transactionId);
            var processPaymentResponse = new ProcessPaymentResponse()
            {
                TransactionId = guid,
                PaymentStatus = PaymentStatus.Success
            };

            this._dtoMapper.Setup(x => x.MapProcessPaymentRequestModelToBankDto(It.IsAny <ProcessPaymentRequestDto>())).Returns(bankingRequestDto);
            this._bankingService.Setup(x => x.ProcessPayment(It.IsAny <BankProcessPaymentRequestDto>())).ReturnsAsync(bankingResponseDto);
            this._dtoMapper.Setup(x => x.MapBankApiPostResponseToDomainResponse(It.IsAny <BankProcessPaymentResponseDto>())).Returns(processPaymentResponse);

            //Act
            var result = await this._paymentProcessingService.ProcessPayment(model);

            //Assert
            Assert.IsNotNull(result);
            Assert.IsInstanceOf <ProcessPaymentResponse>(result);
            Assert.AreEqual(guid, result.TransactionId);
            Assert.AreEqual(PaymentStatus.Success, result.PaymentStatus);
        }
Ejemplo n.º 10
0
        public async Task GivenConcurrencyException_WhenExecuteIsCalled_ThenPaymentIsNotUpdated()
        {
            var apiKey     = "new api key";
            var merchantId = Guid.NewGuid();
            var merchant   = new Merchant {
                Id = merchantId
            };
            var merchantTransactionId = "tranid";
            var amount                    = 15.4m;
            var currency                  = "EUR";
            var cardNumber                = "1234";
            var expiryMonth               = 12;
            var expityYear                = 2020;
            var cvv                       = "123";
            var acquirerResultCode        = "ok";
            var acquirerResultDescription = "Result descroption";
            var acquirerTransactionId     = "transciontionId";

            var requestPaymentCommand = new RequestPaymentCommand
            {
                MerchantTransactionId = merchantTransactionId,
                ApiKey      = apiKey,
                Amount      = amount,
                Currency    = currency,
                CardNumber  = cardNumber,
                ExpiryMonth = expiryMonth,
                ExpiryYear  = expityYear,
                Cvv         = cvv
            };

            var acquirerSuccessResponse = new ProcessPaymentResponse {
                IsSuccess = true, ResultCode = acquirerResultCode, ResultDescription = acquirerResultDescription, TransactionId = acquirerTransactionId
            };

            _merchantRepository.GetByApiKey(apiKey).Returns(merchant);

            _paymentrepository.AddPayment(Arg.Is <Payment>(
                                              p => p.MerchantId.Equals(merchantId) &&
                                              p.Amount == amount &&
                                              p.Currency == currency &&
                                              p.CardDetails.CardNumber == cardNumber &&
                                              p.CardDetails.ExpiryMonth == expiryMonth &&
                                              p.CardDetails.ExpiryYear == expityYear &&
                                              p.CardDetails.Cvv == cvv))
            .Throws(new ArgumentException());


            await _handler.Handle(requestPaymentCommand, new System.Threading.CancellationToken());


            await _paymentrepository.Received(0).UpdatePayment(Arg.Any <Payment>());

            await _acquiringBank.Received(0).ProcessPayment(Arg.Any <ProcessPaymentRequest>());
        }
Ejemplo n.º 11
0
        public ProcessPaymentResponse Process(ProcessPaymentRequest request)
        {
            var response = new ProcessPaymentResponse();

            var order = _orderRepository.Get(request.OrderId);

            if (order == null)
            {
                response.Exception = new ResourceNotFoundException("Order not found.");
                return(response);
            }

            try
            {
                var paymentInfo = new PaymentInfo()
                {
                    InstantBuyKey    = request.InstantBuyKey,
                    CreditCardBrand  = (Domain.CreditCards.CreditCardBrand)request.Brand,
                    CreditCardNumber = request.Number,
                    ExpMonth         = request.ExpMonth,
                    ExpYear          = request.ExpYear,
                    HolderName       = request.HolderName,
                    SecurityCode     = request.SecurityCode,
                    Amount           = (long)order.Price,
                    SaveCreditCard   = request.SaveCreditCard ?? false
                };

                var paymentResult = _paymentService.CreateTransaction(paymentInfo);
                if (paymentResult.Success())
                {
                    order.PaymentReceived(paymentResult);
                    _unitOfWork.Commit();

                    _notificationService.SendPaymentReceived(order);
                }
                else
                {
                    order.PaymentReview();
                    _unitOfWork.Commit();

                    _notificationService.SendPaymentReview(order);
                }
            }
            catch (Exception ex)
            {
                response.Exception = ex;

                Logger.Error("Process Payment", ex);
            }

            return(response);
        }
Ejemplo n.º 12
0
        public ProcessPaymentResponse MapBankApiPostResponseToDomainResponse(BankProcessPaymentResponseDto bankResponseDto)
        {
            if (bankResponseDto == null || bankResponseDto.TransactionId == null || !Enum.IsDefined(typeof(PaymentStatus), bankResponseDto.PaymentStatus))
            {
                this._logger.LogError(Resources.Logging_DtoMapperNullInput, (typeof(BankProcessPaymentResponseDto).Name));

                throw new HttpException(HttpStatusCode.InternalServerError,
                                        Resources.ErrorCode_MappingError_BankApiToPaymentApi,
                                        Resources.ErrorMessage_MappingError_BankApiToPaymentApi);
            }

            var processPaymentResponse = new ProcessPaymentResponse()
            {
                TransactionId = new Guid(bankResponseDto.TransactionId),
                PaymentStatus = bankResponseDto.PaymentStatus
            };

            return(processPaymentResponse);
        }
Ejemplo n.º 13
0
        public ProcessPaymentResponse ProcessPayment(ProcessPaymentRequest processPaymentRequest)
        {
            if (processPaymentRequest.OrderTotal == decimal.Zero)
            {
                var result = new ProcessPaymentResponse
                {
                    NewPaymentStatus = PaymentStatus.Paid
                };
                return result;
            }

            //We should strip out any white space or dash in the CC number entered.
            if (!string.IsNullOrWhiteSpace(processPaymentRequest.CreditCardNumber))
            {
                processPaymentRequest.CreditCardNumber = processPaymentRequest.CreditCardNumber.Replace(" ", "");
                processPaymentRequest.CreditCardNumber = processPaymentRequest.CreditCardNumber.Replace("-", "");
            }
            var paymentMethod = GetPaymentMethodByKey(processPaymentRequest.PaymentMethodName);
            return paymentMethod.ProcessPayment(processPaymentRequest);
        }
Ejemplo n.º 14
0
        public ProcessPaymentResponse ProcessPayment(ProcessPaymentRequest processPaymentRequest)
        {
            if (processPaymentRequest.OrderTotal == decimal.Zero)
            {
                var result = new ProcessPaymentResponse
                {
                    NewPaymentStatus = PaymentStatus.Paid
                };
                return(result);
            }

            //We should strip out any white space or dash in the CC number entered.
            if (!string.IsNullOrWhiteSpace(processPaymentRequest.CreditCardNumber))
            {
                processPaymentRequest.CreditCardNumber = processPaymentRequest.CreditCardNumber.Replace(" ", "");
                processPaymentRequest.CreditCardNumber = processPaymentRequest.CreditCardNumber.Replace("-", "");
            }
            var paymentMethod = GetPaymentMethodByKey(processPaymentRequest.PaymentMethodName);

            return(paymentMethod.ProcessPayment(processPaymentRequest));
        }
        public async Task ProcessPaymentShouldReturn200()
        {
            //Arrange
            var model           = new ProcessPaymentRequestDto();
            var guid            = new Guid();
            var serviceResponse = new ProcessPaymentResponse()
            {
                TransactionId = guid,
                PaymentStatus = PaymentStatus.Success
            };

            this._paymentProcessingService.Setup(x => x.ProcessPayment(It.IsAny <ProcessPaymentRequestDto>()))
            .ReturnsAsync(serviceResponse);

            //Act
            var result = await this._controller.ProcessPayment(model);

            //Assert
            Assert.IsNotNull(result);
            Assert.IsInstanceOf <OkObjectResult>(result);

            var resultAsOkObject = result as OkObjectResult;

            Assert.IsTrue(resultAsOkObject.StatusCode == 200);
            Assert.IsNotNull(resultAsOkObject.Value);
            Assert.IsInstanceOf <ResponseBaseDto>(resultAsOkObject.Value);

            var resultValue = resultAsOkObject.Value as ResponseBaseDto;

            Assert.IsTrue(resultValue.StatusCode == HttpStatusCode.OK);
            Assert.IsNotNull(resultValue.Data);
            Assert.IsInstanceOf <ProcessPaymentResponse>(resultValue.Data);

            var resultData = resultValue.Data as ProcessPaymentResponse;

            Assert.AreEqual(guid, resultData.TransactionId);
            Assert.AreEqual(PaymentStatus.Success, resultData.PaymentStatus);
        }
Ejemplo n.º 16
0
 public Processing_Succeeded(TestFixture fixture) : base(fixture)
 {
     _request                = RequestGenerator.Generate();
     _httpResponseMessage    = HttpClient.PostAsJsonAsync("/payments", _request).Result;
     _processPaymentResponse = DeserializeJson <ProcessPaymentResponse>(_httpResponseMessage.Content.ReadAsStringAsync().Result);
 }
Ejemplo n.º 17
0
 public ProcessPaymentResponseBuilder Create()
 {
     _response = new ProcessPaymentResponse();
     return(this);
 }
        public ProcessPaymentResponse ProcessPayment(ProcessPaymentRequest request)
        {
            var toReturn = new ProcessPaymentResponse
            {
                Success = true
            };
            var result = new List <ValidationResult>();

            try
            {
                var newItem = new PaymentList
                {
                    CreditCardNumber = request.CreditCardNumber,
                    CardHolder       = request.CardHolder,
                    ExpirationDate   = request.ExpirationDate,
                    Amount           = request.Amount,
                    SecurityCode     = request.SecurityCode,
                    PaymentAgent     = "Cheap"
                };
                int retry = 0;

                #region contract validation
                var validationContext = new ValidationContext(request, null, null);
                var isValid           = Validator.TryValidateObject(request, validationContext, result, true);

                #endregion

                if (isValid)
                {
                    var writeResults = false;

                    if (newItem.Amount < 20)
                    {
                        writeResults = WritePayment(newItem, GatewayType.Cheap);
                        if (!writeResults)
                        {
                            throw new CustomException("Unavailable gateway");
                        }
                    }

                    if (newItem.Amount > 20 && newItem.Amount <= 500)
                    {
                        writeResults = WritePayment(newItem, GatewayType.Expensive);
                        if (!writeResults)
                        {
                            writeResults = WritePayment(newItem, GatewayType.Cheap);
                        }

                        if (!writeResults)
                        {
                            throw new CustomException("Unavailable gateway");
                        }
                    }

                    if (newItem.Amount > 500)
                    {
                        PremiumPaymentService premiumPaymentService = new PremiumPaymentService(_factory);

                        #region try 3 times
                        retry = 0;
                        while (retry++ < 3)
                        {
                            try
                            {
                                var premiumPayment = premiumPaymentService.ProcessPayment(request);
                                if (premiumPayment.Success)
                                {
                                    break;
                                }
                            }
                            catch (Exception ex)
                            {
                                if (retry == 3)
                                {
                                    writeResults = WritePayment(newItem, GatewayType.Cheap);
                                    if (!writeResults)
                                    {
                                        throw new CustomException("Unavailable gateway");
                                    }
                                }
                            }
                        }
                        #endregion
                    }
                }
                else
                {
                    throw new CustomException("Invalid contract");
                }
            }
            catch (CustomException cex)
            {
                toReturn.Success = false;
                toReturn.Errors  = new List <string>();

                if (cex.ShortText == "Invalid contract")
                {
                    foreach (var str in result)
                    {
                        toReturn.Errors.Add(str.ErrorMessage.ToString());
                    }
                }

                toReturn.Errors.Add(cex.ShortText);
            }
            catch (Exception ex)
            {
                toReturn.Success = false;
                toReturn.Errors  = new List <string>();
                toReturn.Errors.Add(ex.ToString());
            }
            return(toReturn);
        }
Ejemplo n.º 19
0
        public ProcessPaymentResponse ProcessPayment(ProcessPaymentRequest processPaymentRequest)
        {
            var result = new ProcessPaymentResponse();

            result.AllowStoringCreditCardNumber = false;
            switch (_codPaymentSettings.TransactMode)
            {
                case TransactMode.Pending:
                    result.NewPaymentStatus = PaymentStatus.Pending;
                    break;
                case TransactMode.Authorize:
                    result.NewPaymentStatus = PaymentStatus.Authorized;
                    break;
                case TransactMode.AuthorizeAndCapture:
                    result.NewPaymentStatus = PaymentStatus.Paid;
                    break;
                default:
                    {
                        result.AddError("Not supported transaction type");
                        return result;
                    }
            }
            return result;
        }