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

Get E-way Bill System Access Token

See more HTTP Misc Examples

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

Chilkat Swift Downloads

Swift

func chilkatTest() {
    var success: Bool = false

    //  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()!
    success = pubkey.load(fromFile: "qa_data/pem/eway_publickey.pem")
    if success == false {
        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.usePublicKey(pubKey: pubkey)
    if success == false {
        print("\(rsa.lastErrorText!)")
        return
    }

    //  Returns the encrypted password as base64 (because the EncodingMode = "base64")
    var encPassword: String? = rsa.encryptStringENC(str: password, bUsePrivateKey: false)
    if rsa.lastMethodSuccess == false {
        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(length: 32, bDigits: true, bLower: true, bUpper: true)

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

    //  RSA encrypt the app_key.
    var encAppKey: String? = rsa.encryptStringENC(str: app_key, bUsePrivateKey: false)
    if rsa.lastMethodSuccess == false {
        print("\(rsa.lastErrorText!)")
        return
    }

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

    let http = CkoHttp()!

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

    //  POST the JSON...
    let resp = CkoHttpResponse()!
    success = http.httpJson(verb: "POST", url: "http://ewb.wepgst.com/api/Authenticate", json: jsonBody, contentType: "application/json", response: resp)
    if success == false {
        print("\(http.lastErrorText!)")
        return
    }

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

    if respStatusCode != 200 {
        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(json: resp.bodyStr)

    var status: Int = json.int(of: "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.string(ofSb: "error", sb: sbError)
        sbError.decode(encoding: "base64", charset: "utf-8")
        print("error: \(sbError.getAsString()!)")
        return
    }

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

    //  Decrypt the sek key using our app_key.
    let crypt = CkoCrypt2()!
    crypt.cryptAlgorithm = "aes"
    crypt.cipherMode = "ecb"
    crypt.keyLength = 256
    crypt.setEncodedKey(keyStr: app_key, encoding: "us-ascii")
    crypt.encodingMode = "base64"

    let bdSek = CkoBinData()!
    bdSek.appendEncoded(encData: json.string(of: "sek"), encoding: "base64")
    crypt.decryptBd(bd: 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(jsonPath: "authToken", value: authToken)
    jsonEwayAuth.updateString(jsonPath: "decryptedSek", value: bdSek.getEncoded(encoding: "base64"))
    jsonEwayAuth.emitCompact = false

    let fac = CkoFileAccess()!
    fac.writeEntireTextFile(path: "qa_data/tokens/ewayAuth.json", fileData: jsonEwayAuth.emit(), charset: "utf-8", includePreamble: false)

    print("Saved:")
    print("\(jsonEwayAuth.emit()!)")

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

}