/// <summary> /// Processes a payment request, verifying payment details with the bank and returning the result of the payment request /// </summary> /// <param name="paymentDto">The DTO representing a PaymentRequestDto</param> /// <returns>A PaymentResponseDto, which contains the payment identifier and status.</returns> public PaymentResponseDto MakePayment(PaymentRequestDto paymentDto) { _logger.LogInformation("Received a Payment request for " + paymentDto.Amount.ToString() + " " + paymentDto.Currency + "."); Payment payment = _mapper.Map <Payment>(paymentDto); payment.Card = _cardService.FindOrCreateCard(payment.Card); BankPaymentRequestDto bankPaymentRequest = _mapper.Map <BankPaymentRequestDto>(payment); BankPaymentResponseDto bankPaymentResponse = _bankService.PostPayment(bankPaymentRequest); if (bankPaymentResponse.ReasonCode == -1) { _logger.LogInformation("Payment rejected by bank."); payment.Status = PaymentStatus.Failed; } else { _logger.LogInformation("Payment accepted by bank!"); payment.Status = PaymentStatus.Success; } payment.BankTransactionId = bankPaymentResponse.BankTransactionId; payment.PaymentDate = DateTime.Now; Payment newPayment = _paymentRepository.InsertPayment(payment); _logger.LogInformation("Payment successfully processed."); PaymentResponseDto newPaymentDto = _mapper.Map <PaymentResponseDto>(newPayment); return(newPaymentDto); }
public async Task <IActionResult> Post(PaymentRequestDto paymentRequest) { try { if (ModelState.IsValid) { var paymentState = await _paymentRequestService.Pay(paymentRequest); var paymentResponse = new PaymentResponseDto() { IsProcessed = paymentState.PaymentState == PaymentStateEnum.Processed , PaymentState = paymentState }; if (!paymentResponse.IsProcessed) { return(StatusCode(500, new { error = "Payment could not be processed" })); } return(Ok(paymentResponse)); } else { return(BadRequest(ModelState)); } } catch (Exception ex) { _logger.LogError(ex, ex.Message); return(StatusCode(500)); } }
public void PostAndGetPayment_ShouldAcceptAndRetrieve() { CardDto card = GenerateRandomCard(); PaymentRequestDto paymentRequest = new PaymentRequestDto(); paymentRequest.MerchantId = 1; paymentRequest.Amount = 25.99; paymentRequest.Currency = "CAD"; paymentRequest.Card = card; var postResult = _paymentsController.Post(paymentRequest); Assert.IsType <OkObjectResult>(postResult.Result); OkObjectResult objectResult = postResult.Result as OkObjectResult; Assert.IsType <PaymentResponseDto>(objectResult.Value); PaymentResponseDto paymentResponse = objectResult.Value as PaymentResponseDto; Assert.True(paymentResponse.Id > 0); Assert.NotNull(paymentResponse.Status); int paymentId = paymentResponse.Id; var getResult = _paymentsController.Get(paymentId); Assert.IsType <OkObjectResult>(getResult.Result); OkObjectResult getObjectResult = getResult.Result as OkObjectResult; Assert.IsType <PaymentInformationDto>(getObjectResult.Value); PaymentInformationDto paymentInformation = getObjectResult.Value as PaymentInformationDto; Assert.Equal(paymentRequest.Amount, paymentInformation.Amount); Assert.Equal(paymentRequest.Currency, paymentInformation.Currency); }
public PaymentResponseDto MakePayment(PaymentStripeDto input) { PaymentResponseDto results = new PaymentResponseDto(); return((PaymentResponseDto)_creditsHeroConnect.CallCreditsHeroService <PaymentResponseDto>(results, input, "api/services/app/Subscriber/MakeStripePurchase")); }
public async Task ShouldOperationSucceedWhenExistingAndValidDataProvided() { int expectedPaymentLinksCount = PaymentLinks.Count - 1; PaymentResponseDto responseDto = new PaymentResponseDto() { Id = 1921093123, Control = "1:1", Description = "Opłata rekrutacyjna 1/1/2001", Number = "M10001/1001", OperationAmount = 7, OperationCurrency = "PLN", OperationOriginalAmount = 7, OperationOriginalCurrency = "PLN", Status = OperationStatus.Completed, Type = OperationType.Payment }; SuccessfulMoneyTransferParamValidator validator = new SuccessfulMoneyTransferParamValidator(); Mock <RemovePaymentLinkInDotpayCommand> RemovePaymentLinkInDotpayCommandMock = new Mock <RemovePaymentLinkInDotpayCommand>(null, null, null, null); RemovePaymentLinkInDotpayCommandMock.Setup(c => c.Execute(It.IsAny <PaymentLink>())).ReturnsAsync(new OperationSucceded()); SuccessfulMoneyTransferCommand command = new SuccessfulMoneyTransferCommand(Logger, validator, DbContext.Object, UpdatePaymentCommand, RemovePaymentLinkCommand, AssignCandidateToExamsCommand, RemovePaymentLinkInDotpayCommandMock.Object); OperationResult result = await command.Execute(responseDto); Assert.IsTrue(result.Success); Assert.AreEqual(expectedPaymentLinksCount, PaymentLinks.Count); Assert.AreEqual(GetExams().Count, ExamTakers.Count); }
public async Task <ActionResult <PaymentResponseDto> > Process(PaymentRequestDto paymentRequestDto) { try { var paymentRequest = new PaymentRequest( paymentRequestDto.MerchantId, paymentRequestDto.CardHolderName, paymentRequestDto.CardNumber, paymentRequestDto.ExpiryDate, new Money(paymentRequestDto.Amount, paymentRequestDto.Currency), paymentRequestDto.CVV); var payment = await paymentRequestProcessor.Process(paymentRequest); var result = new PaymentResponseDto { AcquiringBankPaymentId = payment.AcquiringBankPaymentId, Status = payment.Status.ToString(), Timestamp = payment.Timestamp }; return(this.Ok(result)); } catch (Exception ex) { this.logger.LogError(ex, "Error processing payment."); } return(this.Problem("Error processing payment.")); }
public void Test01() { var expectedObject = new PaymentResponseDto(); var mapper = new PaymentResponseMapper(); var mappedObject = mapper.Map(null); mappedObject.Should().NotBeNull(); mappedObject.Should().BeEquivalentTo(expectedObject); }
public async Task <ActionResult> SuccessfulMoneyTransfer([FromQuery] PaymentResponseDto response) { OperationResult result = await Get <SuccessfulMoneyTransferCommand>().Execute(response); if (result.Success) { return(Ok("OK")); } else { return(BadRequest("Operation failed")); } }
public IPaymentResponse PaymentForm(IUser currentUser, string basketId) { var baseUrl = _configuration["Storm:BaseUrl"]; List <StormNameValue> list = new List <StormNameValue>(); list.Add(new StormNameValue() { Name = "mobile", Value = "false" }); list.Add(new StormNameValue() { Name = "termsurl", Value = baseUrl + "/terms" }); list.Add(new StormNameValue() { Name = "checkouturl", Value = baseUrl + "/Basket/Checkout" }); list.Add(new StormNameValue() { Name = "confirmationurl", Value = baseUrl + "/Basket/OrderComplete" }); string url = $"ShoppingService.svc/rest/GetPaymentForm?format=json"; url += "&basketId=" + basketId; url += "&ipAddress=" + "172.16.98.1"; url += "&userAgent=" + "unknown"; if (currentUser.PriceLists != null) { url += "&priceListSeed=" + string.Join(",", currentUser.PriceLists); } var paymentResponse = _stormConnectionManager.PostResult <StormPaymentResponse>(url, list); PaymentResponseDto dto = new PaymentResponseDto(); dto.Reference = paymentResponse.RedirectUrl; dto.Html = paymentResponse.PaymentReference; dto.FormCheckoutProvider = FORM_CHECKOUT_PROVIDER; return(dto); }
public void Setup() { bank = new Mock <IAcquiringBank>(); testBankResponse = new BankResponseDto(testId, testStatus); bank.Setup(x => x.PaymentIsApproved(It.IsAny <PaymentRequestDto>())).Returns(testBankResponse); paymentStore = new Mock <IPaymentStorage>(); paymentStore.Setup(x => x.Store(It.IsAny <int>(), It.IsAny <PaymentStorageObject>())); paymentRequestValidator = new Mock <IPaymentRequestValidator>(); paymentRequestValidator.Setup(x => x.IsValid(It.IsAny <PaymentRequestDto>())).Returns(true); sut = new PaymentController(bank.Object, paymentStore.Object, paymentRequestValidator.Object); testExpiry = DateTime.Now.AddDays(1); testPaymentRequestDto = new PaymentRequestDto(testCardNum, testExpiry, testCurrency, testAmount, testCvv); testPaymentResponse = new PaymentResponseDto(testPaymentRequestDto, testBankResponse); }
public void Test02() { var objectToMap = new PaymentResponse { PaymentId = new Guid("24b542a8-4825-4089-ace6-6c0ef8bd56a8"), IsRequestSucceeded = true }; var expectedObject = new PaymentResponseDto { PaymentId = new Guid("24b542a8-4825-4089-ace6-6c0ef8bd56a8"), IsRequestSucceeded = true }; var mapper = new PaymentResponseMapper(); var mappedObject = mapper.Map(objectToMap); mappedObject.Should().NotBeNull(); mappedObject.Should().BeEquivalentTo(expectedObject); }
// POST api/<controller> public HttpResponseMessage ProcessPayment(PaymentRequestDto request) { var result = new PaymentResponseDto(); if (request.MerchantId > 2) { return(Request.CreateResponse(HttpStatusCode.BadRequest, "Unknown Merchant")); } if (request.PaymentAmount > 99999) { return(Request.CreateResponse(HttpStatusCode.BadRequest, "Payment amount exceeds allowed amount")); } return(Request.CreateResponse(HttpStatusCode.OK, new PaymentResponseDto { PaymentIdentifier = Guid.NewGuid(), PaymentStatus = "Successful" })); }
public async Task InsertPaymentDetails(PaymentResponseDto PaymentResponseDto) { await Repository.InsertAsync(new PaymentResponse { PaymentDate = PaymentResponseDto.PaymentDate, Amount = PaymentResponseDto.Amount, Currency = PaymentResponseDto.Currency, Card = PaymentResponseDto.Card, Cardscheme = PaymentResponseDto.Cardscheme, CardType = PaymentResponseDto.CardType, PaymentStatus = PaymentResponseDto.PaymentStatus, TransactionId = PaymentResponseDto.TransactionId, TransactionType = PaymentResponseDto.TransactionType, CustomerId = PaymentResponseDto.CustomerId, PaymentCustomerId = PaymentResponseDto.PaymentCustomerId, PaymentSourceId = PaymentResponseDto.PaymentSourceId, ReturnPaymentResponse = PaymentResponseDto.ReturnPaymentResponse, OrderId = PaymentResponseDto.OrderId }); }
public void PostPayment_ShouldAccept() { CardDto card = GenerateRandomCard(); PaymentRequestDto paymentRequest = new PaymentRequestDto(); paymentRequest.MerchantId = 1; paymentRequest.Amount = 25.99; paymentRequest.Currency = "CAD"; paymentRequest.Card = card; var okResult = _paymentsController.Post(paymentRequest); Assert.IsType <OkObjectResult>(okResult.Result); OkObjectResult objectResult = okResult.Result as OkObjectResult; Assert.IsType <PaymentResponseDto>(objectResult.Value); PaymentResponseDto paymentResponse = objectResult.Value as PaymentResponseDto; Assert.True(paymentResponse.Id > 0); Assert.NotNull(paymentResponse.Status); }
public IPaymentResponse PaymentComplete(string reference) { List <StormNameValue> list = new List <StormNameValue>(); list.Add(new StormNameValue() { Name = "checkoutId", Value = reference }); list.Add(new StormNameValue() { Name = "PaymentService", Value = "KlarnaCheckoutV3" }); string url = $"ShoppingService.svc/rest/PaymentCallback?format=json"; var paymentResponse = _stormConnectionManager.PostResult <StormPaymentResponse>(url, list); PaymentResponseDto dto = new PaymentResponseDto(); dto.Html = paymentResponse.PaymentReference; dto.FormCheckoutProvider = FORM_CHECKOUT_PROVIDER; return(dto); }
public PaymentResponseDto ChargeCreditCard(PaymentDTO paymentDetails, Guid memberId, string ipAddress) { try { var memberInformation = new UserField { name = "id", value = memberId.ToString() }; var userFields = new UserFields { userField = new List <UserField> { memberInformation } }; var formSubmitted = _context.FormSubmitted.Where(form => form.MemberId == memberId).OrderByDescending(x => x.FormSubmittedId).FirstOrDefault(); var uri = new Uri("https://apitest.authorize.net/xml/v1/request.api"); paymentDetails.createTransactionRequest.merchantAuthentication.name = "3c9V4ct2FKu3"; paymentDetails.createTransactionRequest.merchantAuthentication.transactionKey = "2w78G98K7cwbRN9F"; paymentDetails.createTransactionRequest.transactionRequest.transactionType = "authCaptureTransaction"; paymentDetails.createTransactionRequest.transactionRequest.order.invoiceNumber = formSubmitted.FormId + "-" + DateTime.Now.Millisecond; paymentDetails.createTransactionRequest.transactionRequest.userFields = userFields; var parsedBody = JsonConvert.SerializeObject(paymentDetails).ToString(); var content = new StringContent(parsedBody, Encoding.UTF8, "application/json"); var request = WebRequest.Create(uri) as HttpWebRequest; var postBytes = Encoding.ASCII.GetBytes(parsedBody); request.ContentLength = postBytes.Length; request.Method = "POST"; request.ContentType = "application/json"; request.ContentLength = postBytes.Length; request.Expect = "application/json"; request.GetRequestStream().Write(postBytes, 0, postBytes.Length); var response = request.GetResponse() as HttpWebResponse; var responseObject = new PaymentResponseDto(); var streamResponse = response.GetResponseStream(); var streamReader = new StreamReader(streamResponse, Encoding.UTF8); var resp = streamReader.ReadToEnd(); var respObject = JsonConvert.DeserializeObject <PaymentResponseDto>(resp); responseObject = respObject; switch (response.StatusCode) { case HttpStatusCode.OK: switch (respObject.transactionResponse.responseCode) { case "1": using (var transaction = _context.Database.BeginTransaction()) { try { //Lets save the order var order = new Order { MemberId = memberId, OrderStatusId = 1, OrderDate = DateTime.Now, OrderTotal = decimal.Parse(paymentDetails.createTransactionRequest .transactionRequest.amount), PaymentTypeId = 1 }; _context.Order.Add(order); _context.SaveChanges(); //lets save the line items foreach (var lineItem in paymentDetails.createTransactionRequest.transactionRequest.lineItems.lineItem) { var orderItem = new OrderItem { OrderId = order.OrderId, ItemId = int.Parse(lineItem.itemId), Price = decimal.Parse(lineItem.unitPrice), Quantity = int.Parse(lineItem.quantity) }; _context.OrderItem.Add(orderItem); _context.SaveChanges(); _context.Entry(orderItem).State = EntityState.Detached; } // lets save the status of the form formSubmitted.FormSubmitedStatusId = 3; _context.SaveChanges(); // lets save the order response var orderLog = new LogOrderBilling { Amount = decimal.Parse(paymentDetails.createTransactionRequest.transactionRequest.amount), DateCreated = DateTime.Now, MessageCodes = responseObject.transactionResponse.authCode, Messages = responseObject.transactionResponse.messages[0].ToString(), Result = respObject.transactionResponse.avsResultCode.ToLower() == "y"? true: false, OrderId = order.OrderId, IpHost = ipAddress }; _context.LogOrderBilling.Add(orderLog); _context.SaveChanges(); transaction.Commit(); } catch (Exception e) { throw new Exception(e.Message); } break; } case "3": formSubmitted.FormSubmitedStatusId = 4; _context.SaveChanges(); break; } break; case HttpStatusCode.BadRequest: throw new Exception("There was an error"); } return(responseObject); } catch (Exception e) { throw new Exception(e.Message); } }
public ActionResult <PaymentResponseDto> Post([FromBody] PaymentRequestDto payment) { PaymentResponseDto result = _paymentService.MakePayment(payment); return(Ok(result)); }