Friday, December 15, 2023

Dynamics 365 FO code to generate access token and parse the JSON response using contract class to get the access token

1. Class LSGenerateToken :


using System.Net.Http;

using System.Text;

internal final class LSGenerateToken

{

    public static void main(Args _args)

    {

        str responseJson;

        HttpClient httpClient = new HttpClient();

        str requestUrl = 'https://login.microsoftonline.com/TENANTID/oauth2/token';

        str body = strFmt("grant_type=client_credentials&client_id=%1&client_secret=%2",

        'XXXXXXXXXXXXXXXXX','YYYYYYYYYYYYYYYYYYYYY');

        // Send the request and get the response

        HttpResponseMessage response = httpClient.PostAsync(requestUrl, new StringContent(body, Encoding::UTF8, "application/x-www-form-urlencoded")).Result;

        str responseBodyStr;

        if (response.IsSuccessStatusCode)

        {

            // Parse the response body

            var responseBody = response.Content.ReadAsStringAsync().Result;

            responseBodyStr = responseBody;

        }

        else

        {

            // Handle error

            throw error(strFmt("Failed to get access token. Status code: %1", response.StatusCode));

        }    


        LSAccessTokenContract _Contract = FormJsonSerializer::deserializeObject(classNum(LSAccessTokenContract), responseBodyStr);

        info(strfmt("Access token = %1",_Contract.parmaccess_token()));

    }


}






2. LSAccessTokenContract :

[DataContract]

class LSAccessTokenContract

{

    str token_type;

    str expires_in;

    str ext_expires_in;

    str expires_on;

    str not_before;

    str resource;

    str access_token;


    [DataMember("token_type")]

    public str parmtoken_type(str _token_type = token_type)

    {

        token_type = _token_type;

        return token_type;

    }


    [DataMember("expires_in")]

    public str parmexpires_in(str _expires_in = expires_in)

    {

        expires_in = _expires_in;

        return expires_in;

    }


    [DataMember("ext_expires_in")]

    public str parmext_expires_in(str _ext_expires_in = ext_expires_in)

    {

        ext_expires_in = _ext_expires_in;

        return ext_expires_in;

    }


    [DataMember("expires_on")]

    public str parmexpires_on(str _expires_on = expires_on)

    {

        expires_on = _expires_on;

        return expires_on;

    }


    [DataMember("not_before")]

    public str parmnot_before(str _not_before = not_before)

    {

        not_before = _not_before;

        return not_before;

    }


    [DataMember("resource")]

    public str parmresource(str _resource = resource)

    {

        resource = _resource;

        return resource;

    }


    [DataMember("access_token")]

    public str parmaccess_token(str _access_token = access_token)

    {

        access_token = _access_token;

        return access_token;

    }


}