For a more in depth and other programming language samples, download the Sample Client Install

C# Copy imageCopy
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Net;
using System.Net.Http;
using System.Text;

namespace FaxWSConsoleApplication
{
    public static class GetFaxStatusJsonClass
    {
        const string oauthUrl = "https://login.concord.net/v1/connect/token";
        const string faxWSUrl = "https://ws.concordfax.com/fax/v5";

        public static void GetFaxStatusJson()
        {
            string methodName = "GetFaxStatus";

            Console.WriteLine($"Starting call to {methodName}");

            #region General Settings

            // Fill in with username
            string username = "";
            // Fill in with password
            string password = "";
            // Fill in with JobId to be cancelled
            string jobId = "";

            #endregion General Settings

            #region OAuth 2.0 Settings

            string grantType = "password";
            string scope = "FaxWS";
            string faxWSClientId = "A9F528F9-0000-4B70-0000-078C23030424-ConcordApiFaxWS";
            string faxWSClientSecret = "";

            #endregion OAuth 2.0 Setup


            try
            {
                #region OAuth 2.0 Authentication

                AccessTokenRequest accessTokenRequest = null;
                AccessTokenResponse accessTokenResponse = null;
                TokenManager tokenManager = new TokenManager(oauthUrl);

                accessTokenRequest = new AccessTokenRequest(
                    clientId: faxWSClientId,
                    clientSecret: faxWSClientSecret,
                    username: username,
                    password: password,
                    grantType: grantType,
                    scope: scope,
                    redirectUri: null,
                    code: null,
                    refreshToken: null,
                    state: null);

                Console.WriteLine("Getting access token");

                // Get an access token from Cache OR request one from the Identity Server
                accessTokenResponse = tokenManager.GetAccessToken(accessTokenRequest);

                if(accessTokenResponse == null)
                {
                    Console.WriteLine("Failed to get an AccessToken, returned null");

                    return;
                }

                // Check to see if we failed to get an Access token via a Refresh token that has expired or been revoked, if so we need to re-authenticate
                if(accessTokenResponse.HttpStatusCode == HttpStatusCode.BadRequest && accessTokenResponse.Error == "invalid_grant")
                {
                    Console.WriteLine("Refresh token expired, attempting to get a new Access Token");

                    accessTokenResponse = tokenManager.GetAccessToken(accessTokenRequest, ignoreCache: true);
                }

                if(accessTokenResponse.HttpStatusCode != HttpStatusCode.OK)
                {
                    Console.WriteLine("AccessToken not valid, Error Code: {0}, Error Description: {1}", accessTokenResponse.Error, accessTokenResponse.ErrorDescription);

                    return;
                }

                Console.WriteLine("Access token retrieved sucessfully");

                #endregion OAuth 2.0 Authentication

                #region Request Setup

                // Sample Request
                //{
                //    "GetFaxStatus": {
                //        "UserID": "",
                //        "strPIN": "",
                //        "FaxJobIds": [{
                //        "JobId": ""
                //        }]
                //    }
                //}

                // Create JSON request
                var json = new
                {
                    GetFaxStatus = new {
                        UserID = username,
                        strPIN = "", // Do not set password as using OAUTH
                        FaxJobIds = new[] {
                            new {
                                JobId = jobId
                            }
                        }
                    }
                };

                // Serialize to JSON string {MethodName:{}}
                string content = JsonConvert.SerializeObject(json);

                // Create HttpContent object from  JSON content and set content-type to application/json
                HttpContent httpContent = new StringContent(content, Encoding.UTF8, "application/json");

                #endregion Request Setup

                #region API Call

                using(var client = new HttpClient())
                {
                    // Clear any existing headers
                    client.DefaultRequestHeaders.Accept.Clear();

                    // Add Authorization Bearer OAuth 2.0 Token to header
                    client.DefaultRequestHeaders.Add("Authorization", "Bearer " + accessTokenResponse.AccessToken);

                    // Add Content-Type: application/json
                    client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));

                    Console.WriteLine($"Making API Call to {methodName}");

                    // Sent POST request
                    HttpResponseMessage httpResponseMessage = client.PostAsync(new Uri(faxWSUrl), httpContent).GetAwaiter().GetResult();

                    Console.WriteLine("Reading API Call Response content");

                    // Get JSON body content from response
                    string responseContent = httpResponseMessage.Content.ReadAsStringAsync().GetAwaiter().GetResult();

                    // Check to see if Http Status Code was successful
                    if(!httpResponseMessage.IsSuccessStatusCode)
                    {
                        Console.WriteLine($"Http Error Returned, Status Code: {httpResponseMessage.StatusCode}, Reason Phrase: {httpResponseMessage.ReasonPhrase}");
                        Console.WriteLine($"Response Content:{responseContent}");

                        return;
                    }

                    JObject jsonResult = null;

                    try
                    {
                        // Parse JSON string to Json Object that will help parse response
                        jsonResult = JObject.Parse(responseContent);
                    }
                    catch(JsonReaderException ex)
                    {
                        Console.WriteLine(ex.Message);
                    }

                    // Write JSON response out
                    Console.WriteLine($"Json Response: {jsonResult.ToString()}");

                    // SAMPLE RESPONSE
                    //{
                    //    "GetFaxStatusResponse": {
                    //        "return": false,
                    //        "FaxStatusList": [{
                    //            "FaxJobId": "",
                    //            "FaxJobStatusId": 0,
                    //            "StatusDescription": ""
                    //        }],
                    //        "WSError": {
                    //            "ErrorCode": 0,
                    //            "ErrorString": ""
                    //        }
                    //    }
                    //}

                    // Get response portion
                    // Serialize to JSON string {GetFaxStatusResponse:{}}
                    var response = jsonResult["GetFaxStatusResponse"];

                    // Get API call status
                    bool success = response["return"].Value<bool>();

                    // See if method call was considered successful
                    // If not then output detail from WSError object and RAW JSON response
                    if(!success)
                    {
                        var wsError = response["WSError"];
                        var errorCode = wsError["ErrorCode"].Value<int>();
                        var errorString = wsError["ErrorString"].Value<string>();

                        Console.WriteLine($"ErrorCode: {errorCode}, ErrorString:{errorString}");

                        return;
                    }



                    // API Call was successful, echo back JobId that was cancelled
                    Console.WriteLine($"Successfully retrieved status, looping over results");

                    var faxStatusList = response["FaxStatusList"];

                    foreach(var faxStatus in faxStatusList)
                    {
                        var faxJobId = faxStatus["FaxJobId"].Value<string>();
                        var faxJobStatusId = faxStatus["FaxJobStatusId"].Value<int>();
                        var statusDescription = faxStatus["StatusDescription"].Value<string>();

                        Console.WriteLine($"JobId: {faxJobId}, StatusId: {faxJobStatusId}, StatusDescription: {statusDescription}");
                    }
                }

                #endregion API Call

            }
            catch(Exception ex)
            {
                Console.WriteLine($"Error while calling {methodName} : {ex.Message}");
            }
            finally
            {
                Console.WriteLine($"Finished call to {methodName}");
            }

        }
    }
}

See Also