Generate Bearer Token in D365 f&O
internal final class TECGenerateToken
{
/// <summary>
/// Class entry point. The system will call this method when a designated menu
/// is selected or when execution starts and this class is set as the startup class.
/// </summary>
/// <param name = "_args">The specified arguments.</param>
public static void main(Args _args)
{
#define.PostFormat('client_id=\%1&grant_type=\%2&resource=\%3&client_secret=\%4')
str rawResponse;
Map responseData;
RetailWebResponse responseLoc;
System.Text.Encoding utf8;
System.Byte[] byteArray;
TECAxCrmParameter parameter = TECAxCrmParameter::find();
str token;
str tokenUri = parameter.TokenGenerationURL;
str secretKey = parameter.passwordEdit(false, '');
str byteStr = parameter.ClientId + ':' + secretKey;
str resource = 'https://syndromecrmuat.crm8.dynamics.com';
str postdata;
utf8 = System.Text.Encoding::get_UTF8();
byteArray = utf8.GetBytes(byteStr);
byteStr = System.Convert::ToBase64String(byteArray);
RetailCommonWebAPI webApi = RetailCommonWebAPI::construct();
str authHeader = strFmt('Authorization: Bearer %1',byteStr);
//important state to generate the toekn start
SysUrlEncoder sysUrlEncoder = new SysUrlEncoder();
postdata = strFmt(#postFormat,
sysUrlEncoder.encode(parameter.ClientId),
sysUrlEncoder.encode('client_credentials'),
sysUrlEncoder.encode(resource),
sysUrlEncoder.encode(secretKey));
//important state to generate the toekn start
if(tokenUri && authHeader)
{
responseLoc = webApi.makePostRequest(tokenUri,postdata,authHeader);
}
if(responseLoc.parmHttpStatus() != 200)
{
rawResponse = responseLoc.parmData();
throw error("Failed to retrieve the token");
}
rawResponse = responseLoc.parmData();
responseData = RetailCommonWebAPI::getMapFromJsonString(rawResponse);
token = responseData.lookup("access_token");
Info(token);
}
}
Comments
Post a Comment