Sample code for 30+ languages & platforms
Lazarus Pascal Requires Chilkat v11.0.0+

Hungary NAV Manage Invoice Request

See more Hungary NAV Invoicing Examples

Demonstrates the manageInvoice request for the Hungarian NAV Online Invoicing System REST API v2.0.

Chilkat Lazarus Pascal Downloads

Lazarus Pascal
program ChilkatDemo;

// Demonstrates using the Chilkat Pascal wrapper via the C bridge DLL.
// Builds as a console application under Lazarus (FPC) or Delphi.

{$IFDEF FPC}
  {$MODE DELPHI}
{$ENDIF}
{$APPTYPE CONSOLE}

uses
  {$IFDEF UNIX}
  cthreads,
  {$ENDIF}
  SysUtils,
  CkDllLoader,
  Chilkat.Http,
  Chilkat.CkDateTime,
  Chilkat.Prng,
  Chilkat.HttpResponse,
  Chilkat.StringBuilder,
  Chilkat.BinData,
  Chilkat.Xml,
  Chilkat.Crypt2;

// ---------------------------------------------------------------------------

procedure RunDemo;
var
  success: Boolean;
  bdInvoiceData1: TBinData;
  bdInvoiceData2: TBinData;
  bdInvoiceData3: TBinData;
  crypt: TCrypt2;
  dtNow: TCkDateTime;
  myPassword: string;
  passwordHash: string;
  prng: TPrng;
  sbRequestId: TStringBuilder;
  signatureKey: string;
  sbFinalHashBase: TStringBuilder;
  numReplaced: Integer;
  sbHashBase: TStringBuilder;
  indexHash: string;
  requestSignature: string;
  xmlExchangeToken: TXml;
  encodedEncryptedExchangeToken: string;
  bdExchangeToken: TBinData;
  exchangeToken: string;
  xml: TXml;
  http: THttp;
  endpoint: string;
  resp: THttpResponse;
  respXml: TXml;
  ManageInvoiceResponse_xmlns: string;
  ManageInvoiceResponse_xmlns_ns2: string;
  requestId: string;
  timestamp: string;
  requestVersion: string;
  headerVersion: string;
  funcCode: string;
  softwareId: string;
  softwareName: string;
  softwareOperation: string;
  softwareMainVersion: string;
  softwareDevName: string;
  softwareDevContact: string;
  softwareDevCountryCode: string;
  softwareDevTaxNumber: string;
  transactionId: string;

