Tuesday, April 19, 2022

OAuth 2.0 API call from Business Central

 

Hello Friends,

 Below is sample code to call Auth 2.0 API in BC

Auth 2.0 using client credential method 

Microsoft provide all the different authentication method of Auth2.0 in standard codeunit (Codeunit OAuth2)

First we check our Key and Client Credential details Postman to verify it.



































BC Sample code to call oAuth2.0 API of BC

procedure GetActivationKey(var INTSetup: Record "CRM Integration Setup";
ShowDialog: Boolean)
    var
        gcontent: HttpContent;
        gHttpClient: HttpClient;
        gheaders: HttpHeaders;
        greqMsg: HttpRequestMessage;
        gResponseMsg: HttpResponseMessage;
        ltext: Text;
        lheaders: HttpHeaders;
        lurl: Text;
        Jobject: JsonObject;
        jarray: JsonArray;
        FlowResponse: Text;
        CRMIntegrationFlowLinks: Record "CRM Integration Flow Links";
        TotalCount: Integer;
        i: Integer;
        Jtoken: JsonToken;

        AccesstokenText: Text;
        Scopes: List of [Text];
        Accesstoken: Text;
        oAuth2: Codeunit OAuth2;
    begin
        if ShowDialog then
            if not Confirm('Do you want to Activate and update Activation Serial Key ?', false) then
                exit;

        INTSetup.TestField("Product Code");
        Scopes.Add('https://api.businesscentral.dynamics.com/.default');
//OAuth2.AcquireTokenWithClientCredentials(rec.clientid, rec.clientsecret,
rec.MicrosoftOAuth2Url, '', Scopes, Accesstoken);
        OAuth2.AcquireTokenWithClientCredentials('a2438b84-6537-486a-83af-7a158049b963',
'kCt7Q~hYhPLBXPpEmaYJleFTv9VvWw8d-~CSH',
'https://login.microsoftonline.com/f116a1e5-8088-46f5-a938-4360d60a8472/oauth2/v2.0/token',
'', Scopes, Accesstoken);

        lurl := 'https://api.businesscentral.dynamics.com/v2.0/f116a1e5-8088-46f5-a938-4360d60a8472/
Sandbox2/ODataV4/Company%28%27CRONUS%20USA%2C%20Inc.%27%29/
CustomerProductDetails?$filter=Product_Type%20eq%20%27'
+ INTSetup."Product Code" + '%27%20and%20Tenant_ID%20eq%20%27'
+ TenantId() + '%27%20and%20Blocked%20eq%20false';


        greqMsg.SetRequestUri(lurl);
        greqMsg.Method := 'get';
        gHttpClient.DefaultRequestHeaders.Add('Authorization', 'Bearer ' + AccessToken);
        gHttpClient.Send(greqMsg, gResponseMsg);


        FlowResponse := '';
        gResponseMsg.Content().ReadAs(FlowResponse);
        if not JObject.ReadFrom(FlowResponse) then
            Error('Invalid response, expected a JSON object \Response: \%1', FlowResponse);

        JObject.Get('value', Jtoken);

        if not Jarray.ReadFrom(Format(Jtoken)) then
            Error('Array not Reading Properly');

        if Jarray.Count = 0 then begin
            INTSetup."Serial Key" := '';
            INTSetup.Modify(true);
            Message('No Activation key found with Product Code: %1 and Tenant ID: %2',
INTSetup."Product Code", TenantId());
            exit;
        end;

        Jarray.Get(0, Jtoken);
        if Jtoken.AsObject.Get('Serial_Key', Jtoken) then begin
            INTSetup.validate("Serial Key", Jtoken.AsValue().AsCode());
            INTSetup.Modify(true);
            if ShowDialog then
                Message('Serial Key Updated!');
        end else begin
            INTSetup."Serial Key" := '';
            INTSetup.Modify(true);
            message('Activation API Failed: %1', FlowResponse);
        end;
    end;

No comments:

Post a Comment