public async Task <Transaction> Charge(ChargeOptions chargeOptions, UserWallet wallet) { var requestUri = HttpContext.Current.Request.Url; var response = await httpClient.PostAsJsonAsync($"merchants/{this.merchantAccountId}/send/mobilemoney", new ReceiveModel() { Amount = chargeOptions.Amount, Token = chargeOptions.AdditionalToken, CustomerEmail = chargeOptions.Email, Channel = ResolveChannel(wallet.Provider), ClientReference = chargeOptions.RefLocal, CustomerMsisdn = FixPhone(wallet.Value), CustomerName = chargeOptions.Name, Description = chargeOptions.Description ?? "Pay for booked reservation", PrimaryCallbackUrl = $"{requestUri.Scheme}://{requestUri.Authority}/{Handlers.HubtelPaymentHandler.CallbackUrl}", FeesOnCustomer = chargeOptions.FeesOnCustomer ?? true }); if (response.IsSuccessStatusCode) { var body = await response.Content.ReadAsAsync <ResponseModel>(); return(new Transaction() { ChargedAmount = body.Data.AmountCharged, FinalAmount = body.Data.AmountAfterCharges, IdealAmount = chargeOptions.Amount, Message = body.Data.Description, RefExternal = body.Data.TransactionId, RefLocal = chargeOptions.RefLocal, Status = IsSuccessfulResponse(body.ResponseCode) ? TransactionStatus.Initiated : TransactionStatus.Unknown, Type = TransactionType.Charge, Wallet = wallet }); } else { return(new Transaction() { RefLocal = chargeOptions.RefLocal, ChargedAmount = 0, FinalAmount = 0, IdealAmount = chargeOptions.Amount, Status = TransactionStatus.Failed, Type = TransactionType.Charge, Message = $"Server didn't return successful status code: {response.ReasonPhrase}", Meta = JsonConvert.SerializeObject(new { Response = await response.Content.ReadAsStringAsync(), StatusCode = response.StatusCode }), Wallet = wallet }); } }
public void TestInitialize() { _defaultChargeOptions = new ChargeOptions() { Method = new CardOptions() { Name = "FirstName LastName", Address1 = "123 Main St.", Address2 = "Apt #3", City = "Austin", State = "TX", PostalCode = "78759", Number = "4111111111111111", Cvv = "123", ExpMonth = 3, ExpYear = 2020 } }; _rand = new Random().Next().ToString(); _transactionService = new TransactionService(); _paymentMethodService = new PaymentMethodService(); }
public async Task <Transaction> Charge(ChargeOptions options, UserWallet wallet) { HttpResponseMessage response = null; string requestContentBase64String = string.Empty; string requestUri = HttpUtility.UrlEncode(""); HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, requestUri); string requestHttpMethod = request.Method.Method; //Calculate UNIX time DateTime epochStart = new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc); TimeSpan timeSpan = DateTime.UtcNow - epochStart; string requestTimeStamp = Convert.ToUInt64(timeSpan.TotalSeconds).ToString(); //create random nonce for each request string nonce = Guid.NewGuid().ToString("N"); string merchantRef = $"BST-{Guid.NewGuid().ToString("N")}"; ChargeInfo cInfo = new ChargeInfo() { Amount = options.Amount, TxnMode = 1, TxnType = "DR", MerchantTxnRef = merchantRef, OrderTxnRef = options.RefLocal, PhoneNumber = FormatPhoneNumber(wallet.Value), TxnWallet = ResolveOperator(wallet) }; string rawContent = JsonConvert.SerializeObject(cInfo); request.Content = new StringContent(rawContent, Encoding.UTF8, "application/json"); //Checking if the request contains body, usually will be null with HTTP GET and DELETE if (request.Content != null) { var stringToHash = await request.Content.ReadAsStringAsync(); System.Diagnostics.Debug.WriteLine($"Request Content: {stringToHash}"); var hasher = MD5.Create(); var HashValue = hasher.ComputeHash(Encoding.ASCII.GetBytes(stringToHash)); requestContentBase64String = string.Join("", HashValue.Select(b => b.ToString("x2"))); } //Creating the raw signature string string signatureRawData = String.Format("{0}{1}{2}{3}{4}{5}", appId, requestHttpMethod, requestUri, requestTimeStamp, nonce, requestContentBase64String); string requestSignatureBase64String = CreateToken(signatureRawData, apiKey); string authHeader = string.Format("{0}:{1}:{2}:{3}", appId, requestSignatureBase64String, nonce, requestTimeStamp); request.Headers.Authorization = new AuthenticationHeaderValue("amx", authHeader); try { using (var client = new HttpClient()) { response = await client.SendAsync(request); // get charge response from server response ChargeResponse chargeResponse = JsonConvert.DeserializeObject <ChargeResponse>(await response.Content.ReadAsStringAsync()); return(new Transaction() { Type = TransactionType.Charge, ChargedAmount = 0, Status = (response.IsSuccessStatusCode && chargeResponse?.StatusCode == "010") ? TransactionStatus.Successful : TransactionStatus.Failed, RefLocal = options.RefLocal, Wallet = wallet, IdealAmount = options.Amount, FinalAmount = options.Amount, DateCompleted = DateTime.UtcNow, Message = chargeResponse.Message, RefExternal = merchantRef, }); } } catch (HttpRequestException) { return(new Transaction() { Status = TransactionStatus.Failed, Message = "An exception occured while processing transaction", Wallet = wallet }); } }
public async Task <Transaction> Charge(ChargeOptions options, UserWallet wallet) { var orderItems = new OrderItem[] { new OrderItem() { ItemCode = "TKT", ItemName = "Bus Ticket", Quantity = (int)options.TotalSeats, UnitPrice = (decimal)options.UnitSeatCost, SubTotal = (decimal)options.Amount } }; try { if (IsIntegrationMode) { return(new Transaction() { ChargedAmount = 0, FinalAmount = options.Amount, IdealAmount = options.Amount, RefExternal = Guid.NewGuid().ToString("N"), Message = "Payment was successfull", Status = TransactionStatus.Successful, DateCompleted = DateTime.UtcNow, Wallet = wallet, RefLocal = options.RefLocal, Type = TransactionType.Charge, }); } else { var result = await Task.Run(() => client.mobilePaymentOrder(options.RefLocal, (decimal)options.Amount, true, 0, true, 0, true, (decimal)options.Amount, true, "Payment for bus ticket", "", orderItems)); return(new Transaction() { ChargedAmount = 0, FinalAmount = options.Amount, IdealAmount = options.Amount, RefExternal = result.token, Message = result.status, Status = result.success ? TransactionStatus.Initiated : TransactionStatus.Failed, DateCompleted = result.success ? (DateTime?)null : DateTime.UtcNow, Wallet = wallet, RefLocal = options.RefLocal, Type = TransactionType.Charge, }); } } catch (Exception ex) { return(new Transaction() { DateCompleted = DateTime.UtcNow, ChargedAmount = 0, FinalAmount = 0, IdealAmount = options.Amount, RefExternal = null, RefLocal = options.RefLocal, Wallet = wallet, Message = ex.Message, Status = TransactionStatus.Failed, Type = TransactionType.Charge }); } }