begin
  success := False;

  //  This example assumes the Chilkat API to have been previously unlocked.
  //  See Global Unlock Sample for sample code.

  //  Build the following XML:

  //  Use this online tool to generate code from sample XML: 
  //  Generate Code to Create XML

  //  <?xml version="1.0" encoding="UTF-8"?>
  //  <ManageInvoiceRequest xmlns="http://schemas.nav.gov.hu/OSA/2.0/api">
  //  	<header>
  //  		<requestId>RID181837288942</requestId>
  //  		<timestamp>2019-09-11T12:44:55.442Z</timestamp>
  //  		<requestVersion>2.0</requestVersion>
  //  		<headerVersion>1.0</headerVersion>
  //  	</header>
  //  	<user>
  //  		<login>lwilsmn0uqdxe6u</login>
  //  		<passwordHash>2F43840A882CFDB7DB0FEC07D419D030D864B47B6B541DC280EF81B937B7A176E33C052B0D26638CC18A7A2C08D8D311733078A774BF43F6CA57FE8CD74DC28E</passwordHash>
  //  		<taxNumber>11111111</taxNumber>
  //  		<requestSignature>E4D191A48EE8828A1E84C1F841A2B4E1699ECB49C4CDA1DC7A057765FD935872219644CC2B5A93B8A344404E4FD8ECA4902B5DBCF993E768DC558B0F0281E775</requestSignature>
  //  	</user>
  //  	<software>
  //  		<softwareId>123456789123456789</softwareId>
  //  		<softwareName>string</softwareName>
  //  		<softwareOperation>LOCAL_SOFTWARE</softwareOperation>
  //  		<softwareMainVersion>string</softwareMainVersion>
  //  		<softwareDevName>string</softwareDevName>
  //  		<softwareDevContact>string</softwareDevContact>
  //  		<softwareDevCountryCode>HU</softwareDevCountryCode>
  //  		<softwareDevTaxNumber>string</softwareDevTaxNumber>
  //  	</software>
  //  	<exchangeToken>b1aca173-d9e8-4561-9237-0511eed99eaa2P0ZHLXBRI2U</exchangeToken>
  //  	<invoiceOperations>
  //  		<compressedContent>false</compressedContent>
  //  		<invoiceOperation>
  //  			<index>1</index>
  //  			<invoiceOperation>CREATE</invoiceOperation>
  //  			<invoiceData>base64 contents of invoiceData1 XML file</invoiceData>
  //  		</invoiceOperation>
  //  		<invoiceOperation>
  //  			<index>2</index>
  //  			<invoiceOperation>CREATE</invoiceOperation>
  //  			<invoiceData>base64 contents of invoiceData2 XML file</invoiceData>
  //  		</invoiceOperation>
  //  		<invoiceOperation>
  //  			<index>3</index>
  //  			<invoiceOperation>CREATE</invoiceOperation>
  //  			<invoiceData>base64 contents of invoiceData3 XML file</invoiceData>
  //  		</invoiceOperation>
  //  	</invoiceOperations>
  //  </ManageInvoiceRequest>
  //  

  //  First load the invoiceData for the 3 XML invoice files we'll be sending.
  bdInvoiceData1 := TBinData.Create;
  bdInvoiceData2 := TBinData.Create;
  bdInvoiceData3 := TBinData.Create;
  success := bdInvoiceData1.LoadFile('qa_data/nav_invoicing/invoiceData1.xml');
  success := bdInvoiceData2.LoadFile('qa_data/nav_invoicing/invoiceData2.xml');
  success := bdInvoiceData3.LoadFile('qa_data/nav_invoicing/invoiceData3.xml');
  if (success = False) then
    begin
      WriteLn('Failed to load invoice data.');
      Exit;
    end;

  crypt := TCrypt2.Create;

  dtNow := TCkDateTime.Create;
  dtNow.SetFromCurrentSystemTime();
  WriteLn(dtNow.GetAsTimestamp(False));

  //  The hash algorithm for the password is SHA512 (not SHA3-512).
  crypt.HashAlgorithm := 'sha512';
  crypt.EncodingMode := 'hex';
  myPassword := 'my-password';
  passwordHash := crypt.HashStringENC(myPassword);

  //  Generate a random request ID like "RID215118906689"
  prng := TPrng.Create;
  sbRequestId := TStringBuilder.Create;
  sbRequestId.Append('RID');
  sbRequestId.Append(prng.RandomString(12,True,False,False));
  WriteLn('generated requestId = ' + sbRequestId.GetAsString());

  //  Calculate the requestSignature
  crypt.HashAlgorithm := 'sha3-512';
  signatureKey := 'ce-8f5e-215119fa7dd621DLMRHRLH2S';

  sbFinalHashBase := TStringBuilder.Create;

  //  First append the timestamp because we are going to remove certain chars/parts.
  sbFinalHashBase.Append(dtNow.GetAsTimestamp(False));
  numReplaced := sbFinalHashBase.Replace('Z','');
  numReplaced := sbFinalHashBase.Replace('-','');
  numReplaced := sbFinalHashBase.Replace(':','');
  numReplaced := sbFinalHashBase.Replace('T','');

  //  Prepend the requestId and append the signatureKey
  sbFinalHashBase.Prepend(sbRequestId.GetAsString());
  sbFinalHashBase.Append(signatureKey);

  //  Calculate each index hash and add it to the sbFinalHashBase
  sbHashBase := TStringBuilder.Create;
  sbHashBase.Append('CREATE');
  sbHashBase.Append(bdInvoiceData1.GetEncoded('base64'));
  indexHash := crypt.HashStringENC(sbHashBase.GetAsString());
  sbFinalHashBase.Append(indexHash);

  sbHashBase.Clear();
  sbHashBase.Append('CREATE');
  sbHashBase.Append(bdInvoiceData2.GetEncoded('base64'));
  indexHash := crypt.HashStringENC(sbHashBase.GetAsString());
  sbFinalHashBase.Append(indexHash);

  sbHashBase.Clear();
  sbHashBase.Append('CREATE');
  sbHashBase.Append(bdInvoiceData3.GetEncoded('base64'));
  indexHash := crypt.HashStringENC(sbHashBase.GetAsString());
  sbFinalHashBase.Append(indexHash);

  //  Get our request signature (using sha3-512 because our HashAlgorithm was set to "sha3-512" up above...)
  requestSignature := crypt.HashStringENC(sbFinalHashBase.GetAsString());

  //  Load our recently obtained exchange token.
  //  See Hungary NAV Invoicing Token Exchange Sample Code
  xmlExchangeToken := TXml.Create;
  success := xmlExchangeToken.LoadXmlFile('qa_data/tokens/nav_exchange_token.xml');
  if (success = False) then
    begin
      WriteLn(xmlExchangeToken.LastErrorText);
      Exit;
    end;

  //  Get the base64 encoded/encrypted exchange token.
  //  IMPORTANT:  Make sure to use the exchange token before it expires.
  //  If it expired, then get a new one..
  encodedEncryptedExchangeToken := xmlExchangeToken.GetChildContent('encodedExchangeToken');

  //  Decode to binary.
  bdExchangeToken := TBinData.Create;
  bdExchangeToken.AppendEncoded(encodedEncryptedExchangeToken,'base64');

  //  Decrypt using your 16-digit replacement key:
  crypt.CryptAlgorithm := 'aes';
  crypt.CipherMode := 'ecb';
  crypt.KeyLength := 128;
  crypt.EncodingMode := 'base64';
  //  Pass your 16-digit replacement key here:
  crypt.SetEncodedKey('99952BBAAAAA8XYZ','ascii');
  crypt.DecryptBd(bdExchangeToken);
  exchangeToken := bdExchangeToken.GetString('utf-8');
  WriteLn('exchange token = ' + exchangeToken);

  //  Now build the XML..
  xml := TXml.Create;
  xml.Tag := 'ManageInvoiceRequest';
  xml.AddAttribute('xmlns','http://schemas.nav.gov.hu/OSA/2.0/api');
  xml.UpdateChildContent('header|requestId',sbRequestId.GetAsString());
  xml.UpdateChildContent('header|timestamp',dtNow.GetAsTimestamp(False));
  xml.UpdateChildContent('header|requestVersion','2.0');
  xml.UpdateChildContent('header|headerVersion','1.0');
  xml.UpdateChildContent('user|login','lwilsmn0uqdxe6u');
  xml.UpdateChildContent('user|passwordHash',passwordHash);
  xml.UpdateChildContent('user|taxNumber','11111111');
  xml.UpdateChildContent('user|requestSignature',requestSignature);
  xml.UpdateChildContent('software|softwareId','123456789123456789');
  xml.UpdateChildContent('software|softwareName','string');
  xml.UpdateChildContent('software|softwareOperation','LOCAL_SOFTWARE');
  xml.UpdateChildContent('software|softwareMainVersion','string');
  xml.UpdateChildContent('software|softwareDevName','string');
  xml.UpdateChildContent('software|softwareDevContact','string');
  xml.UpdateChildContent('software|softwareDevCountryCode','HU');
  xml.UpdateChildContent('software|softwareDevTaxNumber','string');
  xml.UpdateChildContent('exchangeToken',exchangeToken);
  xml.UpdateChildContent('invoiceOperations|compressedContent','false');
  xml.UpdateChildContent('invoiceOperations|invoiceOperation|index','1');
  xml.UpdateChildContent('invoiceOperations|invoiceOperation|invoiceOperation','CREATE');
  xml.UpdateChildContent('invoiceOperations|invoiceOperation|invoiceData',bdInvoiceData1.GetEncoded('base64'));
  xml.UpdateChildContent('invoiceOperations|invoiceOperation[1]|index','2');
  xml.UpdateChildContent('invoiceOperations|invoiceOperation[1]|invoiceOperation','CREATE');
  xml.UpdateChildContent('invoiceOperations|invoiceOperation[1]|invoiceData',bdInvoiceData2.GetEncoded('base64'));
  xml.UpdateChildContent('invoiceOperations|invoiceOperation[2]|index','3');
  xml.UpdateChildContent('invoiceOperations|invoiceOperation[2]|invoiceOperation','CREATE');
  xml.UpdateChildContent('invoiceOperations|invoiceOperation[2]|invoiceData',bdInvoiceData3.GetEncoded('base64'));

  //  POST the XML to https://api-test.onlineszamla.nav.gov.hu/invoiceService/v2/manageInvoice
  http := THttp.Create;
  http.Accept := 'application/xml';
  endpoint := 'https://api-test.onlineszamla.nav.gov.hu/invoiceService/v2/manageInvoice';
  resp := THttpResponse.Create;
  success := http.HttpStr('POST',endpoint,xml.GetXml(),'utf-8','application/xml',resp);
  if (success = False) then
    begin
      WriteLn(http.LastErrorText);
      Exit;
    end;

  WriteLn('Response status code = ' + resp.StatusCode);

  respXml := TXml.Create;
  respXml.LoadXml(resp.BodyStr);
  WriteLn('Response body:');
  WriteLn(respXml.GetXml());

  //  The result looks like this:

  //  <?xml version="1.0" encoding="UTF-8" standalone="yes"?>
  //  <ManageInvoiceResponse xmlns="http://schemas.nav.gov.hu/OSA/2.0/api" xmlns:ns2="http://schemas.nav.gov.hu/OSA/2.0/data">
  //      <header>
  //          <requestId>RID871830318143</requestId>
  //          <timestamp>2020-03-25T15:51:25Z</timestamp>
  //          <requestVersion>2.0</requestVersion>
  //          <headerVersion>1.0</headerVersion>
  //      </header>
  //      <result>
  //          <funcCode>OK</funcCode>
  //      </result>
  //      <software>
  //          <softwareId>123456789123456789</softwareId>
  //          <softwareName>string</softwareName>
  //          <softwareOperation>LOCAL_SOFTWARE</softwareOperation>
  //          <softwareMainVersion>string</softwareMainVersion>
  //          <softwareDevName>string</softwareDevName>
  //          <softwareDevContact>string</softwareDevContact>
  //          <softwareDevCountryCode>HU</softwareDevCountryCode>
  //          <softwareDevTaxNumber>string</softwareDevTaxNumber>
  //      </software>
  //      <transactionId>2WT9GFSKFUU1V4XP</transactionId>
  //  </ManageInvoiceResponse>

  //  Use this online tool to generate parsing code from sample XML: 
  //  Generate Parsing Code from XML

  ManageInvoiceResponse_xmlns := respXml.GetAttrValue('xmlns');
  ManageInvoiceResponse_xmlns_ns2 := respXml.GetAttrValue('xmlns:ns2');
  requestId := respXml.GetChildContent('header|requestId');
  timestamp := respXml.GetChildContent('header|timestamp');
  requestVersion := respXml.GetChildContent('header|requestVersion');
  headerVersion := respXml.GetChildContent('header|headerVersion');
  funcCode := respXml.GetChildContent('result|funcCode');
  softwareId := respXml.GetChildContent('software|softwareId');
  softwareName := respXml.GetChildContent('software|softwareName');
  softwareOperation := respXml.GetChildContent('software|softwareOperation');
  softwareMainVersion := respXml.GetChildContent('software|softwareMainVersion');
  softwareDevName := respXml.GetChildContent('software|softwareDevName');
  softwareDevContact := respXml.GetChildContent('software|softwareDevContact');
  softwareDevCountryCode := respXml.GetChildContent('software|softwareDevCountryCode');
  softwareDevTaxNumber := respXml.GetChildContent('software|softwareDevTaxNumber');
  transactionId := respXml.GetChildContent('transactionId');


  bdInvoiceData1.Free;
  bdInvoiceData2.Free;
  bdInvoiceData3.Free;
  crypt.Free;
  dtNow.Free;
  prng.Free;
  sbRequestId.Free;
  sbFinalHashBase.Free;
  sbHashBase.Free;
  xmlExchangeToken.Free;
  bdExchangeToken.Free;
  xml.Free;
  http.Free;
  resp.Free;
  respXml.Free;

end;

// ---------------------------------------------------------------------------

begin

  try
    RunDemo;
  except
    on E: Exception do
      WriteLn('Unhandled exception: ', E.ClassName, ': ', E.Message);
  end;

  WriteLn;
  {$IFDEF MSWINDOWS}
  WriteLn('Press Enter to exit...');
  ReadLn;
  {$ENDIF}
end.