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

Swift 2 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

 

 

 

(Swift) Get E-way Bill System Access Token

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

Chilkat Downloads for the Swift Programming Language

MAC OS X (Cocoa) Objective-C/Swift Libs

iOS Objective-C/Swift Libs

func chilkatTest() {
    //  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
    let pubkey = CkoPublicKey()
    var success: Bool = pubkey.LoadFromFile("qa_data/pem/eway_publickey.pem")
    if success != true {
        print("\(pubkey.LastErrorText)")
        return
    }

    //  Encrypt the password using the RSA public key provided by eway..
    var password: String? = "my_wepgst_password"
    let rsa = CkoRsa()
    rsa.Charset = "utf-8"
    rsa.EncodingMode = "base64"

    success = rsa.ImportPublicKeyObj(pubkey)
    if success != true {
        print("\(rsa.LastErrorText)")
        return
    }

    //  Returns the encrypted password as base64 (because the EncodingMode = "base64")
    var encPassword: String? = rsa.EncryptStringENC(password, bUsePrivateKey: false)
    if rsa.LastMethodSuccess != true {
        print("\(rsa.LastErrorText)")
        return
    }

    //  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.
    let prng = CkoPrng()
    //  Generate a random string containing some numbers, uppercase, and lowercase.
    var app_key: String? = prng.RandomString(32, bDigits: true, bLower: true, bUpper: true)

    print("app_key = \(app_key!)")

    //  RSA encrypt the app_key.
    var encAppKey: String? = rsa.EncryptStringENC(app_key, bUsePrivateKey: false)
    if rsa.LastMethodSuccess != true {
        print("\(rsa.LastErrorText)")
        return
    }

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

    let http = CkoHttp()

    //  Add required headers.
    //  Use your ewb-user-id instead of "03AEXPR16A9M010"
    http.SetRequestHeader("ewb-user-id", headerFieldValue: "03AEXPR16A9M010")
    //  The Gstin should be the same as the username in the jsonBody above.
    http.SetRequestHeader("Gstin", headerFieldValue: "09ABDC24212B1FK")
    http.Accept = "application/json"

    //  POST the JSON...
    var resp: CkoHttpResponse? = http.PostJson2("http://ewb.wepgst.com/api/Authenticate", contentType: "application/json", jsonText: jsonBody.Emit())
    if http.LastMethodSuccess != true {
        print("\(http.LastErrorText)")
        return
    }

    var respStatusCode: Int = resp!.StatusCode.intValue
    print("response status code =\(respStatusCode)")
    print("response body:")
    print("\(resp!.BodyStr)")

    if respStatusCode != 200 {
        resp = nil
        print("Failed in some unknown way.")
        return
    }

    //  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.
    let json = CkoJsonObject()
    json.Load(resp!.BodyStr)
    resp = nil

    var status: Int = json.IntOf("status").intValue
    print("status = \(status)")

    if status != 1 {
        //  Failed.  Base64 decode the error
        // {"status":"0","error":"eyJlcnJvckNvZGVzIjoiMTA4In0="}
        //  For an invalid password, the error is: {"errorCodes":"108"}
        let sbError = CkoStringBuilder()
        json.StringOfSb("error", sb: sbError)
        sbError.Decode("base64", charset: "utf-8")
        print("error: \(sbError.GetAsString())")
        return
    }

    //  At this point, we know the request was entirely successful.
    var authToken: String? = json.StringOf("authtoken")

    //  Decrypt the sek key using our app_key.
    let crypt = CkoCrypt2()
    crypt.CryptAlgorithm = "aes"
    crypt.CipherMode = "ecb"
    crypt.KeyLength = 256
    crypt.SetEncodedKey(app_key, encoding: "us-ascii")
    crypt.EncodingMode = "base64"

    let bdSek = CkoBinData()
    bdSek.AppendEncoded(json.StringOf("sek"), encoding: "base64")
    crypt.DecryptBd(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.
    let jsonEwayAuth = CkoJsonObject()
    jsonEwayAuth.UpdateString("authToken", value: authToken)
    jsonEwayAuth.UpdateString("decryptedSek", value: bdSek.GetEncoded("base64"))
    jsonEwayAuth.EmitCompact = false

    let fac = CkoFileAccess()
    fac.WriteEntireTextFile("qa_data/tokens/ewayAuth.json", textData: jsonEwayAuth.Emit(), charset: "utf-8", includedPreamble: false)

    print("Saved:")
    print("\(jsonEwayAuth.Emit())")

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

}

 

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