/// <summary> /// Makes HttpRequest to mpesa api server /// </summary> /// <param name="Dto">Data transfer object</param> /// <param name="token">Mpesa Accesstoken</param> /// <param name="Endpoint">Request endpoint</param> /// <param name="cancellationToken">Cancellation Token</param> /// <returns>Mpesa API response</returns> private async Task <string> MpesaHttpRequest(object Dto, string token, string Endpoint, CancellationToken cancellationToken = default) { HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, Endpoint) { Content = new StringContent(JsonConvert.SerializeObject(Dto).ToString(), Encoding.UTF8, "application/json") }; request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", token); cancellationToken.ThrowIfCancellationRequested(); HttpResponseMessage response = await _httpclient.SendAsync(request, cancellationToken); var content = await response.Content.ReadAsStreamAsync(); var data = JSONStreamHelper.DeserializeFromStream(content); var strData = JsonConvert.SerializeObject(data); if (response.IsSuccessStatusCode == false) { throw new MpesaApiException { StatusCode = (int)response.StatusCode, Content = strData }; } return(strData); }
/// <summary> /// Method makes the accesstoken request to mpesa api /// </summary> /// <param name="consumerKey"></param> /// <param name="consumerSecret"></param> /// <param name="requestEndPoint"></param> /// <param name="cancellationToken">Cancellation Token</param> /// <returns>string representing accesstoken</returns> private async Task <string> RequestAccessToken(string consumerKey, string consumerSecret, string requestEndPoint, CancellationToken cancellationToken = default) { var keyBytes = Convert.ToBase64String(Encoding.UTF8.GetBytes($"{consumerKey}:{consumerSecret}")); HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, requestEndPoint); request.Headers.Authorization = new AuthenticationHeaderValue("Basic", keyBytes); cancellationToken.ThrowIfCancellationRequested(); var response = await _httpclient.SendAsync(request, cancellationToken); var content = await response.Content.ReadAsStreamAsync(); var data = JSONStreamHelper.DeserializeFromStream(content); var strData = JsonConvert.SerializeObject(data); if (response.IsSuccessStatusCode == false) { throw new MpesaApiException { StatusCode = (int)response.StatusCode, Content = strData }; } return(JsonConvert.DeserializeObject <TokenResponse>(strData).AccessToken); }