Chilkat Examples

ChilkatHOME.NET Core C#Android™AutoItCC#C++Chilkat2-PythonCkPythonClassic ASPDataFlexDelphi ActiveXDelphi DLLGoJavaLianjaMono C#Node.jsObjective-CPHP ActiveXPHP ExtensionPerlPowerBuilderPowerShellPureBasicRubySQL ServerSwift 2Swift 3,4,5...TclUnicode CUnicode C++VB.NETVBScriptVisual Basic 6.0Visual FoxProXojo Plugin

Swift 3,4,5... Web API Examples

Primary Categories

ABN AMRO
AWS Secrets Manager
AWS Security Token Service
AWS Translate
Activix CRM
Adyen
Alibaba Cloud OSS
Amazon Cognito
Amazon DynamoDB
Amazon MWS
Amazon Pay
Amazon Rekognition
Amazon SP-API
Amazon Voice ID
Aruba Fatturazione
Azure Maps
Azure Monitor
Azure OAuth2
Azure Storage Accounts
Backblaze S3
Banco Inter
Belgian eHealth Platform
Bitfinex v2 REST
Bluzone
BrickLink
Bunny CDN
CallRail
CardConnect
Cerved
ClickBank
Clickatell
Cloudfare
Constant Contact
DocuSign
Duo Auth MFA
ETrade
Ecwid
Egypt ITIDA
Egypt eReceipt
Etsy
Facebook
Faire
Frame.io
GeoOp
GetHarvest
Global Payments
Google People
Google Search Console
Google Translate
Google Vision
Hungary NAV Invoicing
IBM Text to Speech
Ibanity
IntakeQ
JCC Cyprus
Jira
Lightspeed
MYOB
Magento
Mailgun
Malaysia MyInvois

Mastercard
MedTunnel
MercadoLibre
MessageMedia
Microsoft Calendar
Microsoft Group
Microsoft Tasks and Plans
Microsoft Teams
Moody's
Okta OAuth/OIDC
OneLogin OIDC
OneNote
OpenAI ChatGPT
PRODA
PayPal
Paynow.pl
Peoplevox
Populi
QuickBooks
Rabobank
Refinitiv
Royal Mail OBA
SCiS Schools Catalogue
SII Chile
SMSAPI
SOAP finkok.com
Salesforce
SendGrid
Shippo
Shopify
Shopware
Shopware 6
SimpleTexting
Square
Stripe
SugarCRM
TicketBAI
TikTok Shop
Trello
Twilio
Twitter API v2
Twitter v1
UPS
UniPin
VoiceBase
Vonage
WaTrend
Walmart v3
Wasabi
WhatsApp
WiX
WooCommerce
WordPress
Xero
Yahoo Mail
Yapily
Yousign
ZATCA
Zendesk
Zoom
_Miscellaneous_
eBay
effectconnect
hacienda.go.cr

 

 

 

(Swift 3,4,5...) ING Open Banking OAuth2 Client Credentials

Demonstrates how to get an access token for the ING Open Banking APIs using client credentials.

