/// <summary> /// Request a new payment. /// </summary> /// <param name="request">The payment request details.</param> /// <param name="cancellationToken">A cancellation token that can be used by other objects or threads to receive notice of cancellation.</param> /// <exception cref="ArgumentException">Thrown when callbackUri has not been suplied via options or passed to the method.</exception> /// <returns>A <see cref="Task"/> representing the asynchronous operation.</returns> public async Task <Result <Payment>?> RequestPaymentAsync(NewPayment request, CancellationToken cancellationToken = default) { if (request is null) { throw new ArgumentNullException(nameof(request)); } if (request.CallbackUri is null) { request.CallbackUri = _options.DefaultCallbackUri ?? throw new ArgumentException($"'{nameof(_options.DefaultCallbackUri)}' has not been configured. To avoid this, configure it via 'options' or use the '{nameof(request.CallbackUri)}' parameter.", nameof(request)); } request.MerchantId = _options.MerchantId; var result = await PostJsonAsync <Result <Payment> >("payment/request.json", request, null, cancellationToken) .ConfigureAwait(false); if (!string.IsNullOrWhiteSpace(result?.Data?.Authority)) { result.Data.PaymentUri = GetPaymentGateUrl(result.Data.Authority); } return(result); }
public async Task <IActionResult> OnPostAddCardAsync() { base.IdentifyCostumer(); var client = new Yandex.Checkout.V3.Client(shopId: Strings.YandexShopId, secretKey: Strings.YandexAPIKey); var newPayment = new NewPayment { Amount = new Amount { Value = 1.00m, Currency = "RUB" }, SavePaymentMethod = true, Confirmation = new Confirmation { Type = ConfirmationType.Redirect, ReturnUrl = $"https://power-now.ru/costumer" }, PaymentMethodData = new PaymentMethod { Type = PaymentMethodType.BankCard }, Description = "Для привязки карты списываем сумму в 1 рубль, которую сразу же вернем на Вашу карту" }; Payment payment = client.CreatePayment(newPayment); string url = payment.Confirmation.ConfirmationUrl; await Costumer.SetOrderId(_appRepository, payment.Id); await Costumer.SetCardStatus(_appRepository, CardsStatus.Progress); return(Redirect(url)); }
public bool ValidatePayment(NewPayment payment) { bool valid = false; if (payment.CustomerId != null) { if (payment.Type != null && payment.ExpirationDate.HasValue && payment.CardNumber != null && payment.SecurityNumber != null && payment.Name != null ) { var nonNullableExpirationDate = (DateTime)payment.ExpirationDate; var dateCardInvalid = new DateTime(nonNullableExpirationDate.Year, nonNullableExpirationDate.Month, 1).AddMonths(1); if (CardTypes.Contains(payment.Type) && VerifyDate(dateCardInvalid)) { payment.IsExpired = false; valid = true; } } else if (payment.RoutingNumber != null && payment.BankAccountNumber != null) { valid = true; } else if (payment.PaypalAuth != null) { valid = true; } } return(valid); }
public async Task <ActionResult <Unit> > Post(NewPayment newPayment) { await _mediator.Send(new CreatePaymentCommand(newPayment.AccountingPointId, newPayment.PayDate, newPayment.Amount, newPayment.PayerInfo, newPayment.Type, newPayment.BatchId)); await _unitOfWork.SaveWorkAsync(); return(Ok()); }
public async Task <IActionResult> SavePaymentAsync([FromBody] NewPayment newPayment) { if (newPayment == null || !newPayment.IsValid) { return(BadRequest()); } var payment = await _paymentService.SavePaymetAsync(newPayment); return(Ok(payment)); }
public bool Validate() { var result = NewPayment.Validate(); //var result = !string.IsNullOrEmpty(NewPayment.CustomerName) // && !string.IsNullOrEmpty(CardType) // && !string.IsNullOrEmpty(CardNumber) // && ExpirationMonth > 0 && ExpirationMonth <= 12 // && ExpirationYear >= DateTime.Today.Year // && !string.IsNullOrEmpty(CardVerificationNumber); return(result); }
public async Task <string> CreatePayment( decimal value, Entities.Payment.Types type, Dictionary <string, string> metadata = null, User user = null, Currency currency = null) { user ??= _userService.User; currency ??= user.Currency; metadata[Entities.Payment.TypeMetadataName] = type.ToString(); if (currency.Key != "RUB") { using var client = new HttpClient(); const string url = "https://www.cbr-xml-daily.ru/daily_json.js"; var result = await client.GetAsync(url); var rate = JsonConvert.DeserializeObject <CurrenciesRate>(await result.Content.ReadAsStringAsync()); if (Equals(currency, Currency.EUR)) { value *= Convert.ToDecimal(rate.Valute.EUR.Value); } else if (Equals(currency, Currency.USD)) { value *= Convert.ToDecimal(rate.Valute.USD.Value); } } var newPayment = new NewPayment { Amount = new Amount { Value = value, Currency = "RUB" }, Metadata = metadata, Confirmation = new Confirmation { Type = ConfirmationType.Redirect, ReturnUrl = "localhost", Locale = user.Culture.Key == Culture.Russian.Key ? "ru_RU" : "en_US" }, }; var payment = await _client.CreatePaymentAsync(newPayment); await SavePaymentToDb(payment, user, currency, type); return(payment.Confirmation.ConfirmationUrl); }
public ActionResult PostPaymentType(NewPayment newPayment) { var validator = new CheckPaymentInfo(); if (validator.ValidatePayment(newPayment)) { var paymentType = _connections.AddPaymentType(newPayment); return(Accepted(paymentType)); } else { return(BadRequest("invalid input")); } }
private void recordPaymentBarButtonItem_ItemClick(object sender, ItemClickEventArgs e) { if (this.ActiveMdiChild == null) { return; } if (this.ActiveMdiChild.GetType() == typeof(FrmInvoiceListView)) { var list = this.ActiveMdiChild as FrmInvoiceListView; var newpayment = new NewPayment(); newpayment.ShowObject(list.GetSelectedItem()); newpayment.ShowDialog(); } }
public PaymentType AddPaymentType(NewPayment newPayment) { using (var connection = new SqlConnection(ConnectionString)) { var queryString = @"Insert into Payment (customerId, type, cardNumber, securityNumber, bankAccountNumber, routingNumber, paypalAuth, name, isExpired, expirationDate) Output inserted.* Values (@customerId, @type, @cardNumber, @securityNumber, @bankAccountNumber, @routingNumber, @paypalAuth, @name, @isExpired, @expirationDate)"; var payment = connection.QueryFirstOrDefault <PaymentType>(queryString, newPayment); if (payment != null) { return(payment); } } throw new Exception("Uhh uhh uhhh, didn't say the magic word."); }
public async Task SavePayment_ShouldSetPaymentInterestTo0_001() { var newPayment = new NewPayment { Name = "Teste", Value = 100, DueDate = DateTime.Today, PaymentDate = DateTime.Today.AddDays(1) }; await _paymentService.SavePaymetAsync(newPayment); _paymentRepositoryMock.Verify( p => p.SaveAsync( It.Is <Payment>(p => p.Interest == PaymentService.InterestForLessThanThreeDays) ) ); }
public async Task SavePayment_ShouldSetPaymentFineT0_05() { var newPayment = new NewPayment { Name = "Teste", Value = 100, DueDate = DateTime.Today, PaymentDate = DateTime.Today.AddDays(6) }; await _paymentService.SavePaymetAsync(newPayment); _paymentRepositoryMock.Verify( p => p.SaveAsync( It.Is <Payment>(p => p.Fine == PaymentService.FineForMoreThanFiveDays) ) ); }
public async Task <PaymentVisualization> SavePaymetAsync(NewPayment newPayment) { var fine = GetFine(newPayment); var interest = GetInterest(newPayment); var payment = new Payment ( newPayment.Name, newPayment.Value.Value, newPayment.PaymentDate.Value, newPayment.DueDate.Value, fine, interest ); await _paymentRepository.SaveAsync(payment); return(GetPaymentVisualization(payment)); }
private decimal?GetInterest(NewPayment newPayment) { if (!newPayment.IsLate) { return(null); } if (newPayment.DelayInDays <= 3) { return(InterestForLessThanThreeDays); } else if (newPayment.DelayInDays <= 5) { return(InterestForLessThanFiveDays); } else { return(InterestForMoreThanFiveDay); } }
public ActionResult MakePayment(NewPayment payment) { if (payment.Ammount <= 0) { this.ModelState.AddModelError("Ammount", "Ammount should be more than zero"); return(this.PartialView("NewPaymentPartial", payment)); } var account = this.database.AccountRepository.GetByLogin(this.User.Identity.Name); if (account.UserName == payment.CorrespondentName) { this.ModelState.AddModelError("CorrespondentName", "You can not transfer to yourself"); return(this.PartialView("NewPaymentPartial", payment)); } var correspondent = this.database.AccountRepository.GetByName(payment.CorrespondentName); if (correspondent == null) { this.ModelState.AddModelError("CorrespondentName", "Correspondent not exists"); return(this.PartialView("NewPaymentPartial", payment)); } if (account.Balance < payment.Ammount) { this.ModelState.AddModelError("Ammount", "Insufficient funds"); return(this.PartialView("NewPaymentPartial", payment)); } this.database.PaymentRepository.Create(new Payment() { SenderUserId = account.Id, CorrespondentUserId = correspondent.Id, Ammount = payment.Ammount }); this.database.Save(); this.ViewData["PaymentRequested"] = true; return(this.PartialView("NewPaymentPartial", payment)); }
protected void submit_YandexPay_Click(object sender, EventArgs e) { ServicePointManager.SecurityProtocol = (SecurityProtocolType)3072; File.Delete(Server.MapPath("log.txt")); // 1. Создайте платеж и получите ссылку для оплаты decimal amount = decimal.Parse(sum.Text, CultureInfo.InvariantCulture.NumberFormat); var newPayment = new NewPayment { Amount = new Amount { Value = amount, Currency = "RUB" }, Confirmation = new Confirmation { Type = ConfirmationType.Redirect, ReturnUrl = Request.Url.AbsoluteUri } }; Payment payment = _client.CreatePayment(newPayment); // 2. Перенаправьте пользователя на страницу оплаты string url = payment.Confirmation.ConfirmationUrl; Response.Redirect(url); }
public async Task ShouldThrowExceptionWhenCallbackIsNotSet() { string json = JsonSerializer.Serialize(new { Status = 100, Authority = "000000000000000000000000000000012345" }); var mockHttp = new MockHttpMessageHandler(); mockHttp.When("*") .Respond("application/json", json); var httpClient = mockHttp.ToHttpClient(); var options = new ZarinPalOptions { DefaultCallbackUri = null, MerchantId = "something-that-does-not-matter", IsDevelopment = true }; var service = new ZarinPal.V4.ZarinPalService(httpClient, Options.Create(options)); await Assert.ThrowsAsync <ArgumentException>("request", async() => { var payment = new NewPayment { Amount = 1000, CallbackUri = null, Description = "From tests", }; await service.RequestPaymentAsync(payment); }); }
protected virtual void OnNewPayment(NewPaymentEventArgs e) { NewPayment?.Invoke(this, e); }
private void Parse(string str) { str = WebUtility.UrlDecode(str); NameValueCollection nq = new NameValueCollection(); string[] strData = str.Split(new char[] { '&', '=' }, StringSplitOptions.None); for (int i = 0; i < strData.Length; i += 2) { nq.Add(strData[i], strData[i + 1]); } //проверка подлинности сообщения string sha1Str = string.Format("{0}&{1}&{2}&{3}&{4}&{5}&{6}&{7}&{8}", nq["notification_type"], nq["operation_id"], nq["amount"], nq["currency"], nq["datetime"], nq["sender"], nq["codepro"], "", nq["label"]); #if !DEBUG sha1Str = Crypto.SHA1Hex(sha1Str); if (sha1Str != nq["sha1_hash"]) { return; } #endif //перевод защищен кодом протекции. if (nq["codepro"] != "false") { return; } //login не известен if (string.IsNullOrWhiteSpace(nq["label"])) { return; } string[] split = nq["label"].Split('|'); if (split.Length != 3) { split = new string[3] { "17a87d89-b8d7-4274-9049-78d7b6af94af", "0", string.Format("Строка не распознана: {0}", nq["label"]) } } ; //Сумма, которая списана со счета отправителя. string amount = nq["withdraw_amount"]; if (string.IsNullOrEmpty(amount)) { amount = nq["amount"];//Сумма операции. } if (string.IsNullOrEmpty(amount)) { return; } int payment = (int)float.Parse(amount, new CultureInfo("en-US")); DateTimeOffset dT = DateTimeOffset.UtcNow; NewPayment?.Invoke(split, payment, dT, nq["operation_id"]); } }
public ActionResult Callback(IPNModel callback) { bool valid_key = false; if (!string.IsNullOrEmpty(callback.private_key_hash) && callback.private_key_hash.Length == 128 && Regex.IsMatch(callback.private_key_hash, "[a-zA-Z0-9]+")) { string[] ss = ConfigurationManager.AppSettings["PrivateKeys"].Split(new char[] { ',', ' ' }, StringSplitOptions.RemoveEmptyEntries); List <string> s = new List <string>(); foreach (string s1 in ss) { s.Add(Calculator.md512(s1)); } valid_key = s.Contains(callback.private_key_hash); } if (!string.IsNullOrEmpty(Request.Form["plugin_ver"]) && string.IsNullOrEmpty(callback.status) && valid_key) { return(new ContentResult() { Content = "cryptoboxver_asp_1.0" }); } if (callback.order == null) { callback.order = ""; } if (callback.user == null) { callback.user = ""; } if (callback.usercountry == null) { callback.usercountry = ""; } string box_status = "cryptobox_nochanges"; if (ModelState.IsValid) { int paymentId = 0; crypto_payments obj = Context.crypto_payments.FirstOrDefault(x => x.boxID == callback.box && x.orderID == callback.order && x.userID == callback.user && x.txID == callback.tx && x.amount == callback.amount && x.addr == callback.addr); if (obj == null) { crypto_payments newPayments = new crypto_payments() { boxID = callback.box, boxType = callback.boxtype, orderID = callback.order, userID = callback.user, countryID = callback.usercountry, coinLabel = callback.coinlabel, amount = callback.amount, amountUSD = callback.amountusd, unrecognised = (byte)(callback.status == "payment_received_unrecognised" ? 1 : 0), addr = callback.addr, txID = callback.tx, txDate = callback.datetime, txConfirmed = callback.confirmed, txCheckDate = DateTime.Now, recordCreated = DateTime.Now }; try { Context.crypto_payments.Add(newPayments); Context.SaveChanges(); paymentId = newPayments.paymentID; } catch (DbEntityValidationException dbEx) { var modelErrors2 = new List <string>(); foreach (var validationErrors in dbEx.EntityValidationErrors) { foreach (var validationError in validationErrors.ValidationErrors) { modelErrors2.Add("Property: " + validationError.PropertyName + " Error: " + validationError.ErrorMessage); } } return(new ContentResult() { Content = String.Join(", ", modelErrors2.ToArray()) }); } obj = newPayments; box_status = "cryptobox_newrecord"; } else if (callback.confirmed == 1 && obj.txConfirmed == 0) { obj.txConfirmed = 1; obj.txCheckDate = DateTime.Now; Context.SaveChanges(); paymentId = obj.paymentID; box_status = "cryptobox_updated"; } else { paymentId = obj.paymentID; } NewPayment.Main(paymentId, callback, box_status); return(new ContentResult() { Content = box_status }); } //for test var modelErrors = new List <string>(); foreach (ModelState err in ViewData.ModelState.Values) { foreach (ModelError error in err.Errors) { modelErrors.Add(error.ErrorMessage); } } return(new ContentResult() { Content = String.Join(", ", modelErrors.ToArray()) }); }
public NewPaymentTests() { _newPayment = Fixture.Create <NewPayment>(); }