Python

Python 2

This example demonstrates an HTTP GET of Lingk event subscriptions.

#!/usr/bin/env
import datetime
import httplib
import hashlib
import hmac
import base64
import urllib

# Constants
endPoint = "www.lingkapis.com"
keyId = "[Access Key]"
secret = "[Secret]"

def createSignature(secret, signingStr):
    """Creates signature for a signing string"""
    message = bytes(signingStr).encode('ascii')
    secret = bytes(secret).encode('ascii')
    signature = base64.b64encode(hmac.new(secret, message, digestmod=hashlib.sha1).digest())
    return signature

def createAuthHeader(keyId, secret, dateStr):
    """Generates authorization header for a given key and secret"""
    requestPath = "/v1/@self/webhooks/subscriptions"
    requestMethod = "GET"
    signingStr = "date: " + dateStr +  "\n(request-target): " + requestMethod.lower() + " " + requestPath
    encodedHMAC = urllib.quote_plus(createSignature(secret, signingStr))
    return "Signature keyId=\"" + keyId + "\",algorithm=\"hmac-sha1\",headers=\"date (request-target)\",signature=\"" + encodedHMAC + "\""

def getHTTPResponse(endPoint, authorizationHeader, dateStr):
    """Connects to an endpoint via HTTPS and retrieves response"""
    connection = httplib.HTTPSConnection(endPoint)
    headers = {'Date': dateStr, 'Authorization': authorizationHeader}
    connection.request('GET', '/v1/@self/webhooks/subscriptions', headers=headers)
    response = connection.getresponse()
    return response

# Start here
dateStr = datetime.datetime.utcnow().strftime("%a, %d %b %Y %H:%M:%S UTC")

authorizationHeader = createAuthHeader(keyId, secret, dateStr)
res = getHTTPResponse(endPoint, authorizationHeader, dateStr)

data = res.read()
print(data)

Python 3

This example demonstrates an HTTP POST of Lingk events.

import datetime
import http.client
import hashlib
import hmac
import base64
import urllib.parse
import json

# Constants
endPoint = "www.lingkapis.com"
keyId = "[Access Key]"
secret = "[Secret]"


# Test Data
contact = '''
    {
        "verb": "create",
        "eventObject": {
            "applicantId": "12345678",
            "studentId": "909706331",
            "title": "Mr",
            "firstName": "Joe",
            "middleName": "Joseph",
            "lastName": "Soap",
            "birthDate": "1996-07-19",
            "gender": "Male"
        },
        "objectType": "mytenant.mywork.contact"
    }'''

def createSignature(secret, signingStr):
    """Creates signature for a signing string"""
    message = signingStr.encode('ascii')
    secret = secret.encode('ascii')
    signature = base64.b64encode(hmac.new(secret, message, digestmod=hashlib.sha1).digest())
    return signature

def createAuthHeader(keyId, secret, dateStr):
    """Generates authorization header for a given key and secret"""
    requestPath = "/v1/@self/events"
    requestMethod = "POST"
    signingStr = "date: " + dateStr +  "\n(request-target): " + requestMethod.lower() + " " + requestPath
    encodedHMAC = urllib.parse.quote_plus(createSignature(secret, signingStr))
    return "Signature keyId=\"" + keyId + "\",algorithm=\"hmac-sha1\",headers=\"date (request-target)\",signature=\"" + encodedHMAC + "\""

def getHTTPResponse(endPoint, authorizationHeader, dateStr, payLoad):
    """Connects to an endpoint via HTTPS and retrieves response"""
    connection = http.client.HTTPSConnection(endPoint)
    #connection.set_debuglevel(5)
    headers = {'Date': dateStr, 'Authorization': authorizationHeader}
    connection.request('POST', '/v1/@self/events', body=payLoad, headers=headers)
    response = connection.getresponse()
    #print(response.getheaders())
    return response

def triggerContactEvent():
    # Start here
    dateStr = datetime.datetime.utcnow().strftime("%a, %d %b %Y %H:%M:%S UTC")
    #print(dateStr)
    authorizationHeader = createAuthHeader(keyId, secret, dateStr)
    res = getHTTPResponse(endPoint, authorizationHeader, dateStr, contact)

    success = False
    result = res.read()
    try:
        jsnResult = json.loads(result.decode("UTF-8"))
        if "eventGuid" in jsnResult:
            success = True
    except:
        pass

    return({"Date": dateStr, "AuthorizationHeader": authorizationHeader, "Success": success, "Result": result})

if __name__ == "__main__":
    result = triggerContactEvent()
    print(result)

Last updated