Chilkat Examples

ChilkatHOMEAndroid™Classic ASPCC++C#Mono C#.NET Core C#C# UWP/WinRTDataFlexDelphi ActiveXDelphi DLLVisual FoxProJavaLianjaMFCObjective-CPerlPHP ActiveXPHP ExtensionPowerBuilderPowerShellPureBasicCkPythonChilkat2-PythonRubySQL ServerSwift 2Swift 3/4TclUnicode CUnicode C++Visual Basic 6.0VB.NETVB.NET UWP/WinRTVBScriptXojo PluginNode.jsExcelGo

Delphi DLL Examples

Web API Categories

ASN.1
Amazon Glacier
Amazon S3
Amazon S3 (new)
Amazon SES
Amazon SNS
Amazon SQS
Async
Azure Cloud Storage
Azure Service Bus
Base64
Bounced Email
Box
CAdES
CSR
CSV
Certificates
Compression
DKIM / DomainKey
DSA
Diffie-Hellman
Digital Signatures
Dropbox
Dynamics CRM
ECC
Email Object
Encryption
FTP
FileAccess
Firebase
GMail REST API
Geolocation
Google APIs
Google Calendar
Google Cloud Storage
Google Drive
Google Photos
Google Sheets
Google Tasks
Gzip
HTML-to-XML/Text

HTTP
HTTP Misc
IMAP
JSON
JSON Web Encryption (JWE)
JSON Web Signatures (JWS)
JSON Web Token (JWT)
Java KeyStore (JKS)
MHT / HTML Email
MIME
Microsoft Graph
NTLM
OAuth1
OAuth2
OneDrive
OpenSSL
Outlook
PEM
PFX/P12
POP3
PRNG
REST
REST Misc
RSA
SCP
SFTP
SMTP
SSH
SSH Key
SSH Tunnel
SharePoint
Socket/SSL/TLS
Spider
Stream
Tar Archive
Upload
WebSocket
XAdES
XML
XML Digital Signatures
XMP
Zip
curl

 

 

 

(Delphi DLL) Get E-way Bill System Access Token

Sends a request to get an E-way bill system access token.

Chilkat for Delphi Downloads

Chilkat non-ActiveX DLL for Delphi

Chilkat ActiveX DLL for Delphi

* The examples here use the non-ActiveX DLL.

uses
    Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
    Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, PublicKey, Prng, Crypt2, HttpResponse, Http, JsonObject, StringBuilder, FileAccess, Rsa, BinData;

...

procedure TForm1.Button1Click(Sender: TObject);
var
pubkey: HCkPublicKey;
success: Boolean;
password: PWideChar;
rsa: HCkRsa;
encPassword: PWideChar;
prng: HCkPrng;
app_key: PWideChar;
encAppKey: PWideChar;
jsonBody: HCkJsonObject;
http: HCkHttp;
resp: HCkHttpResponse;
respStatusCode: Integer;
json: HCkJsonObject;
status: Integer;
sbError: HCkStringBuilder;
authToken: PWideChar;
crypt: HCkCrypt2;
bdSek: HCkBinData;
jsonEwayAuth: HCkJsonObject;
fac: HCkFileAccess;

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

//  First load the public key provided by the E-way bill System
pubkey := CkPublicKey_Create();
success := CkPublicKey_LoadFromFile(pubkey,'qa_data/pem/eway_publickey.pem');
if (success <> True) then
  begin
    Memo1.Lines.Add(CkPublicKey__lastErrorText(pubkey));
    Exit;
  end;

//  Encrypt the password using the RSA public key provided by eway..
password := 'my_wepgst_password';
rsa := CkRsa_Create();
CkRsa_putCharset(rsa,'utf-8');
CkRsa_putEncodingMode(rsa,'base64');

success := CkRsa_ImportPublicKeyObj(rsa,pubkey);
if (success <> True) then
  begin
    Memo1.Lines.Add(CkRsa__lastErrorText(rsa));
    Exit;
  end;

//  Returns the encrypted password as base64 (because the EncodingMode = "base64")
encPassword := CkRsa__encryptStringENC(rsa,password,False);
if (CkRsa_getLastMethodSuccess(rsa) <> True) then
  begin
    Memo1.Lines.Add(CkRsa__lastErrorText(rsa));
    Exit;
  end;

//  Generate a random app_key.  This should be 32 bytes (us-ascii chars)
//  We need 32 bytes because we'll be doing 256-bit AES ECB encryption, and 32 bytes = 256 bits.
prng := CkPrng_Create();
//  Generate a random string containing some numbers, uppercase, and lowercase.
app_key := CkPrng__randomString(prng,32,True,True,True);

Memo1.Lines.Add('app_key = ' + app_key);

//  RSA encrypt the app_key.
encAppKey := CkRsa__encryptStringENC(rsa,app_key,False);
if (CkRsa_getLastMethodSuccess(rsa) <> True) then
  begin
    Memo1.Lines.Add(CkRsa__lastErrorText(rsa));
    Exit;
  end;