For more information, see https://developer.ing.com/openbanking/get-started/openbanking

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.

    let cert = CkoCert()!
    var success: Bool = cert.load(fromFile: "qa_data/certs_and_keys/ING/example_client_tls.cer")
    if success == false {
        print("\(cert.lastErrorText!)")
        return
    }

    let bdPrivKey = CkoBinData()!
    success = bdPrivKey.loadFile("qa_data/certs_and_keys/ING/example_client_tls.key")
    if success == false {
        print("Failed to load example_client_tls.key")
        return
    }

    // The OAuth 2.0 client_id for these certificates is e77d776b-90af-4684-bebc-521e5b2614dd. 
    // Please note down this client_id since you will need it in the next steps to call the API.

    let privKey = CkoPrivateKey()!
    success = privKey.loadAnyFormat(bdPrivKey, password: "")
    if success == false {
        print("\(privKey.lastErrorText!)")
        return
    }

    // Associate the private key with the certificate.
    success = cert.setPrivateKey(privKey)
    if success == false {
        print("\(cert.lastErrorText!)")
        return
    }

    let http = CkoHttp()!

    success = http.setSslClientCert(cert)
    if success == false {
        print("\(http.lastErrorText!)")
        return
    }

    // Calculate the Digest and add the "Digest" header.  Do the equivalent of this:
    // payload="grant_type=client_credentials"
    // payloadDigest=`echo -n "$payload" | openssl dgst -binary -sha256 | openssl base64`
    // digest=SHA-256=$payloadDigest
    let crypt = CkoCrypt2()!
    crypt.hashAlgorithm = "SHA256"
    crypt.encodingMode = "base64"
    var payload: String? = "grant_type=client_credentials"
    var payloadDigest: String? = crypt.hashStringENC(payload)

    // Calculate the current date/time and add the Date header.  
    // reqDate=$(LC_TIME=en_US.UTF-8 date -u "+%a, %d %b %Y %H:%M:%S GMT")  
    let dt = CkoDateTime()!
    dt.setFromCurrentSystemTime()
    // The desire date/time format is the "RFC822" format.
    http.setRequestHeader("Date", value: dt.getAsRfc822(false))

    // Calculate signature for signing your request
    // Duplicate the following code:

    // 	httpMethod="post"
    // 	reqPath="/oauth2/token"
    // 	signingString="(request-target): $httpMethod $reqPath
    // 	date: $reqDate
    // 	digest: $digest"
    // 	signature=`printf "$signingString" | openssl dgst -sha256 -sign "${certPath}example_client_signing.key" -passin "pass:changeit" | openssl base64 -A`

    var httpMethod: String? = "POST"
    var reqPath: String? = "/oauth2/token"

    let sbStringToSign = CkoStringBuilder()!
    sbStringToSign.append("(request-target): ")
    sbStringToSign.append(httpMethod)
    sbStringToSign.toLowercase()
    sbStringToSign.append(" ")
    sbStringToSign.appendLine(reqPath, crlf: false)

    sbStringToSign.append("date: ")
    sbStringToSign.appendLine(dt.getAsRfc822(false), crlf: false)

    sbStringToSign.append("digest: SHA-256=")
    sbStringToSign.append(payloadDigest)

    let signingPrivKey = CkoPrivateKey()!
    success = signingPrivKey.loadPemFile("qa_data/certs_and_keys/ING/example_client_signing.key")
    if success == false {
        print("\(signingPrivKey.lastErrorText!)")
        return
    }

    let rsa = CkoRsa()!
    success = rsa.importPrivateKeyObj(signingPrivKey)
    if success == false {
        print("\(rsa.lastErrorText!)")
        return
    }

    rsa.encodingMode = "base64"
    var b64Signature: String? = rsa.signStringENC(sbStringToSign.getAsString(), hashAlg: "SHA256")

    let sbAuthHdrVal = CkoStringBuilder()!
    sbAuthHdrVal.append("Signature keyId=\"e77d776b-90af-4684-bebc-521e5b2614dd\",")
    sbAuthHdrVal.append("algorithm=\"rsa-sha256\",")
    sbAuthHdrVal.append("headers=\"(request-target) date digest\",")
    sbAuthHdrVal.append("signature=\"")
    sbAuthHdrVal.append(b64Signature)
    sbAuthHdrVal.append("\"")

    let sbDigestHdrVal = CkoStringBuilder()!
    sbDigestHdrVal.append("SHA-256=")
    sbDigestHdrVal.append(payloadDigest)

    // Do the following CURL statement:

    // 	curl -i -X POST "${httpHost}${reqPath}" \
    // 	-H 'Accept: application/json' \
    // 	-H 'Content-Type: application/x-www-form-urlencoded' \
    // 	-H "Digest: ${digest}" \
    // 	-H "Date: ${reqDate}" \
    // 	-H "authorization: Signature keyId=\"$keyId\",algorithm=\"rsa-sha256\",headers=\"(request-target) date digest\",signature=\"$signature\"" \
    // 	-d "${payload}" \
    // 	--cert "${certPath}tlsCert.crt" \
    // 	--key "${certPath}tlsCert.key"

    let req = CkoHttpRequest()!
    req.addParam("grant_type", value: "client_credentials")
    req.addHeader("Accept", value: "application/json")
    req.addHeader("Date", value: dt.getAsRfc822(false))
    req.addHeader("Digest", value: sbDigestHdrVal.getAsString())
    req.addHeader("Authorization", value: sbAuthHdrVal.getAsString())
    var resp: CkoHttpResponse? = http.postUrlEncoded("https://api.sandbox.ing.com/oauth2/token", req: req)
    if http.lastMethodSuccess == false {
        print("\(http.lastErrorText!)")
        return
    }

    // If successful, the status code = 200
    print("Response Status Code: \(resp!.statusCode.intValue)")
    print("\(resp!.bodyStr!)")

    let json = CkoJsonObject()!
    json.load(resp!.bodyStr)

    resp = nil

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

    // A successful response contains an access token such as:
    // {
    //   "access_token": "eyJhbGc ... bxI_SoPOBH9xmoM",
    //   "expires_in": 905,
    //   "scope": "payment-requests:view payment-requests:create payment-requests:close greetings:view virtual-ledger-accounts:fund-reservation:create virtual-ledger-accounts:fund-reservation:delete virtual-ledger-accounts:balance:view",
    //   "token_type": "Bearer",
    //   "keys": [
    //     {
    //       "kty": "RSA",
    //       "n": "3l3rdz4...04VPkdV",
    //       "e": "AQAB",
    //       "use": "sig",
    //       "alg": "RS256",
    //       "x5t": "3c396700fc8cd709cf9cb5452a22bcde76985851"
    //     }
    //   ],
    //   "client_id": "e77d776b-90af-4684-bebc-521e5b2614dd"
    // }

    // Use this online tool to generate parsing code from sample JSON: 
    // Generate Parsing Code from JSON

    var kty: String?
    var n: String?
    var e: String?
    var use: String?
    var alg: String?
    var x5t: String?

    var access_token: String? = json.string(of: "access_token")
    var expires_in: Int = json.int(of: "expires_in").intValue
    var scope: String? = json.string(of: "scope")
    var token_type: String? = json.string(of: "token_type")
    var client_id: String? = json.string(of: "client_id")
    var i: Int = 0
    var count_i: Int = json.size(ofArray: "keys").intValue
    while i < count_i {
        json.i = i
        kty = json.string(of: "keys[i].kty")
        n = json.string(of: "keys[i].n")
        e = json.string(of: "keys[i].e")
        use = json.string(of: "keys[i].use")
        alg = json.string(of: "keys[i].alg")
        x5t = json.string(of: "keys[i].x5t")
        i = i + 1
    }

    // This example will save the JSON containing the access key to a file so that
    // a subsequent example can load it and then use the access key for a request, such as to create a payment request.
    json.writeFile("qa_data/tokens/ing_access_token.json")

}

 

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