codeunit 51109 "Test Integrasi FO"
{
trigger OnRun()
begin
TestPost();
end;
procedure GetOAuthToken() AuthToken: SecretText
var
ClientID: Text;
ClientSecret: Text;
TenantID: Text;
AccessTokenURL: Text;
OAuth2: Codeunit OAuth2;
Scopes: List of [Text];
begin
ClientID := 'xx-xxx-xxxx';
ClientSecret := 'xx-xxx-xxxx';
TenantID := 'xxxxxxxxxx';
AccessTokenURL := 'https://login.microsoftonline.com/' + TenantID + '/oauth2/token';
Scopes.Add('https://api.businesscentral.dynamics.com/.default');
if OAuth2.AcquireTokenWithClientCredentials(ClientID, ClientSecret, AccessTokenURL, '', Scopes, AuthToken) then
exit(AuthToken)
else
Error('Failed to get access token from response\%1', GetLastErrorText());
end;
procedure TestPost()
var
Token: SecretText;
Content: Text[4096];
Url: Text[2048];
UrlActual: Text[2048];
APIName: Text[60];
begin
Token := this.GetOAuthToken();
if Token.IsEmpty() then
Error('Failed to obtain access token')
else begin
Url := 'https//:xxxxx.com/api/xxx';
RequestMsgPost.SetRequestUri(Url);
RequestMsgPost.Method('POST');
RequestMsgPost.GetHeaders(RequestHeaderPost);
RequestHeaderPost.Add('Authorization', SecretStrSubstNo('Bearer %1', Token));
RequestHeaderPost.Add('Chace-Control', 'no-chace');
RequestHeaderPost.Add('Accept', '*/*');
RequestHeaderPost.Add('Connection', 'keep-alive');
Content := SerializeJson();
RequestContentPost.WriteFrom(Content);
RequestContentPost.GetHeaders(RequestContentHeaderPost);
RequestContentHeaderPost.Remove('Content-Type');
RequestContentHeaderPost.Add('Content-Type', 'application/json');
RequestContentPost.GetHeaders(RequestContentHeaderPost);
RequestMsgPost.Content(RequestContentPost);
if HttpClientPost.Send(RequestMsgPost, ResponseMsgPost) then begin
if ResponseMsgPost.IsSuccessStatusCode then begin
Message('Test Succesfully %1 | %2', ResponseMsgPost.HttpStatusCode(), Content);
end else begin
Message('Request failed to communication to FO : %1 | %2', ResponseMsgPost.HttpStatusCode(), Content);
end;
end
else
Error(GetLastErrorText());
end;
end;
local procedure SerializeJson(): Text
var
JObject: JsonObject;
JText: Text;
JObjPricingElement: JsonObject;
JObjPartner: JsonObject;
JObjText: JsonObject;
JObjRelatedObject: JsonObject;
JObjItem: JsonObject;
JArrayPricingElement: JsonArray;
JArrayPartner: JsonArray;
JArrayText: JsonArray;
JArrayRelatedObj: JsonArray;
JArrayItem: JsonArray;
JsonItemResults: JsonObject;
JsonPricingElementResults: JsonObject;
Count: Integer;
Content: Text;
begin
JObject.Add('_dataContract', JsonItemResults);
JsonItemResults.Add('dataAreaId', 'CGS');
JsonItemResults.Add('jot_no', 'JOT/CGS/2408-000402');
JObject.WriteTo(Content);
exit(Content);
end;
var
HttpClientPost: HttpClient;
RequestMsgPost: HttpRequestMessage;
ResponseMsgPost: HttpResponseMessage;
RequestHeaderPost: HttpHeaders;
RequestContentPost: HttpContent;
RequestContentHeaderPost: HttpHeaders;
ResponsePost: Text;
}