public async Task <Result> Handle(RequestPaymentCommand command, CancellationToken cancellationToken) { var merchant = await _merchantRepository.GetByApiKey(command.ApiKey); var payment = BuildPayment(merchant, command); try { await _paymentRequestRepository.AddPayment(payment); } catch (ArgumentException ex) { //Concurrency exception, transaction already processed (or in progress) for that merchant _logger.LogInformation($"Concurrency exception registering payment for Transaction: {command.MerchantTransactionId}, Merchant: {merchant.Code}. ex: {ex}"); return(Result.Empty()); } var acquirerResponse = await _acquiringBank.ProcessPayment(BuildAcquirerRequest(command)); payment.RegisterAcquirerResponse(acquirerResponse); await _paymentRequestRepository.UpdatePayment(payment); return(Result.Empty()); }
public async Task <ResponseMessage> AuthorizePayment(PaymentInfo payment) { var transaction = await _paymentFacade.AuthorizePayment(payment); var validationResult = new ValidationResult(); if (transaction.Status != StatusTransaction.Authorized) { validationResult.Errors.Add(new ValidationFailure("Payment", "Payment declined, contact your card operator")); return(new ResponseMessage(validationResult)); } payment.AddTransaction(transaction); _paymentRepository.AddPayment(payment); if (!await _paymentRepository.UnitOfWork.Commit()) { validationResult.Errors.Add(new ValidationFailure("Payment", "There was an error making the payment.")); return(new ResponseMessage(validationResult)); } return(new ResponseMessage(validationResult)); }
/// <inheritdoc /> public async Task <CreatePaymentResponse> CreatePayment(CreatePaymentRequest request) { var remoteCreatePaymentRequest = new AcquiringBank.Client.Models.CreatePaymentRequest( request.CardNumber, request.CardHolderName, request.ExpiryMonthYear, request.Amount, request.CurrencyCode, request.CardVerificationValue); var remoteCreatePaymentResult = await _acquiringBankClient.CreatePayment( remoteCreatePaymentRequest); await _paymentRepository.AddPayment(new Payment { PaymentId = remoteCreatePaymentResult.PaymentId, CardHolderName = request.CardHolderName, CurrencyCode = request.CurrencyCode, Status = Enum.Parse <PaymentStatus>(remoteCreatePaymentResult.PaymentStatus.ToString()), Amount = request.Amount, ExpiryMonthYear = request.ExpiryMonthYear, LastFourDigitsOfCard = request.CardNumber.Substring(request.CardNumber.Length - 4) }); return(new CreatePaymentResponse(remoteCreatePaymentResult.PaymentId, Enum.Parse <Dtos.PaymentStatus>(remoteCreatePaymentResult.PaymentStatus.ToString()))); }
public async Task AddPayment(Payment payment) { var newPayment = _mapper.Map <Model.Payment>(payment); await Task.Run(() => { _paymentRepository.AddPayment(newPayment); _paymentRepository.Save(); var order = _orderRepository.GetOrderByOrderId(payment.OrderId); order.Payments.Add(newPayment); _orderRepository.AddPayment(newPayment); _orderRepository.Save(); OrderChanged orderChanged = new OrderChanged() { OrderId = order.OrderId, StoreName = order.Store.Name, State = "Paid" }; //notificar publish Order Changed _orderChangedService.SendMessagesAsync(orderChanged); }); }
public async Task <Unit> Handle(CreatePaymentCommand request, CancellationToken cancellationToken) { var userAccount = await _userRepository.GetUserAccountAsync(request.UserId); if (userAccount == null) { throw new PaymentDomainException($"User id: {request.UserId} does not exist."); } var payment = new Moula.Payment.Domain.AggregatesModel.PaymentAggerate.Payment { Id = Guid.NewGuid(), UserId = userAccount.UserId, CreatedDate = request.CreatedDate, Status = Domain.PaymentStatus.Pending, Amount = request.Amount }; // If account balance is less than the requested payment amount, // close the payment with "Not enough funds" message if (request.Amount > userAccount.Balance) { payment.Status = Domain.PaymentStatus.Closed; payment.ClosedReason = "Not enough funds"; } await _paymentRepository.AddPayment(payment); await _paymentRepository.UnitOfWork.SaveEntitiesAsync(cancellationToken); return(await Task.FromResult(Unit.Value)); }
public PaymentViewModel AddPayment(PaymentViewModel model) { var paymentModel = mapper.Map <Payment>(model); var payment = paymentRepository.AddPayment(paymentModel); return(mapper.Map <PaymentViewModel>(payment)); }
public async Task <IActionResult> PostPayment([FromBody] Payment payment) { if (!ModelState.IsValid) { return(BadRequest(ModelState)); } if (payment.Amount <= 0) { return(BadRequest("Payment amount can't be 0")); } if (payment.Customer == null || payment.CustomerId == null) { return(BadRequest("payment is not associated with a valid user")); } payment.DueDate = GetLastDayOfMonth(); var customer = _customerRepository.GetCustomer(payment.CustomerId).Result; if (customer == null) { return(BadRequest("customer is not valid for payment")); } await _paymentRepository.AddPayment(payment); return(CreatedAtAction("GetPayment", new { id = payment.PaymentId }, payment)); }
public void AddPaymentTets() { PaymentModel payment = new PaymentModel() { PatientCID = "345678901010", Agency = "H*",//payment.Patient?.AgencyID != null ? _domainObjectRepository.Get<Agency>(a => a.AgencyID == payment.Patient.AgencyID).AgencyName : null, CompanionAmount = 0, BeneficiaryFName = "New Boston", BeneficiaryLName = "Newman", BeneficiaryMName = "", BeneficiaryBank = "Burgan Bank-008", BeneficiaryIBan = "3333333333333", CompanionCID = "345678901021", CreatedBy = "Mounir", CreatedDate = DateTime.Now, Notes = "test notes", PaymentEndDate = new DateTime(2018, 5, 1),//2018-04-15 Hospital = "BARROW NEUROSURGICAL ASSOCIATES", ModifiedBy = null, ModifiedDate = null, PatientAmount = 0, CompanionPayRate = 25, PatientPayRate = 75, PaymentDate = DateTime.Now, PaymentLengthPeriod = 3, // DateTime.Now- new DateTime(2018, 4, 16), PaymentStartDate = new DateTime(2018, 4, 16), //2018-04-02 TotalDue = 230, BeneficiaryCID = "345678901010", CompanionFName = "New Boston", CompanionLName = "Newman", CompanionMName = "", }; _paymentRepository.AddPayment(payment); }
public async Task <ResponseCardPaymentDto> PersistPaymentRequestToDatabase(RequestCardPaymentDto requestDto, ResponseExternalPaymentDto responseDto, ValidationData validationData) { var paymentEntity = _mapper.Map <RequestCardPaymentDto, Payment>(requestDto); paymentEntity.CurrencyId = validationData.Currency.Id; paymentEntity.Method = PaymentMethods.Card.ToString(); var paymentCardEntity = await _paymentCardRepository.GetPaymentCardByNumberAsync(requestDto.Number); // if payment card exists do not add new record of it in database if (paymentCardEntity != null) { paymentEntity.PaymentCardId = paymentCardEntity.Id; } else { paymentCardEntity = _mapper.Map <RequestCardPaymentDto, PaymentCard>(requestDto); paymentCardEntity.CardIssuerId = validationData.CardIssuer.Id; paymentEntity.PaymentCard = paymentCardEntity; } _mapper.Map(responseDto, paymentEntity); _paymentRepository.AddPayment(paymentEntity); await _paymentRepository.CommitAsync(); var responseCardpaymentDto = _mapper.Map <Payment, ResponseCardPaymentDto>(paymentEntity); return(responseCardpaymentDto); }
public async Task <ResponseMessage> AuthorizePayment(Payment payment) { var transacion = await _paymentFacade.AuthorizePayment(payment); var validationResult = new ValidationResult(); if (transacion.Status != TransactionStatus.Authorized) { validationResult.Errors.Add(new ValidationFailure("Payment", "Error to process your payment, please contact your card operator")); return(new ResponseMessage(validationResult)); } payment.AddTransaction(transacion); _paymentRepository.AddPayment(payment); if (!await _paymentRepository.UnitOfWork.Commit()) { validationResult.Errors.Add(new ValidationFailure("Payment", "Error to process your payment")); //TODO: implement the process to revert the payment, request to Gateway. //you can send to the Queue in case you need to to more operation // OR if you only want to revert, you can simply call this method _paymentRepository.RevertPayment(transacion.Nsu); return(new ResponseMessage(validationResult)); } return(new ResponseMessage(validationResult)); }
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>()); }
public async Task GivenExistingPayment_WhenGetPaymentIsCalled_ThenPaymentReturned() { var existingPayment = BuildPayment(); await _paymentRepository.AddPayment(existingPayment); var url = string.Format(enpointUrl, existingPayment.Id.ToString()); var httpResponse = await HttpClient.GetAsync(url); var payment = ReadAsJsonAsync <Payment>(httpResponse.Content); payment.Should().NotBeNull(); }
// POST api/values public IHttpActionResult Post([FromBody] Payment value) { var result = false; try { result = _paymentRepository.AddPayment(value); return(Ok(result)); } catch (Exception ex) { return(InternalServerError(ex)); } }
public HttpResponseMessage AddPayment([FromBody] PaymentViewModel model) { try { var data = paymentrepository.AddPayment(model); if (data != null) { return(Request.CreateResponse(HttpStatusCode.OK, new { success = true, result = model, message = "The record Created Successfully" })); } return(Request.CreateResponse(HttpStatusCode.OK, new { success = false, message = "The was an error creating this record" })); } catch (Exception e) { return(Request.CreateResponse(HttpStatusCode.OK, new { success = false, message = $"there was an error creating this record {e.Message}" })); } }
public ActionResult Create(PaymentModel payment) { ValidatePayment(payment); if (ModelState.IsValid) { payment.CreatedBy = User.Identity.Name; _paymentRepository.AddPayment(payment); Success(string.Format("Payment for Patient with Civil ID <b>{0}</b> was successfully added.", payment.PatientCID), true); return(RedirectToAction("List")); } else { Danger(string.Format("Please correct the error list before proceeding"), true); //companion.CompanionTypes = _companionManagmentRepository.GetCompanionTypes(); //companion.Banks = _patientManagmentRepository.GetBanks(); payment = _paymentRepository.GetPaymentObject(payment.PatientCID); return(View(payment)); } }
public async Task <int> ProcessPaymentAsync(PaymentDetailsDto paymentDetails) { // Save payment details var newPaymentDetails = CreateNewPayment(paymentDetails); _repository.AddPayment(newPaymentDetails); // Send request to bank var client = new HttpClient(); client.DefaultRequestHeaders.Accept.Clear(); var postBody = new StringContent(JsonConvert.SerializeObject(paymentDetails), System.Text.Encoding.UTF8, "application/json"); var postResponse = await client.PostAsync("https://localhost:44378/api/MockBank/", postBody); // Update details with response UpdatePaymentStatus(newPaymentDetails.PaymentId, postResponse.IsSuccessStatusCode); // Return payment ID return(newPaymentDetails.PaymentId); }
private async Task <bool> SavePaymentHistory(Payment payment) { int retry = 0; bool isInserted = await _iPaymentRepository.AddPayment(payment); while (retry < 3) { if (isInserted) { return(true); } await SavePaymentHistory(payment); retry += 1; } // LOGGING: FAILED HISTORY SAVE return(false); }
public ActionResult Create(string orderid, FormCollection collection, HttpPostedFileBase file) { try { string Namepic = null; if (file != null) { string ImageName = System.IO.Path.GetFileName(file.FileName); string physicalPath = Server.MapPath("~/paymentimage/" + ImageName); file.SaveAs(physicalPath); Namepic = "~/paymentimage/" + ImageName; } EfDbContext _context = new EfDbContext(); int count = 0; foreach (Payment pay in _context.payments) { count = int.Parse(pay.PaymentID); } count++; string currentUserId = User.Identity.GetUserId(); var paymentCheckOrders = from o in _context.payments where o.MemberID == currentUserId select o; var item = paymentCheckOrders.ToList().First(); string idorder = item.OrderID.ToString(); Payment payment = new Payment(); payment.PaymentID = count.ToString(); payment.MemberID = User.Identity.GetUserId().ToString(); payment.OrderID = idorder; payment.imageTranferReceipt = Namepic; repository.AddPayment(payment); return(RedirectToAction("Index")); } catch { return(View()); } }
public async Task <ActionResult> Create(PaymentViewModel payment) { if (payment != null) { //payment.ReservationDetails = _reservationRepo.GetReservationsByCustomer(payment.CustomerID) // .FirstOrDefault(x => DateTime.Compare(x.DateOfBooking.Value, DateTime.Now) >= 0); //var currentUser = User.Identity.GetUserId(); //payment.CustomerID = _customerRepo.GetCustomerRecordByUserId(currentUser).CustID; await _paymentRepo.AddPayment(payment); return(View("Confirmation")); } //ViewBag.CustID = new SelectList(db.Customers, "CustID", "UserID", payment.CustID); //ViewBag.PaymentMethodID = new SelectList(db.PaymentMethods, "PaymentMethodID", "PaymentDesc", payment.PaymentMethodID); payment.MethodsOfPayment = await _paymentRepo.GetPaymentMethods(); return(View(payment)); }
public decimal BookRide(User user, int rideId, string source, string destination, int seat) { decimal cost = 0; var ride = Dbr.GetRideById(rideId); if (ride != null) { cost = CalculateCharge(ride.ViaMaps, source, destination); var rider = new Rider() { UserId = user.Id, Source = source, Destination = destination, RideCost = cost * seat, Seats = seat, RideId = ride.Id }; //ride.Riders.Add(rider.Id); var payment = new Payment() { CreatorId = ride.CreatorId, RiderId = user.Id, Price = cost * seat, RideId = ride.Id }; try { Dbrr.AddRider(rider); Dbp.AddPayment(payment); Dbr.UpdateRide(ride); return(cost * seat); }catch (Exception) { return(-1); } } return(-1); }
public void AddPayment() { Payment payment = new Payment(); try { Console.WriteLine("Print GuestId: "); payment.GuestId = Int32.Parse(Console.ReadLine()); Console.WriteLine("Print ReservationId: "); payment.ReservationId = Int32.Parse(Console.ReadLine()); Console.WriteLine("Print Amount: "); payment.Amount = decimal.Parse(Console.ReadLine()); Console.WriteLine("Print PayTime: "); payment.PayTime = DateTime.Parse(Console.ReadLine()); paymentService.AddPayment(payment); Console.WriteLine("Object successful Added"); ConsolePaymentPresenter.Present(paymentService.ReadPayments()); } catch (Exception ex) { Console.WriteLine(ex.Message); AddPayment(); } }
public Int32 AddPayment(Int32 personId, DateTime date, String category, String subCategory, Decimal spended) { IPaymentRepository paymentRep = CSRepositoryFactory.GetPaymentRepository(); return(paymentRep.AddPayment(personId, date, category, subCategory, spended)); }
public Payment AddPayment(Payment payment) { setPaymentFields(payment); _paymentRepository.AddPayment(payment); return(payment); }
public ActionResult Purchase(string stripeEmail, string stripeToken, AdManageViewModel model) { AdManage objAdManage = new AdManage(); var result = new JsonResult(); int selectedplan = Convert.ToInt32(TempData["PlanAmount"]); string planname = Enum.GetName(typeof(CommanClass.Plans), selectedplan); int planvalue = (int)Enum.Parse(typeof(CommanClass.PlanType), planname.ToString()); int planamount = selectedplan * 100; string FileName = string.Empty; int userid = Convert.ToInt32(Session["UserId"]); var customers = new StripeCustomerService(); var charges = new StripeChargeService(); try { var RegisteredUser = registrationRepository.GetClientById(userid); if (!string.IsNullOrEmpty(stripeEmail)) { var customer = customers.Create(new StripeCustomerCreateOptions { Email = stripeEmail, SourceToken = stripeToken }); var charge = charges.Create(new StripeChargeCreateOptions { Amount = planamount, Description = selectedplan.ToString(), //Currency = "usd", Currency = "eur", CustomerId = customer.Id }); //Save Response in PaymentTransaction Table PaymentTransaction payment = new PaymentTransaction() { RegistId = userid, Customer_stripeEmail = stripeEmail, Customer_Id = customer.Id, Customer_stripeToken = stripeToken, Customer_Created = customer.Created, Customer_DefaultSourceId = customer.DefaultSourceId, Customer_InvoicePrefix = customer.InvoicePrefix, Customer_StripeResponse_RequestId = customer.StripeResponse.RequestId, Customer_StripeResponse_ResponseJson = customer.StripeResponse.ResponseJson, Charge_Id = charge.Id, Charge_Amount = charge.Amount, Charge_BalanceTransactionId = charge.BalanceTransactionId, Charge_Created = charge.Created, Charge_CustomerId = charge.CustomerId, Charge_Description = charge.Description, Charge_FailureCode = charge.FailureCode, Charge_FailureMessage = charge.FailureMessage, Charge_Outcome_SellerMessage = charge.Outcome.SellerMessage, Charge_Paid = charge.Paid, Charge_Source_Id = charge.Source.Id, Charge_Status = charge.Status, Charge_StripeResponse_RequestId = charge.StripeResponse.RequestId, Charge_StripeResponse_ResponseJson = charge.StripeResponse.ResponseJson, IsSuccess = true, Response = "Complete", PaymentMethod = (int)CommanClass.PaymentMethod.Stripe }; _paymentRepository.AddPayment(payment); //_paymentRepository.SaveAll(); //Insert stripe response information in PaymentTransaction table //db.PaymentTransaction.Add(payment); //db.SaveChanges(); RegisteredUser.PaymentStatus = true; registrationRepository.Edit(RegisteredUser); if (!string.IsNullOrEmpty(charge.FailureCode)) { model.ResponseMessage = "Your subscription failed!!"; model.Paymentstatus = CommanClass.PaymentStatus.Failed; return(View(model)); } } //for zarinpal payment plugin else { //Payment with Zarinpal Service reference. string authority = string.Empty; int payment_request_response = 0; PaymentTransaction payment = new PaymentTransaction(); try { PaymentGatewayImplementationServicePortTypeClient request = new PaymentGatewayImplementationServicePortTypeClient(); Amount = PlanCalculate.CalculatePlanAmount(selectedplan); payment_request_response = request.PaymentRequest(MerchantID, 120, "Test", "", "", ZarinpalCallbackURL, out authority); if (payment_request_response > 0) { if (Request.Files[0].ContentLength > 0) { Guid FileNameGuid = Guid.NewGuid(); FileName = FileNameGuid.ToString() + ".html"; string _path = Path.Combine(Server.MapPath("~/AdHTML"), FileName); Request.Files[0].SaveAs(_path); } objAdManage = Mapper.Map <AdManageViewModel, AdManage>(model); objAdManage.Addeddate = DateTime.Now.Date; objAdManage.RegistAdId = userid; objAdManage.UpdateDate = DateTime.Now.Date; objAdManage.UpdatedBy = userid; objAdManage.UploadFile = FileName; objAdManage.Description = model.Description; adManageRepository.AddAd(objAdManage); adManageRepository.SaveAll(); payment.IsSuccess = false; payment.RegistId = userid; payment.Authority = authority; payment.Payment_RequestResponse = payment_request_response; payment.Charge_Amount = Convert.ToInt32(Amount); //Insert in Payment Table Session["IsPaymentPrecessing"] = false; _paymentRepository.InsertPaymentTransactionData(payment); //Redirect to zarinpal gateway site for payment. return(Redirect(ZarinpalPaymentURL + authority)); } } catch (Exception ex) { payment.Charge_Amount = Convert.ToInt32(Amount); payment.IsSuccess = false; payment.RegistId = userid; payment.Authority = authority; payment.Payment_RequestResponse = payment_request_response; payment.PaymentRequest_ErrorResponse = ex.ToString(); _paymentRepository.InsertPaymentTransactionData(payment); Session["PaymentStatus"] = false; Session["IsPaymentPrecessing"] = false; } } //Insert in DB if (Request.Files[0].ContentLength > 0) { //FileName = Convert.ToString(Session["UserId"]) + ".html"; Guid FileNameGuid = Guid.NewGuid(); FileName = FileNameGuid.ToString() + ".html"; string _path = Path.Combine(Server.MapPath("~/AdHTML"), FileName); Request.Files[0].SaveAs(_path); } // AdManage objAdManage = new AdManage(); objAdManage = Mapper.Map <AdManageViewModel, AdManage>(model); objAdManage.Addeddate = DateTime.Now; objAdManage.RegistAdId = Convert.ToInt64(Session["UserId"]); objAdManage.UpdateDate = DateTime.Now; objAdManage.UpdatedBy = Convert.ToInt32(Session["UserId"]); objAdManage.UploadFile = FileName; objAdManage.Description = model.Description; adManageRepository.AddAd(objAdManage); if (adManageRepository.SaveAll()) { Registration objRegisterUser = registrationRepository.GetClientById(userid); objRegisterUser.PaymentStatus = true; registrationRepository.Edit(objRegisterUser); Session["PaymentStatus"] = true; model.ResponseMessage = "Your subscription succesfully!!"; model.Paymentstatus = CommanClass.PaymentStatus.Sucess; return(View(model)); } else { model.ResponseMessage = "Your subscription failed!!"; model.Paymentstatus = CommanClass.PaymentStatus.Failed; Session["PaymentStatus"] = false; } } catch (Exception ex) { //result.Data = "Your subscription failed!! " + ex.Message.ToString(); model.ResponseMessage = "Your subscription failed!! " + ex.Message.ToString(); model.Paymentstatus = CommanClass.PaymentStatus.Failed; Session["PaymentStatus"] = false; } return(View(model)); }
public JsonResult AddPayment(PaymentModel model) { string data = repository.AddPayment(model); return(Json(data, JsonRequestBehavior.AllowGet)); }
public Payment AddPayment(Payment payment) { return(_paymentRespository.AddPayment(payment)); }
public string AddPayment(PaymentDetail detail) { return(Repository.AddPayment(Mapper.Map <DataModels.Payment.PaymentDetail>(detail))); }
public async Task <bool> AddPayment(Payments payment) { return(await _paymentRepository.AddPayment(payment)); }
public async Task <ActionResult> PostPayment(PaymentInsertDTO payment) { var paymentId = await _paymentRepository.AddPayment(payment.ToEntity()); return(Ok()); }
public IActionResult Post([FromBody] Payment item) { _repository.AddPayment(item); return(Ok("Record Added")); }