//  Prepare the JSON body for the HTTP POST that gets the access token.
jsonBody := CkJsonObject_Create();
CkJsonObject_UpdateString(jsonBody,'action','ACCESSTOKEN');
//  Use your username instead of "09ABDC24212B1FK".
CkJsonObject_UpdateString(jsonBody,'username','09ABDC24212B1FK');
CkJsonObject_UpdateString(jsonBody,'password',encPassword);
CkJsonObject_UpdateString(jsonBody,'app_key',encAppKey);

http := CkHttp_Create();

//  Add required headers.
//  Use your ewb-user-id instead of "03AEXPR16A9M010"
CkHttp_SetRequestHeader(http,'ewb-user-id','03AEXPR16A9M010');
//  The Gstin should be the same as the username in the jsonBody above.
CkHttp_SetRequestHeader(http,'Gstin','09ABDC24212B1FK');
CkHttp_putAccept(http,'application/json');

//  POST the JSON...
resp := CkHttp_PostJson2(http,'http://ewb.wepgst.com/api/Authenticate','application/json',CkJsonObject__emit(jsonBody));
if (CkHttp_getLastMethodSuccess(http) <> True) then
  begin
    Memo1.Lines.Add(CkHttp__lastErrorText(http));
    Exit;
  end;

respStatusCode := CkHttpResponse_getStatusCode(resp);
Memo1.Lines.Add('response status code =' + IntToStr(respStatusCode));
Memo1.Lines.Add('response body:');
Memo1.Lines.Add(CkHttpResponse__bodyStr(resp));

if (respStatusCode <> 200) then
  begin
    CkHttpResponse_Dispose(resp);
    Memo1.Lines.Add('Failed in some unknown way.');
    Exit;
  end;

//  When the response status code = 200, we'll have either
//  success response like this:
//   {"status":"1","authtoken":"...","sek":"..."}
// 
//  or a failed response like this:
// 
//  {"status":"0","error":"eyJlcnJvckNvZGVzIjoiMTA4In0="}

//  Load the response body into a JSON object.
json := CkJsonObject_Create();
CkJsonObject_Load(json,CkHttpResponse__bodyStr(resp));
CkHttpResponse_Dispose(resp);

status := CkJsonObject_IntOf(json,'status');
Memo1.Lines.Add('status = ' + IntToStr(status));

if (status <> 1) then
  begin
    //  Failed.  Base64 decode the error
    // {"status":"0","error":"eyJlcnJvckNvZGVzIjoiMTA4In0="}
    //  For an invalid password, the error is: {"errorCodes":"108"}
    sbError := CkStringBuilder_Create();
    CkJsonObject_StringOfSb(json,'error',sbError);
    CkStringBuilder_Decode(sbError,'base64','utf-8');
    Memo1.Lines.Add('error: ' + CkStringBuilder__getAsString(sbError));
    Exit;
  end;

//  At this point, we know the request was entirely successful.
authToken := CkJsonObject__stringOf(json,'authtoken');

//  Decrypt the sek key using our app_key.
crypt := CkCrypt2_Create();
CkCrypt2_putCryptAlgorithm(crypt,'aes');
CkCrypt2_putCipherMode(crypt,'ecb');
CkCrypt2_putKeyLength(crypt,256);
CkCrypt2_SetEncodedKey(crypt,app_key,'us-ascii');
CkCrypt2_putEncodingMode(crypt,'base64');

bdSek := CkBinData_Create();
CkBinData_AppendEncoded(bdSek,CkJsonObject__stringOf(json,'sek'),'base64');
CkCrypt2_DecryptBd(crypt,bdSek);

//  bdSek now contains the decrypted symmetric encryption key...
//  We'll use it to encrypt the JSON payloads we send.

//  Let's persist our authtoken and decrypted sek (symmetric encryption key).
//  To send EWAY requests (such as to create an e-way bill), we'll just load
//  and use these pre-obtained credentials.
jsonEwayAuth := CkJsonObject_Create();
CkJsonObject_UpdateString(jsonEwayAuth,'authToken',authToken);
CkJsonObject_UpdateString(jsonEwayAuth,'decryptedSek',CkBinData__getEncoded(bdSek,'base64'));
CkJsonObject_putEmitCompact(jsonEwayAuth,False);

fac := CkFileAccess_Create();
CkFileAccess_WriteEntireTextFile(fac,'qa_data/tokens/ewayAuth.json',CkJsonObject__emit(jsonEwayAuth),'utf-8',False);

Memo1.Lines.Add('Saved:');
Memo1.Lines.Add(CkJsonObject__emit(jsonEwayAuth));

//  Sample output:
//  {
//    "authToken": "IBTeFtxNfVurg71LTzZ2r0xK7",
//    "decryptedSek": "5g1TyTie7yoslU3DrbYATa7mWyPazlODE7cEh5Vy4Ho="
//  }

CkPublicKey_Dispose(pubkey);
CkRsa_Dispose(rsa);
CkPrng_Dispose(prng);
CkJsonObject_Dispose(jsonBody);
CkHttp_Dispose(http);
CkJsonObject_Dispose(json);
    CkStringBuilder_Dispose(sbError);
CkCrypt2_Dispose(crypt);
CkBinData_Dispose(bdSek);
CkJsonObject_Dispose(jsonEwayAuth);
CkFileAccess_Dispose(fac);

end;

 

© 2000-2019 Chilkat Software, Inc. All Rights Reserved.