public async Task ProcessPayment_DataStoreError() { PaymentResult paymentResult = new PaymentResult() { ExternalPaymentReference = Guid.NewGuid().ToString(), PaymentStatus = PaymentStatus.Approved, PaymentId = Guid.NewGuid().ToString() }; PaymentItem payment = CreateValidPaymentItem(); _mockBank.Setup(x => x.ProcessPaymentAsync(It.IsAny <PaymentItem>())).ReturnsAsync(paymentResult); _mockDataAccess.Setup(x => x.SavePaymentItemAsync(It.IsAny <PaymentItem>())).ReturnsAsync((PaymentItem)null); MerchantId merchantId = new MerchantId() { UUID = Guid.NewGuid().ToString() }; PaymentHelper paymentHelper = new PaymentHelper(_mockLogger.Object, _mockBank.Object, _mockDataAccess.Object); await Assert.ThrowsAsync <ArgumentOutOfRangeException>(() => paymentHelper.ProcessPaymentAsync(merchantId, payment)).ConfigureAwait(false); }
public ContentResult Notify(string id) { id = DecodePaymentId(id); string errorMsg = string.Empty; string response = string.Empty; try { var payment = Core.PluginsManagement.GetPlugin <IPaymentPlugin>(id); var payInfo = payment.Biz.ProcessNotify(_httpContextAccessor); if (payInfo != null) { var orderid = payInfo.OrderIds.FirstOrDefault(); var orderIds = _iOrderService.GetOrderPay(orderid).Select(item => item.OrderId).ToList(); var payTime = payInfo.TradeTime; _iOrderService.PaySucceed(orderIds, id, payInfo.TradeTime.Value, payInfo.TradNo, payId: orderid); //写入支付状态缓存 string payStateKey = CacheKeyCollection.PaymentState(string.Join(",", orderIds)); //获取支付状态缓存键 Cache.Insert(payStateKey, true, 15); //标记为已支付 #region TOD:ZYF 注释,统一在service的方法里实现 //PaymentHelper.IncreaseSaleCount(orderIds); #endregion PaymentHelper.GenerateBonus(orderIds, Request.Host.ToString()); response = payment.Biz.ConfirmPayResult(); } } catch (Exception ex) { errorMsg = ex.Message; Core.Log.Error("移动端支付异步通知返回出错,支持方式:" + id, ex); } return(Content(response)); }
public IPaymentResponse Charge(PaymentRequest request) { var dic = new Dictionary <string, object>(); dic.Add("amt_tran", request.TotalAmount.ToString()); var currency = GetCurrencyCode(request.Currency); dic.Add("tran_currency", currency); dic.Add("purchase_id", DataHelper.GeneratePurchaseId(request.Id)); var preferences = new Dictionary <string, string> { { "success_url", PaymentHelper.GetCallbackUrl(this, nameof(CheckoutFinished), Context) }, { "failure_url", Setting.FailureUrl } }; dic.Add("preferences", preferences); var result = QualpayAPI.CheckOutUrl(dic, Setting); if (result == null) { return(null); } var redirectUrl = result["checkout_link"]; RedirectResponse res = new RedirectResponse(redirectUrl, request.Id); return(res); }
public void GetTerminalByMID(string expected, params object[] mids) { //arrange var settingProvider = new Mock <ISettingProvider>(); settingProvider.Setup(m => m.IsPaymentAPITestMode).Returns(() => true); PaymentProcessorFactory.SettingProvider = settingProvider.Object; var terminals = new List <Terminal>(); foreach (var mid in mids) { terminals.Add(new Terminal() { GW3_MID = (string)mid }); } //act var terminal = PaymentHelper.GetTerminal(Domain.Payment.PaymentUISection.CreditCard, terminals, expected); //assert Assert.Equal(expected, terminal.GW3_MID); }
public async Task <ActionResult> Cancel(string paymentId, PaymentInstrument instrument) { try { switch (instrument) { case PaymentInstrument.CreditCard: await PaymentHelper.CancelCreditCardPayment(paymentId, this.swedbankPayClient, TempData, this.cartService); break; case PaymentInstrument.Trustly: await PaymentHelper.CancelTrustlyPayment(paymentId, this.swedbankPayClient, TempData, this.cartService); break; case PaymentInstrument.Invoice: await PaymentHelper.CancelInvoicePayment(paymentId, this.payeeInfoOptions.PayeeReference, this.swedbankPayClient, TempData, this.cartService); break; } return(RedirectToAction("Details", "Orders")); } catch (Exception e) { TempData["ErrorMessage"] = $"Something unexpected happened. {e.Message}"; return(RedirectToAction("Details", "Orders")); } }
public IPaymentResponse Charge(PaymentRequest request) { var req = new KpSessionRequest { PurchaseCurrency = request.Currency, PurchaseCountry = request.Country, OrderAmount = request.TotalAmount, OrderLines = new[] { new KpSessionRequest.OrderLine { Name = request.Name, Quantity = 1, UnitPrice = request.TotalAmount, TotalAmount = request.TotalAmount } }, }; var callbackUrl = PaymentHelper.GetCallbackUrl(this, nameof(Notify), Context); var apiClient = new KlarnaApi(Setting, request.Country); var kpSession = apiClient.CreateKpSession(req); var hppSession = apiClient.CreateHppSession(kpSession.SessionId, Setting.GetGetMerchantUrls(callbackUrl, request.Id)); return(new RedirectResponse(hppSession.RedirectUrl, request.Id) { paymemtMethodReferenceId = hppSession.SessionId }); }
public IPaymentResponse Charge(PaymentRequest request) { HiddenFormResponse res = new HiddenFormResponse(); if (this.Setting == null) { return(null); } var dic = new AopDictionary(); dic.Add("subject", request.Name); if (request.Description != null) { dic.Add("body", request.Description); } dic.Add("out_trade_no", request.Id.ToString("N")); dic.Add("product_code", "FAST_INSTANT_TRADE_PAY");//fix value var amount = Math.Round(request.TotalAmount, 2); dic.Add("total_amount", amount); dic.Add("time_expire", DateTime.Now.AddMinutes(10)); string notifurl = PaymentHelper.GetCallbackUrl(this, nameof(Notify), Context); string returnurl = request.ReturnUrl ?? PaymentHelper.EnsureHttpUrl(this.Setting.ReturnUrl, Context); res.html = AlipayApi.Pay(dic, this.Setting, returnurl, notifurl); return(res); }
public IActionResult OrderProcess(string complete) { var sessionusername = (int)HttpContext.Session.GetInt32("UserId"); var GetTotalPrice = HttpContext.Session.GetString("totalprice"); ViewBag.TotalPrice = GetTotalPrice; var defaultAddress = AddressHelper.GetAddressByDefaultId(); var defaultPayment = PaymentHelper.GetPaymentByDefaultId(); var getProduct = JsonConvert.DeserializeObject <List <OrderAndPaymentViewModel> >(HttpContext.Session.GetString("ProductTime")); foreach (var item in getProduct) { item.UserId = sessionusername; item.AddressId = defaultAddress.AddressId; item.CCNumber = defaultPayment.CCNumber; item.CCUserName = defaultPayment.CCUserName; item.Month = defaultPayment.Month; item.Year = defaultPayment.Year; item.PaymentId = defaultPayment.PaymentId; item.CVV = defaultPayment.CVV; item.Street = defaultAddress.Street; item.City = defaultAddress.City; item.State = defaultAddress.State; item.PostalCode = defaultAddress.PostalCode; } if (complete == "done") { return(RedirectToAction("SaveOrder", "Store")); } return(View("~/Views/Store/Order.cshtml", getProduct)); }
public ActionResult ConfirmBooking(int UserId, int EventId, int By, bool IsPayed = true) { String message = "Booking Successfull"; using (SussexDBEntities db = new SussexDBEntities()) { UserEvent userEvent = db.UserEvents.Where(w => w.UserId == UserId && w.EventId == EventId).FirstOrDefault(); if (userEvent != null) { message = "User already has booking for this event"; } else { userEvent = new UserEvent(); userEvent.UserId = UserId; userEvent.EventId = EventId; userEvent.UserEventRegisteredDate = DateTime.Now; userEvent.IsAccepted = false; db.UserEvents.Add(userEvent); db.SaveChanges(); PaymentHelper.AddEventPaymentForUser(UserId, EventId, IsPayed); } } return(Redirect("/Event/BookSuccessfullMessage/" + By + "?Message=" + message + "&EventId=" + EventId + "&UserId=" + UserId)); }
public void Cannot_activate_brand_over_licensee_brand_limit() { var licensee = BrandHelper.CreateLicensee(); licensee.AllowedBrandCount = 1; var brand = BrandHelper.CreateBrand(licensee); BrandCommands.ActivateBrand(new ActivateBrandRequest { BrandId = brand.Id, Remarks = "remarks" }); var newBrand = BrandHelper.CreateBrand(BrandRepository.Licensees.Single(x => x.Id == licensee.Id)); BrandHelper.AssignCountry(newBrand.Id, Country.Code); BrandHelper.AssignCulture(newBrand.Id, Culture.Code); PaymentHelper.CreatePaymentLevel(newBrand.Id, Currency.Code); BrandHelper.CreateWallet(licensee.Id, newBrand.Id); Action action = () => BrandCommands.ActivateBrand(new ActivateBrandRequest { BrandId = newBrand.Id, Remarks = "remarks" }); action.ShouldThrow <ValidationException>() .Where(x => x.Message.Contains("licenseeBrandLimitExceeded")); }
public async Task ProcessPaymentReturnsBadRequestWhenModelStateIsInvalid() { using (var mock = AutoMock.GetLoose()) { //Arrange var controller = mock.Create <PaymentsController>(); var processPaymentDto = PaymentHelper.GetCorrectProcessPaymentDto(); controller.ModelState.AddModelError("Some key", "Some message"); //Act var result = await controller.ProcessPayment(processPaymentDto); //Assert Assert.IsType <BadRequestObjectResult>(result.Result); var badRequest = result.Result as BadRequestObjectResult; var error = badRequest?.Value as SerializableError; Assert.NotNull(error); Assert.Single(error); Assert.Equal("Some key", error.First().Key); var value = error.First().Value as string[]; Assert.NotNull(value); Assert.Equal("Some message", value[0]); } }
public async Task ProcessPaymentReturnsInternalServerErrorWhenPaymentHasNotBeenSaved() { using (var mock = GetMockWithAutoMapper()) { //Arrange mock.Mock <IBankService>().Setup(x => x.ProcessPaymentRequest(It.IsAny <BankPaymentRequestDto>())) .Returns(() => Task.FromResult(new BankPaymentResponseDto())); mock.Mock <IPaymentService>().Setup(x => x.CreatePayment(It.IsAny <Payment>())) .Returns(() => Task.FromResult(false)); var controller = mock.Create <PaymentsController>(); var processPaymentDto = PaymentHelper.GetCorrectProcessPaymentDto(); //Act var result = await controller.ProcessPayment(processPaymentDto); //Assert Assert.IsType <ObjectResult>(result.Result); var statusCodeResult = result.Result as ObjectResult; Assert.Equal(500, statusCodeResult?.StatusCode); Assert.Equal("Payment creation failed", statusCodeResult?.Value); } }
public async Task ProcessPayment_HappyPath() { PaymentResult paymentResult = new PaymentResult() { ExternalPaymentReference = Guid.NewGuid().ToString(), PaymentStatus = PaymentStatus.Approved, PaymentId = Guid.NewGuid().ToString() }; PaymentItem payment = CreateValidPaymentItem(); _mockBank.Setup(x => x.ProcessPaymentAsync(It.IsAny <PaymentItem>())).ReturnsAsync(paymentResult); _mockDataAccess.Setup(x => x.SavePaymentItemAsync(It.IsAny <PaymentItem>())).ReturnsAsync(payment); MerchantId merchantId = new MerchantId() { UUID = Guid.NewGuid().ToString() }; PaymentHelper paymentHelper = new PaymentHelper(_mockLogger.Object, _mockBank.Object, _mockDataAccess.Object); PaymentResult result = await paymentHelper.ProcessPaymentAsync(merchantId, payment).ConfigureAwait(false); Assert.NotNull(result); }
public ActionResult Edit(string id) { PaymentViewModel model = PaymentHelper.GetPayment(id); SessionHelper.PeriodId = model.PeriodId; SessionHelper.Calendar = CalendarHelper.GetCalendar(PayablePeriodHelper.GetPayablePeriod(model.PeriodId.ToString()).CalendarId.ToString()); if (model.BankAccount == null) { model.BankAccount = BankHelper.GetBankAccountList(model.BankId); model.BankAccountId = model.BankAccount.Any() ? Convert.ToInt32(model.BankAccount.First().Value) : 0; } if (model.VendorSite == null) { model.VendorSite = VendorHelper.GetAllSites(model.VendorId) .Select(x => new SelectListItem { Text = x.Name, Value = x.Id.ToString() }).ToList(); model.VendorSiteId = model.VendorSite.Any() ? Convert.ToInt32(model.VendorSite.First().Value) : 0; } model.PaymentInvoiceLines = PaymentHelper.GetPaymentLines(id).ToList(); model.SOBId = SessionHelper.SOBId; SessionHelper.Payment = model; return(View("Create", model)); }
private void CalcularCuotas() { var listadoCuotas = PaymentHelper.Divide((decimal)Adeuda, Cuotas ?? 1).ToArray(); Montocuota = (float?)listadoCuotas.First(); SubTotal = listadoCuotas.Sum(); }
public IActionResult AddPayment(string payment) { string pattern1 = @"delete"; string pattern2 = @"add"; string validate = payment; Match match = Regex.Match(validate, pattern1); var paymentId = Regex.Match(payment, @"\d+").Value; string helperType = Regex.Match(payment, pattern2).Value; HttpContext.Session.SetString("HelperType", helperType); HttpContext.Session.SetString("PaymentId", paymentId); if (match.Success) { var result = Int32.Parse(paymentId); dm.Payment paymentInfo = new dm.Payment { PaymentId = result }; PaymentHelper.DeletePaymentByPaymentId(paymentInfo); return(RedirectToAction("ChangePayment", "Home")); } return(RedirectToAction("AddPaymentView", "Home")); }
public void SalesInvoicecmdProcessAccessCompute_ChargeIsAllowedForCustomer_Applicable() { var customer = PaymentHelper.GetCustomer("LGBUI"); var salesInvoice = PaymentHelper.CreateInvoiceWithDetail(customer, PaymentHelper.DefaultProduct, 1, 10).Invoice; Assert.IsFalse(IsHiddenAndNotApplicable(salesInvoice.accesscmdProcess)); }
// In the user homepage when payment is selected, userId is passed in PaymentViewModel format public List <PaymentViewModel> GetAllPayments(PaymentViewModel paymentView) { dm.Payment paymentDomainModel = createModel.MappingPayment(paymentView); List <dm.Payment> domainPaymentList = PaymentHelper.GetPaymentById(paymentDomainModel); return(createModel.MappingView(domainPaymentList)); }
private ProcessOrderResponse HandleSuccess(ICart cart, IPayment payment, IVippsPaymentDetails paymentDetails, IVippsUserDetails userDetails, string orderId) { if (payment == null) { OrderNoteHelper.AddNoteAndSaveChanges(cart, "Cancel", $"No vipps payment found for vipps order id {orderId}. Canceling payment"); PaymentHelper.CancelPayment(cart, paymentDetails.Amount, orderId); return(new ProcessOrderResponse { ErrorMessage = $"No vipps payment found for vipps order id {orderId}.", ProcessResponseErrorType = ProcessResponseErrorType.NOVIPPSPAYMENTINCART }); } EnsureExpressPaymentAndShipping(cart, payment, paymentDetails, userDetails); payment.Status = PaymentStatus.Processed.ToString(); AddNote(cart, payment, orderId, paymentDetails); var loadOrCreatePurchaseOrderResponse = CreatePurchaseOrder(cart); if (loadOrCreatePurchaseOrderResponse.PurchaseOrder != null) { return(loadOrCreatePurchaseOrderResponse); } PaymentHelper.CancelPayment(cart, payment); return(loadOrCreatePurchaseOrderResponse); }
private string GetHtml(bool isisUsingSanbox, string iavToken, Money money, PaymentRequest request) { var apiUrl = PaymentHelper.GetCallbackUrl(this, nameof(CreateTransfer), Context); var html = GenerateHtml(iavToken, isisUsingSanbox, apiUrl, money, request); return(html); }
public async Task <CreditCardDto> GetPaymentProfileAsync() { var user = await GetCurrentUser(); if (user == null) { throw new NotFoundException("user not found"); } if (user.PaymentProfile == null) { throw new NotFoundException("user payment profile not found"); } // Due to the CPI regulation, credit card information not allow to store in our database // send request to vendor and get the credit card info var url = string.Format(_paymentProcessConfigs.GetProfileUrl, _paymentProcessConfigs.RootUrl, user.PaymentProfile.CustomerCode); var authorization = PaymentHelper.GetAuthorizationHeader(_paymentProcessConfigs.ProfilePasscode); var headers = new List <(string, string)> { authorization }; var response = await HttpRequestHelper.GetAsync(url, headers); var meta = await response.Content.ReadAsStringAsync(); PaymentProfileResponseDto paymentProfileDto = JsonConvert.DeserializeObject <PaymentProfileResponseDto>(meta); return(paymentProfileDto.Card); }
public async Task <ActionResult <Payment> > PostPayment(Payment payment) { try { PaymentHelper paymentHelper = new PaymentHelper(_context); if (payment.SecurityCode == null) { payment.SecurityCode = "000"; } if (paymentHelper.Validatated(payment) == false) { return(StatusCode(400)); } var paymentState = paymentHelper.Process(payment); if (paymentState.PaymentProcessStatus == Data.Standard.PaymentProcessStatus.PaymentStatus.Processed) { return(Ok()); } } catch (Exception ex) { return(StatusCode(500)); } return(StatusCode(500)); }
/// <summary> /// 更新支付方式是否启用 /// </summary> private void UpdatePaymentStatus() { var id = GetInt("id"); var status = GetInt("status"); if (status != 0 && status != 1) { ReturnErrorMsg("支付方式类型不合法"); return; } var payment = PaymentHelper.GetPayment(id); if (payment == null) { ReturnErrorMsg("不存在该支付方式"); return; } if (status == payment.Status) { ReturnErrorMsg("状态未改变"); return; } payment.Status = status; if (PaymentHelper.SavePayment(payment)) { ReturnCorrectMsg("新增成功"); } else { ReturnErrorMsg("新增失败"); } }
private PaymentHelper GetHelper(Payment Payment) { var helper = new PaymentHelper(Payment); helper.ServiceUserId = GetUserId(); return(helper); }
public void SalesInvoicecmdProcessExecuted_HasAllowedRealPaymentType_NoMessage() { var warningMessage = new MessageId(typeof(SalesInvoiceBL), nameof(SalesInvoiceBL.SalesInvoice_cmdProcess_Executed)); var salesInvoice = PaymentHelper.CreateInvoiceWithDetail(PaymentHelper.GetCustomer("AMERET"), PaymentHelper.DefaultProduct, 10, 10).Invoice; salesInvoice.cmdProcess.Execute(); Assert.IsFalse(warningMessage.Any(TestContext.Messages)); }
public void ReturnsErrorWhenAmountIsNegative() { var payment = PaymentHelper.GetCorrectProcessPaymentDto(); payment.Amount = -5; SingleErrorTest(payment, "Amount of payment should be greater than 0"); }
public void WhenNewBankAccountIsCreated() { var licensee = BrandHelper.CreateLicensee(); var brand = BrandHelper.CreateBrand(licensee, isActive: true); var bankAccount = PaymentHelper.CreateBankAccount(brand.Id, brand.DefaultCurrency); ScenarioContext.Current.Add("bankAccountId", bankAccount.Id); }
public frmPayment() { InitializeComponent(); helper = new PaymentHelper(); flag = false; _payment = new Payment(); _paymentBLL = new PaymentBLL(); }
public void WhenNewPaymentLevelIsCreated() { ScenarioContext.Current.Should().ContainKey("brandId"); var brandId = ScenarioContext.Current.Get <Guid>("brandId"); var paymentLevel = PaymentHelper.CreatePaymentLevel(brandId, "CAD", true); ScenarioContext.Current.Add("paymentLevelId", paymentLevel.Id); }
private PaymentHelper GetHelper(int PaymentId) { PaymentHelper helper = new PaymentHelper(PaymentId); helper.ServiceUserId = GetUserId(); return(helper); }