Sample code for 30+ languages & platforms
Swift

ShippingEasy.com Calculate Signature for API Authentication

See more HTTP Misc Examples

Demonstrates how to calculate the shippingeasy.com API signature for authenticating requests.

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, concatenate these into a plaintext string using the following order:
    // 
    //     Capitilized method of the request. E.g. "POST"
    //     The URI path
    //     The query parameters sorted alphabetically and concatenated together into a URL friendly format: param1=ABC&param2=XYZ
    //     The request body as a string if one exists
    //     All parts are then concatenated together with an ampersand. The result resembles something like this:
    // 
    // "POST&/partners/api/accounts&api_key=f9a7c8ebdfd34beaf260d9b0296c7059&api_timestamp=1401803554&{ ... request body ... }"

    let sbStringToSign = CkoStringBuilder()!

    var httpVerb: String? = "POST"
    var uriPath: String? = "/partners/api/accounts"
    var queryParamsStr: String? = "api_key=YOUR_API_KEY&api_timestamp=UNIX_EPOCH_TIMESTAMP"

    // Build the following JSON that will be the body of the request:

    // {
    //   "account": {
    //     "first_name": "Coralie",
    //     "last_name": "Waelchi",
    //     "company_name": "Hegmann, Cremin and Bradtke",
    //     "email": "se_greg_6d477b1e59e8ff24abadfb59d3a2de3e@shippingeasy.com",
    //     "phone_number": "1-381-014-3358",
    //     "address": "2476 Flo Inlet",
    //     "address2": "",
    //     "state": "SC",
    //     "city": "North Dennis",
    //     "postal_code": "29805",
    //     "country": "USA",
    //     "password": "abc123",
    //     "subscription_plan_code": "starter"
    //   }
    // }

    let json = CkoJsonObject()!
    json.updateString(jsonPath: "account.first_name", value: "Coralie")
    json.updateString(jsonPath: "account.last_name", value: "Waelchi")
    json.updateString(jsonPath: "account.company_name", value: "Hegmann, Cremin and Bradtke")
    json.updateString(jsonPath: "account.email", value: "se_greg_6d477b1e59e8ff24abadfb59d3a2de3e@shippingeasy.com")
    json.updateString(jsonPath: "account.phone_number", value: "1-381-014-3358")
    json.updateString(jsonPath: "account.address", value: "2476 Flo Inlet")
    json.updateString(jsonPath: "account.address2", value: "")
    json.updateString(jsonPath: "account.state", value: "SC")
    json.updateString(jsonPath: "account.city", value: "North Dennis")
    json.updateString(jsonPath: "account.postal_code", value: "29805")
    json.updateString(jsonPath: "account.country", value: "USA")
    json.updateString(jsonPath: "account.password", value: "abc123")
    json.updateString(jsonPath: "account.subscription_plan_code", value: "starter")

    json.emitCompact = false
    print("\(json.emit()!)")

    // First, let's get the current date/time in the Unix Epoch Timestamp format (which is just an integer)
    let dt = CkoDateTime()!
    dt.setFromCurrentSystemTime()
    // Get the UTC time.
    var bLocalTime: Bool = false
    var unixEpochTimestamp: String? = dt.get(asUnixTimeStr: bLocalTime)

    // Build the string to sign:
    sbStringToSign.append(value: httpVerb)
    sbStringToSign.append(value: "&")
    sbStringToSign.append(value: uriPath)
    sbStringToSign.append(value: "&")
    sbStringToSign.append(value: queryParamsStr)
    sbStringToSign.append(value: "&")
    // Make sure to send the JSON body of a request in compact form..
    json.emitCompact = true
    sbStringToSign.append(value: json.emit())

    // Use your API key here:
    var your_api_key: String? = "f9a7c8ebdfd34beaf260d9b0296c7059"

    var numReplaced: Int = sbStringToSign.replace(value: "YOUR_API_KEY", replacement: your_api_key).intValue
    numReplaced = sbStringToSign.replace(value: "UNIX_EPOCH_TIMESTAMP", replacement: unixEpochTimestamp).intValue

    // Do the HMAC-SHA256 with your API secret:
    var your_api_secret: String? = "ea210785fa4656af03c2e4ffcc2e7b5fc19f1fba577d137905cc97e74e1df53d"
    let crypt = CkoCrypt2()!
    crypt.macAlgorithm = "hmac"
    crypt.encodingMode = "hexlower"
    crypt.setMacKeyString(key: your_api_secret)
    crypt.hashAlgorithm = "sha256"

    var api_signature: String? = crypt.macStringENC(inText: sbStringToSign.getAsString())
    print("api_signature: \(api_signature!)")

    // --------------------------------------------------------------------
    // Here's an example showing how to use the signature in a request:

    // Build a new string-to-sign and create a new api_signature for the actual request we'll be sending...
    sbStringToSign.clear()
    sbStringToSign.append(value: "GET")
    sbStringToSign.append(value: "&")
    sbStringToSign.append(value: "/app.shippingeasy.com/api/orders")
    sbStringToSign.append(value: "&")
    sbStringToSign.append(value: queryParamsStr)
    sbStringToSign.append(value: "&")
    // There is no body for a GET request.

    api_signature = crypt.macStringENC(inText: sbStringToSign.getAsString())

    let http = CkoHttp()!
    let queryParams = CkoJsonObject()!

    queryParams.updateString(jsonPath: "api_signature", value: api_signature)
    queryParams.updateString(jsonPath: "api_timestamp", value: unixEpochTimestamp)
    queryParams.updateString(jsonPath: "api_key", value: your_api_key)

    let resp = CkoHttpResponse()!
    success = http.httpParams(verb: "GET", url: "https://app.shippingeasy.com/api/orders", json: queryParams, response: resp)
    if success == false {
        print("\(http.lastErrorText!)")
        return
    }

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

}