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
{
    class GetFaxBroadcastStatusJsonClass
    {
        const string oauthUrl = "https://login.concord.net/v1/connect/token";
        const string faxWSUrl = "https://ws.concordfax.com/fax/v5";

        public void GetFaxBroadcastStatusJson()
        {
            string methodName = "GetFaxBroadcastStatus";

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

            #region General Settings

            // Fill in with username
            string username = "c0016956";
            // Fill in with password
            string password = "concord!1";
            // Fill in with JobId to be cancelled
            string jobId = "br907h261r0j2168897";
            // Fill in start recipient id
            int startRecipientId = -1; // -1: return all recipients
                                       // Fill in end recipient id
            int endRecipientId = -1;
            // Fill in recipient status
            int recipientStatus = -1;


            #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
                //{
                //    "GetFaxBroadcastStatus": {
                //        "UserID": "",
                //        "strPIN": "",
                //        "request": {
                //            "JobId":"",
                //            "StartRecipientId": 0,
                //            "EndRecipientId": 0,
                //            "RecipientStatus": 0
                //        }
                //    }
                //}

                // Create JSON request
                var json = new
                {
                    GetFaxBroadcastStatus = new {
                        UserID = username,
                        strPIN = "", // Do not set password as using OAUTH                
                        request = new {
                            JobId = jobId,
                            StartRecipientId = startRecipientId,
                            EndRecipientId = endRecipientId,
                            RecipientStatus = recipientStatus
                        }
                    }
                };

                // 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
                    //{
                    //    "GetFaxBroadcastStatusResponse": {
                    //        "return": true,
                    //            "RecipientStatusList":[{
                    //                "FaxJobId": "br001h261r17j2168897",
                    //                "RecipientId": 1,
                    //                "RecipientStatusId": 3,
                    //                "RecipientStatusDescription": "In Progress",
                    //                "RecipientName": "",
                    //                "RecipientCompanyName": "",
                    //                "DeliveryAttempts": 2,
                    //                "DeliveryDuration": 0,
                    //                "DeliverySpeed": 14400,
                    //               "ReceiveCSID": "12063746799 5       ",
                    //                "PageCount": 1,
                    //                "FaxNumber": "12063746799",
                    //                "StartDate": "2021-10-29T12:27:51-07:00",
                    //                "EndDate": "2021-10-29T12:25:36-07:00"
                    //            }],
                    //            "WSError": {
                    //                "ErrorCode": 0,
                    //              "ErrorString": "Success"
                    //            }
                    //    }
                    //}

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

                    // 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 requested fax broadcast report for jobId: {jobId}");

                    var recipientStatusList = response["RecipientStatusList"];

                    foreach(var status in recipientStatusList)
                    {
                        Console.WriteLine($"FaxJobId: {status["FaxJobId"]}, RecipientId: {status["RecipientId"]}, RecipientStatusDescription: {status["RecipientStatusDescription"]}");
                    }

                }

                #endregion API Call

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

See Also