Sample code for 30+ languages & platforms
Swift

MyInvois Malaysia Submit Document

See more Malaysia MyInvois Examples

Demonstrates how to submit a document to MyInvois.

Chilkat Swift Downloads

Swift

func chilkatTest() {
    var success: Bool = false

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

    let http = CkoHttp()!

    // The following JSON is sent in the request body.

    // {
    //   "documents": [
    //     {
    //       "format": "XML",
    //       "documentHash": "<SHA256_hash_of_document>",
    //       "codeNumber": "INV12345",
    //       "document": "<Document_encoded_in_Base64>"
    //     }
    //   ]
    // }

    // Load the document to be sent.
    let sbXmlDoc = CkoStringBuilder()!
    success = sbXmlDoc.loadFile(path: "c:/invoices/invoice1.xml", charset: "utf-8")

    // The MyInvois online documentation neglects to tell us the encoding of the documentHash.
    // Should it be base64?  Or hex?  We can only guess.  MyInvois provides no samples,
    // and omits these crucial details which are needed for actual implementation.
    // 
    // *** Note: It was confirmed that "hex" is the encoding that is needed.
    var sha256: String? = sbXmlDoc.getHash(algorithm: "sha256", encoding: "hex", charset: "utf-8")

    let sbEncoded = CkoStringBuilder()!
    sbEncoded.appendSb(sb: sbXmlDoc)
    sbEncoded.encode(encoding: "base64", charset: "utf-8")

    let json = CkoJsonObject()!
    json.updateString(jsonPath: "documents[0].format", value: "XML")
    json.updateString(jsonPath: "documents[0].documentHash", value: sha256)
    json.updateString(jsonPath: "documents[0].codeNumber", value: "INV12345")
    json.updateSb(jsonPath: "documents[0].document", sb: sbEncoded)

    // Adds the "Authorization: Bearer <access_token>" header.
    http.authToken = "<access_token>"

    let resp = CkoHttpResponse()!
    success = http.httpJson(verb: "POST", url: "https://preprod-api.myinvois.hasil.gov.my/api/v1.0/documentsubmissions", json: json, contentType: "application/json", response: resp)
    if success == false {
        print("\(http.lastErrorText!)")
        return
    }

    print("response status code = \(resp.statusCode.intValue)")
    print("\(resp.bodyStr!)")

}