Skip to main content

Notifications

Small and medium business | Business Central, N...
Unanswered

POST API Request - Business Central

Posted on by
Hello Community,

I am trying to post a Sales Invoice as a json with a HTTP Request and I get a 400 Bad Request response. Authorization process works and I get jwt. Also checked the url (Path) and it is ok.
Any suggestions?

My code:
 
codeunit 52101 "Invoice Poster"
{
    [ServiceEnabled]
    procedure SendInvoice(InvoiceHeader: Record "Sales Header"): Boolean
    var
        JwtToken: Text;
        JsonString: JsonObject;
        InvNo: Code[20];
        Authentication: Codeunit "Authentication";
        InvoiceCreator: Codeunit "Invoice Creator";
    begin
        // Step 1: Authenticate and get the JWT token
        JwtToken := Authentication.Authenticate();  // Call the Authenticate procedure from codeunit 52100

        if JwtToken = '' then
            Error('Authentication failed. No JWT token received.');

        // Step 2: Create the invoice JSON
        JsonString := InvoiceCreator.CreateB2BInvoiceJson(InvoiceHeader);

        // Step 3: Post the generated JSON to the provider
        PostInvoiceJson(InvoiceHeader, JwtToken, InvNo, '', '0', JsonString);  // Send the JSON data to the provider
    end;
	
	procedure PostInvoiceJson(InvoiceHeader: Record "Sales Header"; Jwt: Text; InvNo: Code[20]; TemplID: Text; TransmType: Text; JsonString: JsonObject)
    var

        Client: HttpClient;
        Content: HttpContent;
        RequestContentMessage: HttpRequestMessage;
        Response: HttpResponseMessage;
        ContentHeaders: HttpHeaders;
        IsSuccessful: Boolean;

        JsonResponse: InStream;
        JsonResponse: Text;

        JsonObject: JsonObject;
        Token: JsonToken;
        RequestBody: InStream;
        Path: Text;
        AuthString: Text;

        InvoiceSetup: Record "E-Invoice Setup";
        ProvidersResponse: Record "Providers Response";

        Authentication: Codeunit "Authentication";
        InvoiceCreator: Codeunit "Invoice Creator";
        LogResponse: Codeunit "Log Response";
        LogResponseTimer: Codeunit "Log Status";

        TempBlob: Codeunit "Temp Blob";
        OutStream: OutStream;
        InStream: InStream;
        JsonText: Text;

        HttpStatusCode: Integer;
        ResponseText: Text;
		
    begin
	
		// Call the CreateB2BInvoiceJson procedure to create JSON Invoice
        Clear(JsonString);
        JsonString.Add('invoice', InvoiceCreator.CreateB2BInvoiceJson(InvoiceHeader));
        

        // Serialize the nested JSON object to a string
        Clear(TempBlob);
        Clear(OutStream);
        Clear(InStream);
        TempBlob.CreateOutStream(OutStream);
        JsonString.WriteTo(OutStream);
        TempBlob.CreateInStream(InStream);
        InStream.ReadText(JsonText);
        Message('Serialized JSON: %1', JsonText);

        InvNo := InvoiceCreator.GetInvoiceNo(InvoiceHeader);

        // Create the Request body including JSON Invoice
        Clear(JsonObject);
        TemplID := 'eInvoicing';
        //JsonObject.Add('processID', '');
        JsonObject.Add('externalSystemId', InvNo);
        JsonObject.Add('identifier', TemplID);
        JsonObject.Add('transmissionType', TransmType);
        //JsonObject.Add('source', JsonText);
        JsonObject.Add('source', JsonString);

        Clear(TempBlob);
        Clear(OutStream);
        TempBlob.CreateOutStream(OutStream);
        JsonObject.WriteTo(OutStream);
        TempBlob.CreateInStream(RequestBody);
		
        JsonObject.WriteTo(RequestBody);

        RequestContentMessage.Content(Content);
        RequestContentMessage.Method := 'POST';
        //RequestContentMessage.Method('POST');

        // Add necessary headers (such as Content-Type and Method)
        Content.GetHeaders(ContentHeaders);
		
        AuthString := StrSubstNo('Bearer %1', jwt);
		
        Client.DefaultRequestHeaders.Remove('Authorization');
        Client.DefaultRequestHeaders.Add('Authorization', AuthString);
		
        if ContentHeaders.Contains('Content-Type') then ContentHeaders.Remove('Content-Type');
        ContentHeaders.Add('Content-Type', 'application/json');
        if ContentHeaders.Contains('X-Version') then ContentHeaders.Remove('X-Version'); //! Necessary Header by documentation
        ContentHeaders.Add('X-Version', '3.0');
        //if ContentHeaders.Contains('Content-Encoding') then ContentHeaders.Remove('Content-Encoding');
        //ContentHeaders.Add('Content-Encoding', 'UTF8');

        // Send the POST request with the JSON data
        ProvidersResponse.Reset();
        ProvidersResponse.SetRange(jwt, jwt);
        if ProvidersResponse.FindSet() then begin
            Clear(Path);
            if InvoiceSetup.FindFirst() then
                Path := StrSubstNo('%1%2', ProvidersResponse."URL1", InvoiceSetup."Send Request");
        end;
		
        RequestContentMessage.SetRequestUri(Path);
        Content.WriteFrom(RequestBody);
		
		//Client.Post(Path, Content, Response);
        IsSuccessful := Client.Post(Path, Content, Response);
		
        if not IsSuccessful then begin// handle the errorend;         
            if not Response.IsSuccessStatusCode() then begin
                HttpStatusCode := response.HttpStatusCode();
                // handle the error (depending on the HTTP status code)
            end;
            Response.Content().ReadAs(ResponseText);
        end;
    end;
 
Categories:

Under review

Thank you for your reply! To ensure a great experience for everyone, your content is awaiting approval by our Community Managers. Please check back later.

Helpful resources

Quick Links

December Spotlight Star - Muhammad Affan

Congratulations to a top community star!

Top 10 leaders for November!

Congratulations to our November super stars!

Community AMA December 12th

Join us as we continue to demystify the Dynamics 365 Contact Center

Leaderboard

#1
André Arnaud de Calavon Profile Picture

André Arnaud de Cal... 291,240 Super User 2024 Season 2

#2
Martin Dráb Profile Picture

Martin Dráb 230,149 Most Valuable Professional

#3
nmaenpaa Profile Picture

nmaenpaa 101,156

Leaderboard

Featured topics

Product updates

Dynamics 365 release plans