Sample code for 30+ languages & platforms
Unicode C++

Create ITIDA Signed JSON and Send to ETA (Egypt Tax Authority) Portal

See more Egypt ITIDA Examples

Demonstrates how to create a .p7s signature that fits Egypt's ITIDA requirements where Chilkat automatically does the ITIDA JSON canonicalization. Also shows the code to send to the ETA Portal.

Chilkat Unicode C++ Downloads

Unicode C++
#include <CkCrypt2W.h>
#include <CkCertW.h>
#include <CkJsonObjectW.h>
#include <CkStringBuilderW.h>
#include <CkHttpW.h>
#include <CkHttpRequestW.h>
#include <CkHttpResponseW.h>

void ChilkatSample(void)
    {
    bool success = false;

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

    CkCrypt2W crypt;
    crypt.put_VerboseLogging(true);

    CkCertW cert;
    cert.put_VerboseLogging(true);

    //  Set the smart card PIN, which will be needed for signing.
    cert.put_SmartCardPin(L"12345678");

    //  There are many ways to load the certificate.  
    //  This example was created for a customer using an ePass2003 USB token.
    //  Assuming the USB token is the only source of a hardware-based private key..
    success = cert.LoadFromSmartcard(L"");
    if (success == false) {
        wprintf(L"%s\n",cert.lastErrorText());
        return;
    }

    //  Tell the crypt class to use this cert.
    success = crypt.SetSigningCert(cert);
    if (success == false) {
        wprintf(L"%s\n",crypt.lastErrorText());
        return;
    }

    CkJsonObjectW cmsOptions;
    //  Setting "DigestData" causes OID 1.2.840.113549.1.7.5 (digestData) to be used.
    cmsOptions.UpdateBool(L"DigestData",true);
    cmsOptions.UpdateBool(L"OmitAlgorithmIdNull",true);

    //  Indicate that we are passing normal JSON and we want Chilkat do automatically
    //  do the ITIDA JSON canonicalization:
    cmsOptions.UpdateBool(L"CanonicalizeITIDA",true);

    crypt.put_CmsOptions(cmsOptions.emit());

    //  The CadesEnabled property applies to all methods that create CMS/PKCS7 signatures. 
    //  To create a CAdES-BES signature, set this property equal to true. 
    crypt.put_CadesEnabled(true);

    crypt.put_HashAlgorithm(L"sha256");

    CkJsonObjectW jsonSigningAttrs;
    jsonSigningAttrs.UpdateInt(L"contentType",1);
    jsonSigningAttrs.UpdateInt(L"signingTime",1);
    jsonSigningAttrs.UpdateInt(L"messageDigest",1);
    jsonSigningAttrs.UpdateInt(L"signingCertificateV2",1);
    crypt.put_SigningAttributes(jsonSigningAttrs.emit());

    //  By default, all the certs in the chain of authentication are included in the signature.
    //  If desired, we can choose to only include the signing certificate:
    crypt.put_IncludeCertChain(false);

    //  Pass a JSON document such as the following.  Chilkat will do the ITIDA canonicalization.
    //  (It is the canonicalized JSON that gets signed.)

    //        {
    //           "issuer":{
    //              "address":{
    //                 "branchID":"0",
    //                 "country":"EG",
    //                 "regionCity":"Cairo",
    //                 "postalCode":"",
    //                 "buildingNumber":"0",
    //                 "street":"123rd Street",
    //                 "governate":"GOVERNATE"
    //              },
    //              "type":"B",
    //              "id":"209999899",
    //              "name":"Xyz SAE"
    //           },
    //           "receiver":{
    //              "address":{
    //                 "country":"EG",
    //                 "regionCity":"CAIRO",
    //                 "postalCode":"11435",
    //                 "buildingNumber":"0",
    //                 "street":"Autostrad Road Abc",
    //                 "governate":"GOVERNATE"
    //              },
    //              "type":"B",
    //              "id":"999999999",
    //              "name":"XYZ EGYPT FOR TRADE"
    //           },
    //           "documentType":"I",
    //           "documentTypeVersion":"1.0",
    //           "dateTimeIssued":"2020-11-15T11:04:53Z",
    //           "taxpayerActivityCode":"1073",
    //           "internalID":"ZZZZ999",
    //           "purchaseOrderReference":"2009199918",
    //           "salesOrderReference":"",
    //           "payment":{
    //              "bankName":"",
    //              "bankAddress":"",
    //              "bankAccountNo":"",
    //              "bankAccountIBAN":"",
    //              "swiftCode":"",
    //              "terms":""
    //           },
    //           "delivery":{
    //              "approach":"",
    //              "packaging":"",
    //              "dateValidity":"",
    //              "exportPort":"",
    //              "countryOfOrigin":"EG",
    //              "grossWeight":0,
    //              "netWeight":0,
    //              "terms":""
    //           },
    //           "invoiceLines":[
    //              {
    //                 "description":"CDM Widget 48GX99X12BA",
    //                 "itemType":"GS1",
    //                 "itemCode":"7622213335056",
    //                 "unitType":"CS",
    //                 "quantity":1.00,
    //                 "unitValue":{
    //                    "currencySold":"EGP",
    //                    "amountEGP":588.67,
    //                    "amountSold":0,
    //                    "currencyExchangeRate":0
    //                 },
    //                 "salesTotal":588.67,
    //                 "total":603.97,
    //                 "valueDifference":0,
    //                 "totalTaxableFees":0,
    //                 "netTotal":529.8,
    //                 "itemsDiscount":0,
    //                 "discount":{
    //                    "rate":10.00,
    //                    "amount":58.87
    //                 },
    //                 "taxableItems":[
    //                    {
    //                       "taxType":"T1",
    //                       "amount":74.17,
    //                       "subType":"No sub",
    //                       "rate":14.00
    //                    }
    //                 ],
    //                 "internalCode":"9099994"
    //              }
    //           ],
    //           "totalSales":588.67,
    //           "totalSalesAmount":588.67,
    //           "totalDiscountAmount":58.87,
    //           "netAmount":529.80,
    //           "taxTotals":[
    //              {
    //                 "taxType":"T1",
    //                 "amount":74.17
    //              }
    //           ],
    //           "extraDiscountAmount":0,
    //           "totalItemsDiscountAmount":0,
    //           "totalAmount":603.97,
    //        }

    //  Build the above JSON..

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

    CkJsonObjectW json;
    json.UpdateString(L"issuer.address.branchID",L"0");
    json.UpdateString(L"issuer.address.country",L"EG");
    json.UpdateString(L"issuer.address.regionCity",L"Cairo");
    json.UpdateString(L"issuer.address.postalCode",L"");
    json.UpdateString(L"issuer.address.buildingNumber",L"0");
    json.UpdateString(L"issuer.address.street",L"123rd Street");
    json.UpdateString(L"issuer.address.governate",L"GOVERNATE");
    json.UpdateString(L"issuer.type",L"B");
    json.UpdateString(L"issuer.id",L"209999899");
    json.UpdateString(L"issuer.name",L"Xyz SAE");
    json.UpdateString(L"receiver.address.country",L"EG");
    json.UpdateString(L"receiver.address.regionCity",L"CAIRO");
    json.UpdateString(L"receiver.address.postalCode",L"11435");
    json.UpdateString(L"receiver.address.buildingNumber",L"0");
    json.UpdateString(L"receiver.address.street",L"Autostrad Road Abc");
    json.UpdateString(L"receiver.address.governate",L"GOVERNATE");
    json.UpdateString(L"receiver.type",L"B");
    json.UpdateString(L"receiver.id",L"999999999");
    json.UpdateString(L"receiver.name",L"XYZ EGYPT FOR TRADE");
    json.UpdateString(L"documentType",L"I");
    json.UpdateString(L"documentTypeVersion",L"1.0");
    json.UpdateString(L"dateTimeIssued",L"2020-11-15T11:04:53Z");
    json.UpdateString(L"taxpayerActivityCode",L"1073");
    json.UpdateString(L"internalID",L"ZZZZ999");
    json.UpdateString(L"purchaseOrderReference",L"2009199918");
    json.UpdateString(L"salesOrderReference",L"");
    json.UpdateString(L"payment.bankName",L"");
    json.UpdateString(L"payment.bankAddress",L"");
    json.UpdateString(L"payment.bankAccountNo",L"");
    json.UpdateString(L"payment.bankAccountIBAN",L"");
    json.UpdateString(L"payment.swiftCode",L"");
    json.UpdateString(L"payment.terms",L"");
    json.UpdateString(L"delivery.approach",L"");
    json.UpdateString(L"delivery.packaging",L"");
    json.UpdateString(L"delivery.dateValidity",L"");
    json.UpdateString(L"delivery.exportPort",L"");
    json.UpdateString(L"delivery.countryOfOrigin",L"EG");
    json.UpdateInt(L"delivery.grossWeight",0);
    json.UpdateInt(L"delivery.netWeight",0);
    json.UpdateString(L"delivery.terms",L"");
    json.UpdateString(L"invoiceLines[0].description",L"CDM Widget 48GX99X12BA");
    json.UpdateString(L"invoiceLines[0].itemType",L"GS1");
    json.UpdateString(L"invoiceLines[0].itemCode",L"7622213335056");
    json.UpdateString(L"invoiceLines[0].unitType",L"CS");
    json.UpdateNumber(L"invoiceLines[0].quantity",L"1.00");
    json.UpdateString(L"invoiceLines[0].unitValue.currencySold",L"EGP");
    json.UpdateNumber(L"invoiceLines[0].unitValue.amountEGP",L"588.67");
    json.UpdateInt(L"invoiceLines[0].unitValue.amountSold",0);
    json.UpdateInt(L"invoiceLines[0].unitValue.currencyExchangeRate",0);
    json.UpdateNumber(L"invoiceLines[0].salesTotal",L"588.67");
    json.UpdateNumber(L"invoiceLines[0].total",L"603.97");
    json.UpdateInt(L"invoiceLines[0].valueDifference",0);
    json.UpdateInt(L"invoiceLines[0].totalTaxableFees",0);
    json.UpdateNumber(L"invoiceLines[0].netTotal",L"529.8");
    json.UpdateInt(L"invoiceLines[0].itemsDiscount",0);
    json.UpdateNumber(L"invoiceLines[0].discount.rate",L"10.00");
    json.UpdateNumber(L"invoiceLines[0].discount.amount",L"58.87");
    json.UpdateString(L"invoiceLines[0].taxableItems[0].taxType",L"T1");
    json.UpdateNumber(L"invoiceLines[0].taxableItems[0].amount",L"74.17");
    json.UpdateString(L"invoiceLines[0].taxableItems[0].subType",L"No sub");
    json.UpdateNumber(L"invoiceLines[0].taxableItems[0].rate",L"14.00");
    json.UpdateString(L"invoiceLines[0].internalCode",L"9099994");
    json.UpdateNumber(L"totalSales",L"588.67");
    json.UpdateNumber(L"totalSalesAmount",L"588.67");
    json.UpdateNumber(L"totalDiscountAmount",L"58.87");
    json.UpdateNumber(L"netAmount",L"529.80");
    json.UpdateString(L"taxTotals[0].taxType",L"T1");
    json.UpdateNumber(L"taxTotals[0].amount",L"74.17");
    json.UpdateInt(L"extraDiscountAmount",0);
    json.UpdateInt(L"totalItemsDiscountAmount",0);
    json.UpdateNumber(L"totalAmount",L"603.97");

    json.put_EmitCompact(true);
    const wchar_t *jsonToSign = json.emit();

    //  Create the CAdES-BES signature.
    crypt.put_EncodingMode(L"base64");

    //  Make sure we sign the utf-8 byte representation of the JSON string
    crypt.put_Charset(L"utf-8");

    const wchar_t *sigBase64 = crypt.signStringENC(jsonToSign);
    if (crypt.get_LastMethodSuccess() == false) {
        wprintf(L"%s\n",crypt.lastErrorText());
        return;
    }

    wprintf(L"Base64 signature:\n");
    wprintf(L"%s\n",sigBase64);

    //  Insert the base64 signature into the JSON to be sent
    json.UpdateString(L"signatures[0].signatureType",L"I");
    json.UpdateString(L"signatures[0].value",sigBase64);

    //  Wrap the JSON in  {"documents":[ ... ]}
    CkStringBuilderW sbToSend;
    sbToSend.Append(L"{\"documents\":[");
    sbToSend.Append(json.emit());
    sbToSend.Append(L"]}");

    //  ------------------------------------------------------------------------
    //  Get an access token using our client ID and client secret key
    const wchar_t *clientId = L"abc999ff-1234";
    const wchar_t *clientSecretKey = L"123fff22-1234-abcd";

    CkHttpW http;

    //  Causes the Authorization: Basic header to be added..
    http.put_Login(clientId);
    http.put_Password(clientSecretKey);
    http.put_BasicAuth(true);

    CkHttpRequestW req;
    req.put_HttpVerb(L"POST");
    req.put_Path(L"/connect/token");
    req.put_ContentType(L"application/x-www-form-urlencoded");
    req.AddParam(L"grant_type",L"client_credentials");
    req.AddHeader(L"Connection",L"close");

    http.put_Accept(L"application/json");

    CkHttpResponseW resp;
    success = http.HttpReq(L"https://id.preprod.eta.gov.eg/connect/token",req,resp);
    if (success == false) {
        wprintf(L"%s\n",http.lastErrorText());
        return;
    }

    http.CloseAllConnections();

    wprintf(L"Response status code: %d\n",resp.get_StatusCode());
    wprintf(L"Response body:\n");
    wprintf(L"%s\n",resp.bodyStr());

    if (resp.get_StatusCode() != 200) {
        wprintf(L"Failed.\n");
        return;
    }

    CkJsonObjectW jsonToken;
    success = jsonToken.Load(resp.bodyStr());

    const wchar_t *accessToken = jsonToken.stringOf(L"access_token");
    wprintf(L"access_token = %s\n",accessToken);

    //  ------------------------------------------------------------------------
    //  Submit the signed JSON to the ETA (Egypt Tax Authority) Portal

    //  No longer sending basic authentication...
    http.put_Login(L"");
    http.put_Password(L"");
    http.put_BasicAuth(false);

    //  Setting the AuthToken property causes the "Authorization: Bearer <token>" header to be added to each request.
    http.put_AuthToken(accessToken);

    const wchar_t *jsonStr = sbToSend.getAsString();
    const wchar_t *url = L"https://api.preprod.invoicing.eta.gov.eg/api/v1/documentsubmissions";
    success = http.HttpStr(L"POST",url,jsonStr,L"utf-8",L"application/json; charset=utf-8",resp);
    if (success == false) {
        wprintf(L"%s\n",http.lastErrorText());
        return;
    }

    wprintf(L"Response status code: %d\n",resp.get_StatusCode());
    wprintf(L"Response body:\n");
    wprintf(L"%s\n",resp.bodyStr());
    }