public void Credit_Card_Not_Present_Include_Addres_Request_Returns_Successfully() { // Arrange var request = new ChargeRequest { Amount = 11.00m, Card = new Card { Number = "4444 3333 2222 1111", Cvv = "999", ExpirationDate = "04/2017", Address = new Address { Line1 = "123 Main St.", City = "Austin", State = "TX", Zip = "78759" } }, ExtendedInformation = new ExtendedInformation { TypeOfGoods = "PHYSICAL", SoftDescriptor = Helper.RequestSoftDescriptor, DynamicMCC = Helper.RequestDynamicMCC }, DeveloperApplication = new DeveloperApplication { DeveloperId = 12345678, Version = "1.2" } }; var apiContext = new APIContext(); var controller = new PaymentsController(); // Act var response = controller.ProcessRequest <ChargeResponse>(apiContext, request); // Assert Assert.IsNotNull(response); Assert.AreEqual(response.Transaction.SoftDescriptor, Helper.ResponseSoftDescriptor); Assert.AreEqual(response.Transaction.DynamicMCC, Helper.ResponseDynamicMCC); Assert.IsTrue(response.Success); }
public void TestCharge() { OpenpayAPI openpayAPI = new OpenpayAPI(Constants.API_KEY, Constants.MERCHANT_ID); Card card = openpayAPI.CardService.Create(GetCardInfo()); ChargeRequest request = new ChargeRequest(); request.Method = "card"; request.SourceId = card.Id; request.Description = "Testing from .Net"; request.Amount = new Decimal(111.00); Charge charge = openpayAPI.ChargeService.Create(request); Assert.IsNotNull(charge); Assert.IsNotNull(charge.Id); Assert.IsNotNull(charge.CreationDate); Assert.AreEqual("completed", charge.Status); }
public void TestChargeToCustomerWithBankAccount() { OpenpayAPI openpayAPI = new OpenpayAPI(Constants.API_KEY, Constants.MERCHANT_ID); ChargeRequest request = new ChargeRequest(); request.Method = "bank_account"; request.Description = "Testing from .Net [BankAccount]"; request.Amount = new Decimal(9.99); request.DueDate = new DateTime(2020, 12, 6, 11, 50, 0); Charge charge = openpayAPI.ChargeService.Create("adyytoegxm6boiusecxm", request); Assert.IsNotNull(charge); Assert.IsNotNull(charge.Id); Assert.IsNotNull(charge.CreationDate); Assert.IsNotNull(charge.PaymentMethod); Assert.AreEqual("in_progress", charge.Status); }
public void TestRefundChargeWithRequest() { OpenpayAPI openpayAPI = new OpenpayAPI(Constants.NEW_API_KEY, Constants.NEW_MERCHANT_ID); Card card = openpayAPI.CardService.Create(GetScotiaCardInfo()); SearchParams searh = new SearchParams(); List <Customer> customers = openpayAPI.CustomerService.List(searh); Customer customer = customers[0]; customer.ExternalId = null; ChargeRequest request = new ChargeRequest(); request.Method = "card"; request.SourceId = card.Id; request.Description = "Testing from .Net"; request.Amount = new Decimal(111.00); request.DeviceSessionId = "sah2e76qfdqa72ef2e2q"; request.Customer = customer; Charge charge = openpayAPI.ChargeService.Create(request); Assert.IsNotNull(charge); Assert.IsNotNull(charge.Id); Assert.IsNotNull(charge.CreationDate); Assert.AreEqual("completed", charge.Status); Decimal refundAmount = charge.Amount; string description = "reembolso desce .Net de " + refundAmount; RefundRequest refundRequest = new RefundRequest(); refundRequest.Description = description; refundRequest.Amount = refundAmount; // refundRequest.Gateway = Charge refund = openpayAPI.ChargeService.RefundWithRequest(charge.Id, refundRequest); Assert.IsNotNull(refund); Assert.IsNotNull(refund.Id); Assert.IsNotNull(refund.CreationDate); Assert.AreEqual("completed", refund.Status); }
public IActionResult Charge([FromBody] SampleChargeRequest chargeRequest) { var request = new ChargeRequest { Source = new PaymentSourceCardOnFile() { Type = PaymentSourceType.CARD_ON_FILE, CardOnFile = new CardOnFile() { Id = chargeRequest.Source, CVV = chargeRequest.CVV // should be provided when the transaction is user attended } }, Params = new TransactionParameters() { Amount = chargeRequest.Amount, Capture = true, //sale charge CofType = CofType.UNSCHEDULED_CARDHOLDER, CurrencyCode = CurrencyCode.USD, CountryCode = ISO3166CountryCode.USA, SavePaymentInstrument = true }, Meta = new TransactionMeta() { ClientCustomerID = "12345", //set your customer id ClientInvoiceID = "IX213", //set your invoice id ClientTransactionDescription = "E-comm order", // any useful description ClientTransactionID = "000111222333" } }; try { var charge = _chargeService.Charge(request); return(Ok(charge)); } catch (System.Exception ex) { var exx = ex; throw; } }
public void TestChargeToCustomerWithStore() { OpenpayAPI openpayAPI = new OpenpayAPI(Constants.API_KEY, Constants.MERCHANT_ID); ChargeRequest request = new ChargeRequest(); request.Method = "store"; request.Description = "Testing from .Net [STORE]"; request.Amount = new Decimal(9.99); request.DueDate = DateTime.Now.AddDays(25); Charge charge = openpayAPI.ChargeService.Create("adyytoegxm6boiusecxm", request); Assert.IsNotNull(charge); Assert.IsNotNull(charge.Id); Assert.IsNotNull(charge.CreationDate); Assert.IsNotNull(charge.PaymentMethod); Assert.IsNotNull(charge.PaymentMethod.Reference); Assert.AreEqual("in_progress", charge.Status); }
public void TestChargeToMerchantAndRefund() { ChargeRequest request = new ChargeRequest(); request.Method = "card"; request.Card = GetCardInfo(); request.Description = "Testing from .Net with new card"; request.Amount = new Decimal(9.99); OpenpayAPI openpayAPI = new OpenpayAPI(Constants.API_KEY, Constants.MERCHANT_ID); Charge charge = openpayAPI.ChargeService.Create(request); Assert.IsNotNull(charge); Assert.IsNotNull(charge.Id); Charge refund = openpayAPI.ChargeService.Refund(charge.Id, "Merchant Refund"); Assert.IsNotNull(refund); Assert.IsNotNull(refund.Refund); }
public JsonResult Charge(string nonce, int orderId) { // Every payment you process with the SDK must have a unique idempotency key. // If you're unsure whether a particular payment succeeded, you can reattempt // it with the same idempotency key without worrying about double charging // the buyer. Order order = context.Orders.Find(orderId); string uuid; if (order == null) { return(Json(null)); } else { uuid = string.IsNullOrWhiteSpace(order.PaymentRef) ? NewIdempotencyKey() : order.PaymentRef; } double totalPayment = order.TotalAmount + order.TaxAmount + order.DeliveryCharge; totalPayment *= 100; // Monetary amounts are specified in the smallest unit of the applicable currency. // This amount is in cents. It's also hard-coded for $1.00, // which isn't very useful. Money amount = NewMoney((int)totalPayment, "USD"); ChargeRequest body = new ChargeRequest(AmountMoney: amount, IdempotencyKey: uuid, CardNonce: nonce); var response = _transactionApi.Charge(_accessToken, _locationId, body); if (response.Errors == null) { order.PaymentRef = uuid; context.SaveChanges(); return(Json(uuid)); } return(Json(null)); }
public void TestMerchantChargeWithBitcoin() { ChargeRequest request = new ChargeRequest(); request.Method = "bitcoin"; request.Description = "Testing from .Net [BITCOIN]"; request.Amount = new Decimal(9.99); OpenpayAPI openpayAPI = new OpenpayAPI(Constants.API_KEY, Constants.MERCHANT_ID); Charge charge = openpayAPI.ChargeService.Create(request); Assert.IsNotNull(charge); Assert.IsNotNull(charge.Id); Assert.IsNotNull(charge.PaymentMethod); Assert.IsNotNull(charge.PaymentMethod.AmountBitcoins); Assert.IsNotNull(charge.PaymentMethod.PaymentAddress); Assert.IsNotNull(charge.PaymentMethod.PaymentUrlBip21); Assert.IsNotNull(charge.PaymentMethod.ExchangeRate); Assert.AreEqual("bitcoin", charge.PaymentMethod.Type); Assert.AreEqual("charge_pending", charge.Status); }
public void ChargeCapture() { var row = this.TestContext.DataRow; Charge response = null; { //カードを作る CardRequest card = Helper.CreateCard(row); //課金を作成 ChargeRequest charge = new ChargeRequest(); charge.Amount = 500; charge.Description = "仮の売上"; charge.Capture = false;//これで仮売上 charge.Card = card; response = client.Charge.Create(charge); { Helper.AssertChargeReqAndRes(charge, response); Assert.AreEqual(response.AmountRefunded, 0); Assert.IsFalse(response.Paid); Assert.IsFalse(response.Captured); Assert.IsFalse(response.Refunded); Assert.IsNull(response.Customer); Assert.IsNull(response.FailureMessage); Helper.AssertCardAndCSV(response.Card, row); } } { var captured = this.client.Charge.Capture(response.ID, response.Amount); Assert.AreEqual(captured.Amount, response.Amount); Assert.IsTrue(captured.Captured); Assert.IsNull(captured.FailureMessage); } }
public void Credit_Card_Not_Present_Charge_Authorization_And_Capture_Request_Returns_Successfully() { // Arrange var request = new ChargeRequest { Amount = 11.00m, Card = new Card { Number = "4444 3333 2222 1111", Cvv = "999", ExpirationDate = "04/2016", Address = new Address { Line1 = "123 Main St.", City = "Austin", State = "TX", Zip = "78759" } }, ExtendedInformation = new ExtendedInformation { TypeOfGoods = "PHYSICAL" }, DeveloperApplication = new DeveloperApplication { DeveloperId = 12345678, Version = "1.2" } }; var apiContext = new APIContext(); var controller = new PaymentsController(); // Act var response = controller.ProcessRequest <ChargeResponse>(apiContext, request); // Assert Assert.IsNotNull(response); Assert.IsTrue(response.Success); }
/// <summary> /// Charge transaction /// </summary> /// <param name="chargeRequest">Request parameters to charge transaction</param> /// <returns>Transaction</returns> public Transaction Charge(ChargeRequest chargeRequest) { try { //try to get the selected location var selectedLocation = GetActiveLocations().FirstOrDefault(location => location.Id.Equals(_squarePaymentSettings.LocationId)); if (selectedLocation == null) throw new NopException("Location is a required parameter for payment requests"); //create transaction API var configuration = CreateApiConfiguration(); var transactionsApi = new TransactionsApi(configuration); //create charge transaction var chargeResponse = transactionsApi.Charge(selectedLocation.Id, chargeRequest); if (chargeResponse == null) throw new NopException("No service response"); //check whether there are errors in the service response if (chargeResponse.Errors?.Any() ?? false) { var errorsMessage = string.Join(";", chargeResponse.Errors.Select(error => error.ToString())); throw new NopException($"There are errors in the service response. {errorsMessage}"); } return chargeResponse.Transaction; } catch (Exception exception) { var errorMessage = $"Square payment error: {exception.Message}."; if (exception is ApiException apiException) errorMessage = $"{errorMessage} Details: {apiException.ErrorCode} - {apiException.ErrorContent}"; //log errors _logger.Error(errorMessage, exception, _workContext.CurrentCustomer); return null; } }
public void TestCancelCharge() { string customer_id = "aa8ekxqmzcwyxugli0h1"; Customer customer = new Customer(); customer.Name = "Openpay"; customer.LastName = "Test"; customer.PhoneNumber = "1234567890"; customer.Email = "*****@*****.**"; customer.Id = customer_id; OpenpayAPI openpayAPI = new OpenpayAPI(Constants.API_KEY, Constants.MERCHANT_ID); Card card = openpayAPI.CardService.Create(GetCardInfo()); ChargeRequest request = new ChargeRequest(); request.Method = "card"; request.SourceId = card.Id; request.Description = "Testing from .Net"; request.Amount = new Decimal(111.00); request.Use3DSecure = true; request.RedirectUrl = "https://www.openpay.mx"; request.Customer = customer; request.Confirm = "false"; request.SendEmail = false; request.DeviceSessionId = "kR1MiQhz2otdIuUlQkbEyitIqVMiI16f"; Charge charge = openpayAPI.ChargeService.Create(request); Assert.IsNotNull(charge); Assert.IsNotNull(charge.Id); Assert.IsNotNull(charge.CreationDate); Assert.IsNotNull(charge.PaymentMethod.Url); Assert.AreEqual("charge_pending", charge.Status); charge = openpayAPI.ChargeService.CancelByMerchant(Constants.MERCHANT_ID, charge.Id, request); Assert.IsNotNull(charge); Assert.AreEqual("cancelled", charge.Status); }
public CommonApiResponse Hold(ChargeRequest request, [FromServices] SessionManagerService sessionManager, [FromServices] OperationManagerService operationManager) { var merchant = (Merchant)HttpContext.Items["Merchant"]; var session = sessionManager.GetByOrderId(merchant, request.OrderId); if (session == null) { return new CommonApiResponse { Error = new ApiError(InnerError.SessionNotFound) } } ; var result = operationManager.Charge(merchant, session, null, request.Amount); return(new DebitResponse { Status = result.OperationStatus, Auth = result.AdditionalAuth }); } }
/// <summary> /// Successful response returned from a Credit Card Present Charge request. /// https://apidocs.securenet.com/docs/creditcardpresent.html?lang=JSON#charge /// </summary> public int Voids_Charge_Request_Returns_Successfully() { // Arrange var request = new ChargeRequest { Amount = 11.00m, Card = new Card { TrackData = "%B4444333322221111^SECURENET^17041015432112345678?;4444333322221111=17041015432112345678?" }, DeveloperApplication = new DeveloperApplication { DeveloperId = 12345678, Version = "1.2" }, ExtendedInformation = new ExtendedInformation { SoftDescriptor = Helper.RequestSoftDescriptor, DynamicMCC = Helper.RequestDynamicMCC }, }; var apiContext = new APIContext(); var controller = new PaymentsController(); // Act var response = controller.ProcessRequest <ChargeResponse>(apiContext, request); // Assert Assert.IsNotNull(response); Assert.IsTrue(response.Success); Assert.IsNotNull(response.Transaction); Assert.AreEqual(response.Transaction.SoftDescriptor, Helper.ResponseSoftDescriptor); Assert.AreEqual(response.Transaction.DynamicMCC, Helper.ResponseDynamicMCC); Assert.IsTrue(response.Transaction.TransactionId > 0); return(response.Transaction.TransactionId); }
public void AuthorizeWithDataInBody() { //Arrage const string nonce = "32f3c8c2b06e96ec8e19eb4d39672720"; const string timestamp = "1443539180"; var charge = new ChargeRequest { Amount = 15.95, Currency = "EUR", Payments = new List <PaymentRequest>() { new IdealPaymentRequest() { Amount = 15.95, Currency = "EUR", Details = new IdealDetailsRequest { IssuerId = "INGBNL2A", SuccessUrl = "", FailedUrl = "", CancelledUrl = "", ExpiredUrl = "", PurchaseId = "e90b4be7b95c48ccaeafe64193bc1ebc", Description = "Test description" } } } }; var json = JsonConvert.SerializeObject(charge); var auth = new OAuth("xvz1evFS4wEEPTGEFPHBog", "LswwdoUaIvS8ltyTt5jkRh4J50vUPVVHtR2YPi5kE"); const string expectedSignature = "MzcxYjUyZTBkZGE1YjYwOTA2MmExMzRmMGU2OTkzYWZmODVlNjgwOGU2MzgyYmNkNDI5ZmFmZDQwYTAwMGU3Nw=="; //Act var actualSignature = auth.GenerateSignature("POST", "https://api.cmpayments.com/charges/v1?exampleParameter=value", json, timestamp, nonce); //Assert Assert.AreEqual(expectedSignature, actualSignature); }
public void TestCharge3DSecure() { OpenpayAPI openpayAPI = new OpenpayAPI(Constants.API_KEY, Constants.MERCHANT_ID); Card card = openpayAPI.CardService.Create(GetCardInfo()); ChargeRequest request = new ChargeRequest(); request.Method = "card"; request.SourceId = card.Id; request.Description = "Testing from .Net"; request.Amount = new Decimal(111.00); request.Use3DSecure = true; request.RedirectUrl = "https://www.openpay.mx"; Charge charge = openpayAPI.ChargeService.Create(request); Assert.IsNotNull(charge); Assert.IsNotNull(charge.Id); Assert.IsNotNull(charge.CreationDate); Assert.IsNotNull(charge.PaymentMethod.Url); Assert.AreEqual("charge_pending", charge.Status); }
public static string Charge(string nonce) { // Every payment you process with the SDK must have a unique idempotency key. // If you're unsure whether a particular payment succeeded, you can reattempt // it with the same idempotency key without worrying about double charging // the buyer. string uuid = NewIdempotencyKey(); // Monetary amounts are specified in the smallest unit of the applicable currency. // This amount is in cents. It's also hard-coded for $1.00, // which isn't very useful. Money amount = NewMoney(100, "USD"); ChargeRequest body = new ChargeRequest(AmountMoney: amount, IdempotencyKey: uuid, CardNonce: nonce); var response = _transactionApi.Charge(_accessToken, _locationId, body); if (response.Errors == null) { return "Transaction complete\n" + response.ToJson(); } else { return response.Errors.ToString(); } }
public void ACH_Add_Billing_Address_Charge_Request_Returns_Successfully() { // Arrange var request = new ChargeRequest { Amount = 10.00m, Check = new Check { FirstName = "Jack", LastName = "Test", RoutingNumber = "222371863", AccountNumber = "123456", Address = new Address { Line1 = "123 Main St.", City = "Austin", State = "TX", Zip = "78759" }, }, DeveloperApplication = new DeveloperApplication { DeveloperId = 12345678, Version = "1.2" } }; var apiContext = new APIContext(); var controller = new PaymentsController(); // Act var response = controller.ProcessRequest <ChargeResponse>(apiContext, request); // Assert Assert.IsNotNull(response); Assert.IsTrue(response.Success); }
/// <summary> /// Successful response returned from an Charge using Tokenization request. /// https://apidocs.securenet.com/docs/creditcardnotpresent.html?lang=csharp#tokenization /// </summary> public void Credit_Card_Not_Present_Charge_Using_Tokenization_Request_Returns_Successfully(string token) { // Arrange var request = new ChargeRequest { Amount = 10.00m, PaymentVaultToken = new PaymentVaultToken { PaymentMethodId = token, PublicKey = "278DCC4B-85FE-485D-AFDD-9927AC4CA229" }, AddToVault = true, ExtendedInformation = new ExtendedInformation { TypeOfGoods = "PHYSICAL", SoftDescriptor = Helper.RequestSoftDescriptor, DynamicMCC = Helper.RequestDynamicMCC }, DeveloperApplication = new DeveloperApplication { DeveloperId = 12345678, Version = "1.2" } }; var apiContext = new APIContext(); var controller = new PaymentsController(); // Act var response = controller.ProcessRequest <ChargeResponse>(apiContext, request); // Assert Assert.IsNotNull(response); Assert.AreEqual(response.Transaction.SoftDescriptor, Helper.ResponseSoftDescriptor); Assert.AreEqual(response.Transaction.DynamicMCC, Helper.ResponseDynamicMCC); Assert.IsTrue(response.Success); }
public IActionResult AddCharge([FromBody] ChargeToken ChargeData) { if (ChargeData == null) { _log.Error(nameof(ChargeData).ToString() + "Cannot be null."); throw new ArgumentNullException(nameof(ChargeData), "Cannot be null."); } Charge charge = null; ChargeRequest request = new ChargeRequest(); try { _log.Information("Adding charge to customer."); var openpayAPI = OpenPayHandler.GetOpenPayInstance(); request.Method = ChargeData.Method; request.SourceId = ChargeData.SourceId; request.Amount = new Decimal(ChargeData.Amount); request.Description = ChargeData.Description; request.DeviceSessionId = ChargeData.DeviceSessionId; //request.Customer = customerCargo; charge = openpayAPI.ChargeService.Create(ChargeData.CustomerId, request); } catch (Exception ex) { _log.Error("Exception while adding charge." + ex.ToString()); return(NotFound()); } return(Ok(charge)); }
public ActionResult Create(ChargeRequest chargeRequest) { string carta = chargeRequest.carta; int expMonth = chargeRequest.expMonth; int expYear = chargeRequest.expYear; string cvc = chargeRequest.cvc; using (var client = new HttpClient()) { client.BaseAddress = new Uri("http://localhost:8082/SpringMVC/servlet/"); var postJob = client.PostAsJsonAsync <ChargeRequest>("pay/" + Session["UserConnecteId"] + "/" + carta.ToString() + "/" + expMonth.ToString() + "/" + expYear.ToString() + "/" + cvc, chargeRequest); postJob.Wait(); var postResult = postJob.Result; if (postResult.IsSuccessStatusCode) { return(RedirectToAction("../Item/ListItemPayee")); } ModelState.AddModelError(string.Empty, "Server error occured. Please contact admin for help!"); // ViewBag.CategoryList= new SelectList(categorys, "idCategory", "nameCategory"); return(View(chargeRequest)); } }
public void TestChargeToCustomerWithCard_metdatata_USD() { OpenpayAPI openpayAPI = new OpenpayAPI(Constants.API_KEY, Constants.MERCHANT_ID); ChargeRequest request = new ChargeRequest(); request.Method = "card"; request.Card = GetCardInfo(); request.Description = "Testing from .Net"; request.Amount = new Decimal(9.99); request.Metadata = new Dictionary <string, string> (); request.Metadata.Add("test_key1", "pruebas"); request.Metadata.Add("test_key2", "123456"); request.Currency = "USD"; Charge charge = openpayAPI.ChargeService.Create("adyytoegxm6boiusecxm", request); Assert.IsNotNull(charge); Assert.IsNotNull(charge.Id); Assert.IsNotNull(charge.CreationDate); Assert.AreEqual("completed", charge.Status); Assert.IsNotNull(charge.Metadata); Assert.IsNotNull(charge.ExchangeRate); }
public void SecureNet_Vault_Store_Account_After_Charge_Request_Returns_Successfully() { // Arrange var request = new ChargeRequest { Amount = 11.00m, AddToVault = true, Card = new Card { Number = "4444 3333 2222 1111", ExpirationDate = "04/2017", Address = new Address { Line1 = "123 Main St.", City = "Austin", State = "TX", Zip = "78759" } }, DeveloperApplication = new DeveloperApplication { DeveloperId = 12345678, Version = "1.2" } }; var apiContext = new APIContext(); var controller = new CustomersController(); // Act var response = controller.ProcessRequest <ChargeResponse>(apiContext, request); // Assert Assert.IsNotNull(response); Assert.IsTrue(response.Success); }
public void TestChargeToCustomerWithSourceId_AndRefund() { String customer_id = "adyytoegxm6boiusecxm"; OpenpayAPI openpayAPI = new OpenpayAPI(Constants.API_KEY, Constants.MERCHANT_ID); ChargeRequest request = new ChargeRequest(); request.Method = "card"; request.SourceId = "kwkoqpg6fcvfse8k8mg2"; request.Description = "Testing from .Net"; request.Amount = new Decimal(9.99); Charge charge = openpayAPI.ChargeService.Create(customer_id, request); Assert.IsNotNull(charge); Assert.IsNotNull(charge.Id); Assert.IsNotNull(charge.CreationDate); Assert.AreEqual("completed", charge.Status); Charge chargeWithrefund = openpayAPI.ChargeService.Refund(customer_id, charge.Id, "refund desc"); Assert.IsNotNull(chargeWithrefund); Assert.IsNotNull(chargeWithrefund.Refund); }
//ONE-TIME CHARGE public void Charge(ChargeRequest model) { StripeConfiguration.SetApiKey(""); var options = new StripeChargeCreateOptions { Amount = (int)(model.Amount * 100), //Stripe arg in units of cents (usd) Currency = model.Currency, SourceTokenOrExistingSourceId = model.SourceTokenOrExistingSourceId, ReceiptEmail = model.Email }; var service = new StripeChargeService(); StripeCharge charge = service.Create(options); //insert into transaction table TransactionsAddRequest transactionModel = new TransactionsAddRequest { UserBaseId = model.UserBaseId, PlanId = model.PlanId, DurationTypeId = model.DurationTypeId, DiscountPercent = model.DiscountPercent, ChargeId = charge.Id, AmountPaid = model.Amount, Currency = model.Currency, CardId = charge.Source.Card.Id, ExpMonth = charge.Source.Card.ExpirationMonth, ExpYear = charge.Source.Card.ExpirationYear, CardLast4 = charge.Source.Card.Last4, NetworkStatus = charge.Outcome.NetworkStatus, Type = charge.Outcome.Type, isPaid = charge.Paid, CreatedDate = charge.Created }; InsertTransaction(transactionModel); }
public bool RealizarCargoTarjeta(int id, string tarjetaToken, string sessionId, CarritoDeCompra carrito, out string resultadoJson) { if (carrito == null || carrito.TotalCarrito <= 0.0) { resultadoJson = new ResultadoCargo(false, ResultadoCargoTarjeta.ErrorInterno, mensaje: "El carrito de compras esta vacio").AsJson(); return(false); } HttpRequest request = HttpContext.Current.Request; var usuario = getUsuarioPortalActual(request); if (usuario.Id != id) { resultadoJson = new ResultadoCargo(false, ResultadoCargoTarjeta.ErrorInterno, mensaje: "Error favor de hacer login").AsJson(); return(false); } using (var _dbContext = new MercampoEntities()) { Startup.OpenDatabaseConnection(_dbContext); if (_dbContext.Database.Connection.State != ConnectionState.Open) { resultadoJson = new ResultadoCargo(false, ResultadoCargoTarjeta.ErrorInterno, mensaje: "Error en el servidor, vuelva a intentarlo de nuevo en unos minutos").AsJson(); return(false); } try { Customer cliente = Startup.OpenPayLib.CustomerService.Get(usuario.IdConekta); if (cliente == null) { resultadoJson = new ResultadoCargo(false, ResultadoCargoTarjeta.ErrorInterno, mensaje: "Error en el servidor, vuelva a intentarlo de nuevo en unos minutos").AsJson(); return(false); } ChargeRequest chargeRequest = new ChargeRequest(); chargeRequest.Method = "card"; chargeRequest.SourceId = tarjetaToken; chargeRequest.Amount = new decimal(carrito.TotalCarrito); chargeRequest.Currency = "MXN"; chargeRequest.Description = "Servicio de anuncios Mercampo.mx"; chargeRequest.OrderId = getToken(); chargeRequest.DeviceSessionId = sessionId; chargeRequest.SendEmail = true; Charge cargo = Startup.OpenPayLib.ChargeService.Create(usuario.IdConekta, chargeRequest); ResultadoCargo resultado = new ResultadoCargo(true, ResultadoCargoTarjeta.Aprobado, cargo.OrderId, cargo.Authorization, "El cargo ha sido exitoso", (double)cargo.Amount); AgregarAnuncios(carrito, usuario.Id); resultadoJson = resultado.AsJson(); return(true); } catch (OpenpayException e) { ResultadoCargoTarjeta res = ResultadoCargoTarjeta.ErrorInterno; if ((int)ResultadoCargoTarjeta.Rechazado == e.ErrorCode) { res = ResultadoCargoTarjeta.Rechazado; } resultadoJson = new ResultadoCargo(false, res, mensaje: TarjetaResultadoHelpers.ObtenerMensajeError((OpenPayErrorCodes)e.ErrorCode)).AsJson(); return(false); } } }
/// <summary> /// 月底自动己充电 /// 仅充会到期的B币券,低于2的时候不会充 /// </summary> public void Charge(UserInfo userInfo) { if (_dailyTaskOptions.DayOfAutoCharge == 0) { _logger.LogInformation("已配置为关闭,跳过"); return; } //大会员类型 int vipType = userInfo.GetVipType(); if (vipType != 2) { _logger.LogInformation("不是年度大会员,跳过"); return; } int targetDay = _dailyTaskOptions.DayOfAutoCharge == -1 ? DateTime.Today.LastDayOfMonth().Day : _dailyTaskOptions.DayOfAutoCharge; _logger.LogInformation("【目标日期】{targetDay}号", targetDay); _logger.LogInformation("【今天】{today}号", DateTime.Today.Day); if (DateTime.Today.Day != targetDay) { _logger.LogInformation("跳过"); return; } //B币券余额 decimal couponBalance = userInfo.Wallet.Coupon_balance; _logger.LogInformation("【B币券】{couponBalance}", couponBalance); if (couponBalance < 2) { _logger.LogInformation("余额小于2,无法充电"); return; } string targetUpId = _dailyTaskOptions.AutoChargeUpId; //如果没有配置或配了-1,则为自己充电 if (_dailyTaskOptions.AutoChargeUpId.IsNullOrEmpty() | _dailyTaskOptions.AutoChargeUpId == "-1") { targetUpId = _cookie.UserId; } _logger.LogDebug("【目标Up】{up}", targetUpId); var request = new ChargeRequest(couponBalance, long.Parse(targetUpId), _cookie.BiliJct); //BiliApiResponse<ChargeResponse> response = _chargeApi.Charge(decimal.ToInt32(couponBalance * 10), _dailyTaskOptions.AutoChargeUpId, _cookieOptions.UserId, _cookieOptions.BiliJct).Result; BiliApiResponse <ChargeV2Response> response = _chargeApi.ChargeV2(request) .GetAwaiter().GetResult(); if (response.Code == 0) { if (response.Data.Status == 4) { _logger.LogInformation("【充电结果】成功"); _logger.LogInformation("【充值个数】 {num}个B币", couponBalance); _logger.LogInformation("经验+{exp} √", couponBalance); _logger.LogInformation("在过期前使用成功,赠送的B币券没有浪费哦~", targetUpId, couponBalance); //充电留言 ChargeComments(response.Data.Order_no); } else { _logger.LogInformation("【充电结果】失败"); _logger.LogError("【原因】{reason}", response.ToJson()); } } else { _logger.LogInformation("【充电结果】失败"); _logger.LogError("【原因】{reason}", response.Message); } }
public async Task <ChargeResponse> FraudCheck(ChargeRequest request) { return(await _serviceHelper.Post <ChargeResponse, ChargeRequest>(request, "charges/fraud", overrideConfigSecretKey : _overrideConfigSecretKey)); }
public async Task <WalletResponse> InitializeWallet(ChargeRequest request) { return(await _serviceHelper.Post <WalletResponse, ChargeRequest>(request, "charges/wallet", overrideConfigSecretKey : _overrideConfigSecretKey)); }
private void OnTransactionSuccess (ChargeRequest.Success successResult) { var message = Html.FromHtml( "<b><font color='#00aa00'>Success</font></b><br><br>" + "<b>Client RealTransaction Id</b><br>" + successResult.ClientTransactionId + "<br><br><b>Server RealTransaction Id</b><br>" + successResult.ServerTransactionId + "<br><br><b>Request Metadata</b><br>" + successResult.RequestMetadata).ToString(); ShowResult(message); System.Diagnostics.Debug.WriteLine(message); }
/// <summary> /// Create request parameters to charge transaction /// </summary> /// <param name="paymentRequest">Payment request parameters</param> /// <param name="isRecurringPayment">Whether it is a recurring payment</param> /// <returns>Charge request parameters</returns> private ChargeRequest CreateChargeRequest(ProcessPaymentRequest paymentRequest, bool isRecurringPayment) { //get customer var customer = _customerService.GetCustomerById(paymentRequest.CustomerId); if (customer == null) { throw new NopException("Customer cannot be loaded"); } //whether USD is available var usdCurrency = _currencyService.GetCurrencyByCode("USD"); if (usdCurrency == null) { throw new NopException("USD currency cannot be loaded"); } //create common charge request parameters var request = new ChargeRequest { OrderId = CommonHelper.EnsureMaximumLength(paymentRequest.OrderGuid.ToString(), 25), TransactionDuplicateCheckType = TransactionDuplicateCheckType.NoCheck, ExtendedInformation = new ExtendedInformation { InvoiceNumber = paymentRequest.OrderGuid.ToString(), InvoiceDescription = $"Order from the '{_storeService.GetStoreById(paymentRequest.StoreId)?.Name}'" } }; //set amount in USD var amount = _currencyService.ConvertFromPrimaryStoreCurrency(paymentRequest.OrderTotal, usdCurrency); request.Amount = Math.Round(amount, 2); //get current shopping cart var shoppingCart = customer.ShoppingCartItems .Where(shoppingCartItem => shoppingCartItem.ShoppingCartType == ShoppingCartType.ShoppingCart) .LimitPerStore(paymentRequest.StoreId).ToList(); //whether there are non-downloadable items in the shopping cart var nonDownloadable = shoppingCart.Any(item => !item.Product.IsDownload); request.ExtendedInformation.GoodsType = nonDownloadable ? GoodsType.Physical : GoodsType.Digital; //try to get previously stored card details var storedCardKey = _localizationService.GetResource("Plugins.Payments.Worldpay.Fields.StoredCard.Key"); if (paymentRequest.CustomValues.TryGetValue(storedCardKey, out object storedCardId) && !storedCardId.ToString().Equals(Guid.Empty.ToString())) { //check whether customer exists in Vault var vaultCustomer = _worldpayPaymentManager.GetCustomer(customer.GetAttribute <string>(WorldpayPaymentDefaults.CustomerIdAttribute)) ?? throw new NopException("Failed to retrieve customer"); //use previously stored card to charge request.PaymentVaultToken = new VaultToken { CustomerId = vaultCustomer.CustomerId, PaymentMethodId = storedCardId.ToString() }; return(request); } //or try to get the card token var cardTokenKey = _localizationService.GetResource("Plugins.Payments.Worldpay.Fields.Token.Key"); if (!paymentRequest.CustomValues.TryGetValue(cardTokenKey, out object token) || string.IsNullOrEmpty(token?.ToString())) { throw new NopException("Failed to get the card token"); } //remove the card token from payment custom values, since it is no longer needed paymentRequest.CustomValues.Remove(cardTokenKey); //public key is required to pay with card token request.PaymentVaultToken = new VaultToken { PublicKey = _worldpayPaymentSettings.PublicKey }; //whether to save card details for the future purchasing var saveCardKey = _localizationService.GetResource("Plugins.Payments.Worldpay.Fields.SaveCard.Key"); if (paymentRequest.CustomValues.TryGetValue(saveCardKey, out object saveCardValue) && saveCardValue is bool saveCard && saveCard && !customer.IsGuest()) { //remove the value from payment custom values, since it is no longer needed paymentRequest.CustomValues.Remove(saveCardKey); try { //check whether customer exists and try to create the new one, if not exists var vaultCustomer = _worldpayPaymentManager.GetCustomer(customer.GetAttribute <string>(WorldpayPaymentDefaults.CustomerIdAttribute)) ?? _worldpayPaymentManager.CreateCustomer(new CreateCustomerRequest { CustomerId = customer.Id.ToString(), CustomerDuplicateCheckType = CustomerDuplicateCheckType.Ignore, EmailReceiptEnabled = !string.IsNullOrEmpty(customer.Email), Email = customer.Email, FirstName = customer.GetAttribute <string>(SystemCustomerAttributeNames.FirstName), LastName = customer.GetAttribute <string>(SystemCustomerAttributeNames.LastName), Company = customer.GetAttribute <string>(SystemCustomerAttributeNames.Company), Phone = customer.GetAttribute <string>(SystemCustomerAttributeNames.Phone), BillingAddress = new Address { Line1 = customer.BillingAddress?.Address1, City = customer.BillingAddress?.City, State = customer.BillingAddress?.StateProvince?.Abbreviation, Country = customer.BillingAddress?.Country?.TwoLetterIsoCode, Zip = customer.BillingAddress?.ZipPostalCode, Company = customer.BillingAddress?.Company, Phone = customer.BillingAddress?.PhoneNumber } }) ?? throw new NopException("Failed to create customer. Error details in the log"); //save Vault customer identifier as a generic attribute _genericAttributeService.SaveAttribute(customer, WorldpayPaymentDefaults.CustomerIdAttribute, vaultCustomer.CustomerId); //add card to the Vault after charge request.AddToVault = true; request.PaymentVaultToken.CustomerId = vaultCustomer.CustomerId; } catch (Exception exception) { _logger.Warning(exception.Message, exception, customer); if (isRecurringPayment) { throw new NopException("For recurring payments you need to save the card details"); } } }
private void OnTransactionError (ChargeRequest.Error errorResult) { var message = Html.FromHtml( "<b><font color='#aa0000'>Error</font></b><br><br>" + "<b>Error Key</b><br>" + errorResult.Code + "<br><br><b>Error Description</b><br>" + errorResult.DebugDescription + "<br><br><b>Request Metadata</b><br>" + errorResult.RequestMetadata).ToString(); ShowResult(message); System.Diagnostics.Debug.WriteLine(message); }