public ChargeServiceTests() { _service = new StartChargeService("test_sec_k_8512e94e69d6a46c67ab2"); _customerService = new StartCustomerService("test_sec_k_8512e94e69d6a46c67ab2"); _tokenService = new StartTokenService("test_open_k_956a1de10dba98935041"); _iPAddress = "127.0.0.1"; _workingCard = new Card() { Name = "Abdullah Ahmed", Cvc = 123, ExpireMonth = 12, ExpireYear = 2020, Number = "4242424242424242" }; _createTokenRequest = new CreateTokenRequest(_workingCard); _createChargeRequest = new CreateChargeRequest() { Amount = 10000, Currency = Currency.AED, Email = "*****@*****.**", Ip = _iPAddress }; }
public ChargeServiceTests(string _iPAddress) { _service = new StartChargeService("test_sec_k_8512e94e69d6a46c67ab2"); _customerService = new StartCustomerService("test_sec_k_8512e94e69d6a46c67ab2"); _tokenService = new StartTokenService("test_open_k_3gfew76877gy689798hc86a4"); _workingCard = new Card() { Name = "Abdullah Ahmed", Cvc = 123, ExpireMonth = 12, ExpireYear = 2020, Number = "4242424242424242" }; _createTokenRequest = new CreateTokenRequest() { Number = "4242424242424242", Exp_Month = 12, Exp_Year = 2020, Cvc = "123", Name = "Abdullah Ahmed" }; _createChargeRequest = new CreateChargeRequest() { Amount = 10000, Currency = Currency.AED, Email = "*****@*****.**", Ip = _iPAddress }; }
public async Task Validate_InputValidation(string idempotentKey, double amount, string currency, string description, string cardNumber, string cvv, int expiryMonth, int expiryYear) { // Arrange var request = new CreateChargeRequest { IdempotentKey = idempotentKey, Amount = (decimal)amount, Currency = currency, Description = description, CardNumber = cardNumber, Cvv = cvv, ExpiryMonth = expiryMonth, ExpiryYear = expiryYear }; var serialized = JsonSerializer.Serialize(request); using var content = new StringContent(serialized, Encoding.UTF8, "application/json"); // Act using var response = await _client.PostAsync("api/charges", content); // Assert Assert.IsNotNull(response); Assert.AreEqual(HttpStatusCode.BadRequest, response.StatusCode); }
public async Task Request_With_Invalid_ApiKey_Returns_Unauthorized() { // Arrange // Remove the ApiKey header so that auth fails. _client.DefaultRequestHeaders.Remove("X-Api-Key"); _client.DefaultRequestHeaders.Add("X-Api-Key", "invalid key"); var request = new CreateChargeRequest { IdempotentKey = "111", Amount = 1.0m, Currency = "USD", Description = null, CardNumber = "1234567890123452", Cvv = "111", ExpiryMonth = 1, ExpiryYear = 2020 }; var serialized = JsonSerializer.Serialize(request); using var content = new StringContent(serialized, Encoding.UTF8, "application/json"); // Act using var response = await _client.PostAsync("api/charges", content); // Assert Assert.IsNotNull(response); Assert.AreEqual(HttpStatusCode.Unauthorized, response.StatusCode); }
public async Task <int> CreateChargeAsync(CreateChargeRequest chargeRequest) { var charge = chargeRequest.ToDTO(); await _chargeManager.InsertChargeAsync(charge).ConfigureAwait(false); return(charge.Id); }
public async Task <IActionResult> AddCharge([FromRoute] int buildingId, [FromBody] CreateChargeRequest charge) { charge.BuildingId = buildingId; var id = await _chargeApplicationService.CreateChargeAsync(charge); return(Ok(id)); }
public async Task <IActionResult> Post([FromBody] CreateChargeRequest request) { // Note that explicitly checking ModelState is not required for controllers with the [ApiController] // attribute, so there is no code here for that here. var entity = new Charge { IdempotentKey = request.IdempotentKey, CreatedOn = DateTimeOffset.UtcNow, Status = ChargeStatus.Pending, Amount = request.Amount, Currency = request.Currency, Description = request.Description, CardNumber = request.CardNumber, Cvv = request.Cvv, ExpiryMonth = request.ExpiryMonth, ExpiryYear = request.ExpiryYear }; _db.Charges.Add(entity); try { await _db.SaveChangesAsync(); } catch (DbUpdateException exception) when(exception.IsViolationOfUniqueIndex()) { // This handles the case where someone is double-posting a charge with the same IdempotentKey. _logger.LogWarning("A charge with idempotency key {IdempotentKey} attempted to double post.", request.IdempotentKey); return(Conflict()); } var acquiringBankRequest = new AcquiringBankRequest { Amount = entity.Amount, Currency = entity.Currency, CardNumber = entity.CardNumber, Cvv = entity.Cvv, ExpiryMonth = entity.ExpiryMonth, ExpiryYear = entity.ExpiryYear }; var success = await _bank.TrySendAsync(acquiringBankRequest, out var bankChargeId); if (!success) { _logger.LogError("The acquiring bank for charge id {Id} rejected the payment.", entity.Id); } entity.Status = success ? ChargeStatus.Success : ChargeStatus.Failed; entity.BankChargeId = bankChargeId; await _db.SaveChangesAsync(); var result = new GetChargeResponse(entity); return(CreatedAtAction("Get", new { id = entity.Id }, result)); }
public BaseResponse <GetChargeResponse> CreateCharge(string idempotencyKey, CreateChargeRequest request) { var method = HttpMethod.Post; var endpoint = $"/charges"; var headers = this.GetIdempontecyAsHeader(idempotencyKey); return(this.HttpClientUtil.SendRequest <GetChargeResponse>(method, endpoint, request, null, headers)); }
/// <summary> /// Charges the buyer using the ChargePermission generated by the MerchantScan call. /// </summary> /// <param name="chargeRequest"></param> /// <param name="headers"></param> /// <returns>AmazonPayResponse response</returns> public ChargeResponse Charge(CreateChargeRequest chargeRequest, Dictionary <string, string> headers = null) { var chargeUri = apiUrlBuilder.BuildFullApiPath(Constants.ApiServices.InStore, Constants.Resources.InStore.Charge); var apiRequest = new ApiRequest(chargeUri, HttpMethod.POST, chargeRequest, headers); var result = CallAPI <ChargeResponse>(apiRequest); return(result); }
public void ChargesCreateTest() { // TODO uncomment below to test the method and replace null with proper value CreateChargeRequest body = null; string idempotencyKey = null; var response = instance.ChargesCreate(body, idempotencyKey); Assert.IsInstanceOf <Charge> (response, "response is Charge"); }
public static ChargeDTO ToDTO(this CreateChargeRequest chargeRequest) { var dto = new ChargeDTO { BuildingId = chargeRequest.BuildingId, From = chargeRequest.From, To = chargeRequest.To }; return(dto); }
public async Task ChargesCreateCreateWithCustomer() { var request = new CreateChargeRequest { Amount = 100000, // THB 1,000.00 Currency = "THB", Customer = "cust_test_52ydv7e3ao0oqwjj97e", }; var charge = await Client.Charges.Create(request); Assert.AreEqual(100000, charge.Amount); }
public async Task ChargesCreateCreateWithToken() { var request = new CreateChargeRequest { Amount = 100000, // THB 1,000.00 Currency = "THB", Card = "tokn_test_4xs9408a642a1htto8z", }; var charge = await Client.Charges.Create(request); Assert.AreEqual(100000, charge.Amount); }
public async Task Charge_Written_To_Db_With_Bank_Status(bool bankReturnStatus, ChargeStatus expectedStatus) { // Arrange var s = "bankChargeId"; _bank.Setup(o => o.TrySendAsync(It.IsAny <AcquiringBankRequest>(), out s)).ReturnsAsync(bankReturnStatus); var request = new CreateChargeRequest { IdempotentKey = "111", Amount = 1.0m, Currency = "USD", Description = null, CardNumber = "1234567890123452", Cvv = "111", ExpiryMonth = 1, ExpiryYear = 2020 }; var serialized = JsonSerializer.Serialize(request); using var content = new StringContent(serialized, Encoding.UTF8, "application/json"); // Act using var response = await _client.PostAsync("api/charges", content); // Assert Assert.IsNotNull(response); Assert.AreEqual(HttpStatusCode.Created, response.StatusCode); using var responseStream = await response.Content.ReadAsStreamAsync(); var responseCharge = await JsonSerializer.DeserializeAsync <GetChargeResponse>(responseStream); var dbCharge = await _db.Charges.FindAsync(responseCharge.Id); Assert.IsNotNull(dbCharge); Assert.AreEqual(request.IdempotentKey, dbCharge.IdempotentKey); Assert.AreEqual(request.Amount, dbCharge.Amount); Assert.AreEqual(request.Currency, dbCharge.Currency); Assert.AreEqual(request.Description, dbCharge.Description); Assert.AreEqual(request.CardNumber, dbCharge.CardNumber); Assert.AreEqual(request.Cvv, dbCharge.Cvv); Assert.AreEqual(request.ExpiryMonth, dbCharge.ExpiryMonth); Assert.AreEqual(request.ExpiryYear, dbCharge.ExpiryYear); Assert.AreEqual(expectedStatus, dbCharge.Status); Assert.AreEqual(s, dbCharge.BankChargeId); }
public async Task <Charge> CreateAsync(CreateChargeRequest request) { if (request is null) { throw new ArgumentNullException(nameof(request)); } using var content = new JsonHttpContent <CreateChargeRequest>(request); using var response = await _client.PostAsync("api/charges", content).ConfigureAwait(false); using var stream = await response.Content.ReadAsStreamAsync().ConfigureAwait(false); var result = await JsonSerializer.DeserializeAsync <Charge>(stream).ConfigureAwait(false); return(result); }
public async Task Charge_Returned_When_Posted() { // Arrange var request = new CreateChargeRequest { IdempotentKey = "111", Amount = 1.0m, Currency = "USD", Description = null, CardNumber = "1234567890123452", Cvv = "111", ExpiryMonth = 1, ExpiryYear = 2020 }; var serialized = JsonSerializer.Serialize(request); using var content = new StringContent(serialized, Encoding.UTF8, "application/json"); // Act using var response = await _client.PostAsync("api/charges", content); // Assert Assert.IsNotNull(response); Assert.AreEqual(HttpStatusCode.Created, response.StatusCode); using var responseStream = await response.Content.ReadAsStreamAsync(); var responseCharge = await JsonSerializer.DeserializeAsync <GetChargeResponse>(responseStream); Assert.AreEqual(request.IdempotentKey, responseCharge.IdempotentKey); Assert.AreEqual(request.Amount, responseCharge.Amount); Assert.AreEqual(request.Currency, responseCharge.Currency); Assert.AreEqual(request.Description, responseCharge.Description); Assert.AreEqual("************3452", responseCharge.CardNumber); var location = response.Headers.Location; Assert.AreEqual($"/api/charges?id={responseCharge.Id}", location.PathAndQuery); }
public void CanConvertToJsonFull() { // arrange var chargePermissionId = "S02-7331650-8246451"; var request = new CreateChargeRequest(chargePermissionId, 12.99M, Currency.EUR); request.ProviderMetadata.ProviderReferenceId = "foo"; request.SoftDescriptor = "foo"; request.CaptureNow = true; request.CanHandlePendingAuthorization = true; // act string json = request.ToJson(); string json2 = request.ToJson(); // assert Assert.AreEqual(json, json2); Assert.AreEqual("{\"chargePermissionId\":\"S02-7331650-8246451\",\"chargeAmount\":{\"amount\":12.99,\"currencyCode\":\"EUR\"},\"captureNow\":true,\"softDescriptor\":\"foo\",\"canHandlePendingAuthorization\":true,\"providerMetadata\":{\"providerReferenceId\":\"foo\"}}", json); }
internal static CreateChargeRequest BuildCreateChargeRequest(string paymentMethod = "credit_card", int amount = 100, bool capture = true) { var request = new CreateChargeRequest(); request.Amount = amount; request.Code = Guid.NewGuid().ToString().Substring(0, 6); request.Customer = new CreateCustomerRequest() { Name = "Vitor de Andrade", Email = "*****@*****.**" }; request.Payment = new CreatePaymentRequest() { PaymentMethod = paymentMethod, }; switch (paymentMethod) { case "boleto": break; case "credit_card": request.Payment.CreditCard = new CreateCreditCardPaymentRequest() { CreditCardInfo = new CreateCreditCardRequest() { Number = "4556604245849434", HolderName = "VITOR DE ANDRADE", Cvv = "123", ExpMonth = 12, ExpYear = 21 }, StatementDescriptor = "STATEMENT TEST", Installments = 3, Capture = capture }; break; } return(request); }
public void CanConstructWithAllPropertiesInitializedAsExpected() { // arrange var chargePermissionId = "S02-7331650-8246451"; // act var request = new CreateChargeRequest(chargePermissionId, 12.99M, Currency.EUR); // assert Assert.IsNotNull(request); Assert.IsNotNull(request.ChargePermissionId); Assert.IsNotNull(request.ChargeAmount); Assert.AreEqual(12.99, request.ChargeAmount.Amount); Assert.AreEqual(Currency.EUR, request.ChargeAmount.CurrencyCode); Assert.IsNotNull(request.ProviderMetadata); Assert.IsNotNull(request.MerchantMetadata); Assert.IsNull(request.CanHandlePendingAuthorization); Assert.IsNull(request.CaptureNow); Assert.IsNull(request.SoftDescriptor); }
public ChargeServiceTests() { _service = new StartChargeService("test_sec_k_8512e94e69d6a46c67ab2"); _customerService = new StartCustomerService("test_sec_k_8512e94e69d6a46c67ab2"); _workingCard = new Card() { Name = "Abdullah Ahmed", Cvc = 123, ExpireMonth = 12, ExpireYear = 2020, Number = "4242424242424242" }; _createChargeRequest = new CreateChargeRequest() { Amount = 10000, Currency = Currency.AED, Email = "*****@*****.**" }; }
public static CreateChargeResponse InvokeRestApi(string customerId, long amount, TimeSpan?timeout = null) { Console.WriteLine(DateTime.Now.ToString("HH:mm:ss.fff") + " INVOKE STRIPE"); var createChargeRequest = new CreateChargeRequest(); createChargeRequest.amount = amount; HttpClient client = new HttpClient(); if (timeout != null) { client.Timeout = timeout.Value; } var httpResponse = client.PostAsync(STRIPE_CHARGE_URL, new StringContent(JsonConvert.SerializeObject(createChargeRequest), Encoding.UTF8, "application/json")).Result; httpResponse.EnsureSuccessStatusCode(); return(JsonConvert.DeserializeObject <CreateChargeResponse>(httpResponse.Content.ReadAsStringAsync().Result)); }
public IActionResult RetrievePayment([FromBody] CreateChargeRequest request) { CreateChargeResponse response = new CreateChargeResponse(); int waitTimeMillis = 0; if (slow) { waitTimeMillis = random.Next(0, 60) * 1000; } if (random.NextDouble() > 0.8d) { response.errorCode = "Credit card expired"; } Console.WriteLine("Charge on credit card will take " + waitTimeMillis / 1000 + " seconds"); Thread.Sleep(waitTimeMillis); response.transactionId = Guid.NewGuid().ToString(); return(Ok(response)); }
private async Task <Charge> ChargeCustomer(string omiseCustId, string omiseCardId, double amount, string urlComplete = null) { try { var request = new CreateChargeRequest { Amount = (long)(amount * 100), Currency = "THB", Customer = omiseCustId, Card = omiseCardId, ReturnUri = urlComplete }; var charge = await client.Charges.Create(request); return(charge); } catch (Exception) { throw; } }
internal static string CreateCharge(IMundiAPIClient client, CreateChargeRequest request) { try { var response = client.Charges.CreateCharge(request); FileHelper.SaveResponse(response, $"CREATE{request.Payment.PaymentMethod.ToUpper()}CHARGE"); return(response.Id); } catch (ErrorException e) { FileHelper.SaveApiError(e, $"CREATE{request.Payment.PaymentMethod.ToUpper()}CHARGE"); return(null); } catch (Exception e) { FileHelper.SaveException(e, $"CREATE{request.Payment.PaymentMethod.ToUpper()}CHARGE"); return(null); } }
public void CanConvertToJsonRecurring() { // arrange var chargePermissionId = "S02-7331650-8246451"; var request = new CreateChargeRequest(chargePermissionId, 12.99M, Currency.EUR); request.ProviderMetadata.ProviderReferenceId = "foo1"; request.SoftDescriptor = "foo2"; request.CaptureNow = true; request.CanHandlePendingAuthorization = true; request.MerchantMetadata.MerchantReferenceId = "123abc!"; request.MerchantMetadata.MerchantStoreName = "My Store Name"; request.MerchantMetadata.NoteToBuyer = "My Note to Buyer"; request.MerchantMetadata.CustomInformation = "My Custom Info"; // act string json = request.ToJson(); string json2 = request.ToJson(); // assert Assert.AreEqual(json, json2); Assert.AreEqual("{\"chargePermissionId\":\"S02-7331650-8246451\",\"chargeAmount\":{\"amount\":12.99,\"currencyCode\":\"EUR\"},\"captureNow\":true,\"softDescriptor\":\"foo2\",\"canHandlePendingAuthorization\":true,\"providerMetadata\":{\"providerReferenceId\":\"foo1\"},\"merchantMetadata\":{\"merchantReferenceId\":\"123abc!\",\"merchantStoreName\":\"My Store Name\",\"noteToBuyer\":\"My Note to Buyer\",\"customInformation\":\"My Custom Info\"}}", json); }
public int Add(CreateChargeRequest request) { int count = 0; try { bx_charge item = new bx_charge() { charge_type = request.ChargeType, total_price = request.TotalPrice, unit_price = request.UnitPirce, used_count = 0, agent = request.Agent }; count = _chargeRepository.Add(item); logInfo.Info("创建消费用户成功:" + item.ToJson()); } catch (Exception ex) { logError.Info("创建消费用户发生异常:" + ex.Source + "\n" + ex.StackTrace + "\n" + ex.Message + "\n" + ex.InnerException); } return(count); }
public async Task <IActionResult> UpdateCharge([FromRoute] int chargeId, [FromRoute] int buildingId, [FromBody] CreateChargeRequest charge) { charge.BuildingId = buildingId; await _chargeApplicationService.UpdateChargeAsync(chargeId, charge); return(Ok()); }
//a rotina é um timer de 100ms para monitorar a porta de comunicação (COM4) ao aguardo de uma TAG RFID. //Quando chegar um conjunto de 40bits for redebido nessa porta, tal informação será armazenada na variavel X1 private void Timer1_Tick(object sender, EventArgs e) { String x1 = ""; if (serialPort1.IsOpen) { comando.Connection = conn; // parametro para banco de dados x1 = serialPort1.ReadExisting(); } //A rotina abaixo verifica se a variavel x1 recebeu a instrução da tag de 40bits atravez da porta COM4. //caso X1 ainda tenha o valor null continuará presa em um lopp aguardando TAG e essa tag será verificada novamente a cada //100ms devido ao timer implementado em "void Timer1_Tick" if (x1 != "") { //Assim que for feita a leitura de uma TAG RFID na porta serial emulada a variavel X1 assume o valor dessa TAG, afim de que seja //realizado um select no bando de dados em busda id do cliente relacionado. conn.Open(); comando.CommandText = "select id from pessoa where RFID = '" + x1 + "'"; comando.ExecuteScalar(); SqlDataReader dr = comando.ExecuteReader(); dr.Read(); var idcliente = Convert.ToString(dr["id"]); conn.Close(); x1 = ""; textBox1.Text = ""; textBox1.AppendText(idcliente); //A rotina abaixo realiza a consulta na base de dados da mundipagg, atravez do Id do cliente(carregada na variavel cachorrinho), //retornando os dados de nome, email,... string basicAuthUserName = "******"; string basicAuthPassword = ""; var client = new MundiAPIClient(basicAuthUserName, basicAuthPassword); var response1 = client.Customers.GetCustomer(idcliente); textBox3.Text = response1.Name; textBox4.Text = response1.Email; textBox5.Text = response1.Type; conn.Open(); comando.CommandText = "UPDATE pessoa SET email = '" + response1.Email + "', name = '" + response1.Name + "' WHERE id = '" + idcliente + "'"; comando.ExecuteNonQuery(); conn.Close(); //a etapa abaixo sera de requeisitar dados do cartão passando o id do cliente. //aqui seria realizado a busca dos dados do cartão do cliente, mas nao consegui informação de como trabalhar com os dados //que receber dentro da String response2 // var response2 = client.Customers.GetCards(idcliente); if (checkBox1.Checked) { var valor = textBox8.Text; var cart = textBox9.Text; var request = new CreateChargeRequest() { Amount = Convert.ToInt32(valor), CustomerId = idcliente, Payment = new CreatePaymentRequest() { PaymentMethod = "credit_card", CreditCard = new CreateCreditCardPaymentRequest() { //colocar proteção de if CardId = cart, Card = new CreateCardRequest { Cvv = "353", } } } }; { try { var response = client.Charges.CreateCharge(request); textBox6.Text = response.Status; textBox5.Text = response.Id; checkBox1.Checked = false; } catch { MessageBox.Show("Esse Cartão não pertence ao cliente " + textBox3.Text + ". Por favor altere os dados"); textBox9.Focus(); } } } } }
public ApiResponse <Charge> CreateCharge(CreateChargeRequest request) { ApiResponse <Charge> response = SendApiRequest <CreateChargeRequest, Charge>(request); return(response); }
public async Task UpdateChargeAsync(int chargeId, CreateChargeRequest charge) { await _chargeManager.UpdateChargeAsync(chargeId, charge.ToDTO()); }