Python

This is walkthrough showing you how to connect Live Link 365's SMS sending API to a flight booking app. This sample creates the model of a flight's booking information and sends an SMS notification to a phone number.

This is not a production-ready application. Please take your time to enhance it for production so that it meets your specific business requirements.

Steps

Code

keyboard_arrow_down
1
2
3
4
5
6
7
# _Step_1
class CustomerDetails:
    def __init__(self, firstname, lastName, CustomerMobNo, cUserName):
        self.customerFirstName = firstname
        self.customerLastName = lastName
        self.customerMobNo = CustomerMobNo
        self.cUserName = cUserName
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
import random
from sendSMS import MessageHandler
import configparser

# _Step_2
class FlightInformation:
    def __init__(self):
        config = configparser.ConfigParser()
        config.read('../resources/config.ini')

        base_url = config['API']['base_url']
        app_key = config['API']['app_key']
        app_secret = config['API']['app_secret']
        self.messageHandler = MessageHandler(base_url, app_key, app_secret)
        self.noOfSeats = 10
        self.noOFSeatsbooked = 6

    def addFlightDetails(self, flightID, fromCity, toCity, deptTime, arrTime):
        self.flightID = flightID
        self.fromCity = fromCity
        self.toCity = toCity
        self.deptTime = deptTime
        self.arrTime = arrTime

    def bookFlight(self, customerDetails):
        messageString = "Hi " + customerDetails.customerFirstName + " your flight has been booked with seat Number: " + self.getAvailableSeatsAndAssign(1) + " from " \
        + self.fromCity + " to " + self.toCity + " departuring at " + self.deptTime

        destinationNumber = customerDetails.customerMobNo
        self.messageHandler.sendSMS(messageString, destinationNumber)

    def getAvailableSeatsAndAssign(self, NoOFpeople):
        flightID = self.flightID
        booked = False
        availablesSeats = self.noOfSeats - self.noOFSeatsbooked
        if availablesSeats != 0 and availablesSeats >= NoOFpeople:
            booked = True
            seatNumberAssign = random.randint(1, availablesSeats)
            return flightID + '_' + str(seatNumberAssign)   
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
; _Step_3
[API]
;Insert your api url here
base_url=https://livelink.sapdigitalinterconnect.com/api
;Insert your generated app key here
app_key=appKey
;Insert your generated app secret here
app_secret=appSecret

[APP]
customerFirstName=Mr.Sam
customerLastName=George
contactNo=123234
customerUsername=SAMG
flightID1=UNI101
fromCity1=New York
toCity1=Chicago
deptTime1=11.30 AM
arrTime1=1.00 PM
flightID2=AXU201
fromCity2=Boston
toCity2=Miami
deptTime2=11.10 AM
arrTime2=2.00 PM
cost2=250
NewDeptTime=3.00 PM
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
import base64
import json
from urllib.request import Request, urlopen
from urllib.error import HTTPError, URLError
from urllib.parse import urlencode

class MessageHandler():
    def __init__(self, base_url, app_key, app_secret):
        self.base_url = base_url
        self.app_key = app_key
        self.app_secret = app_secret

    # _Step_4
    def getAccessToken(self, key, secret):
        """
        This Function is used to retrieve oAuth2 access_tokens.
        This conforms to oAuth2 Spec client_credentials grant_type.
        This Function is not doing any validation regarding expiration of tokens.
        """
        token_url = self.base_url + '/oauth/token'
        credentials = "%s:%s" % (key, secret)
        encode_credential = base64.b64encode(credentials.encode('utf-8')).decode('utf-8').replace("\n", "")
        header_params = {
            "Authorization": ("Basic %s" % encode_credential),
            "Content-Type": "application/x-www-form-urlencoded",
            "Accept": "application/json"
        }
        param = {
            'grant_type': 'client_credentials'
        }

        token_data = urlencode(param)
        token_request = Request(url=token_url, headers=header_params, data=token_data.encode('ascii'))

        try:
            token_response = urlopen(token_request).read()
        except HTTPError as error:
            print ("Error " + error.reason)
        else:
            return json.loads(token_response.decode('UTF-8'))['access_token']

    # _Step_5
    def sendSMS(self, sms, number):
        token_url = self.base_url + '/v2/sms'
        header_params = {
            "Content-Type": "application/json",
            "Authorization": ("Bearer %s" % self.getAccessToken(self.app_key, self.app_secret))
        } 

        param = { 
            "message": sms,
            "origin": "", 
            "destination": number #Phone numbers have to be in E.164 format.
        }
        token_data = json.dumps(param).encode('ascii')
        token_request = Request(url=token_url, headers=header_params, data=token_data)
        # Exception handle example
        try:
            token_response = urlopen(token_request)
            print (token_response)
        except HTTPError as e:
            return 'HTTP Request error with status %i %s' % (e.code, e.reason)
        except URLError as e:
            return 'URL Request error with status %i %s' % (e.code, e.reason)
        else:
            return 'SMS Sent Successfully' #with OrderId:' #% json.loads(sms_response.read().decode('UTF-8'))['orderId']
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
import random
from CustomerDetails import *
from FlightInformation import FlightInformation
import json
import configparser

# _Step_6
if __name__ == '__main__':
    flight1 = FlightInformation()
    flight2 = FlightInformation()
    deptTime1 = "11.30 AM"
    NewDeptTime = "3.00 PM"

    def modifyDepartTime(NewDeptTime):
        deptTime1 = NewDeptTime

    def checkIfFlightIsDelayed(finalFlight):
        if finalFlight.deptTime != NewDeptTime:
            return deptTime1
        else:
            return finalFlight.arrTime

    def searchFlight():
        randNum = random.randint(1, 10)
        if randNum == 0:
            return flight1
        else:
            return flight2

    config = configparser.ConfigParser()
    config.read('../resources/config.ini')

    flight1.addFlightDetails(config["APP"]["flightID1"], config["APP"]["fromCity1"], config["APP"]["toCity1"], config["APP"]["deptTime1"], config["APP"]["arrTime1"])
    flight2.addFlightDetails(config["APP"]["flightID2"], config["APP"]["fromCity2"], config["APP"]["toCity2"], config["APP"]["deptTime2"], config["APP"]["arrTime2"])
    customer = CustomerDetails(config["APP"]["customerFirstName"], config["APP"]["customerLastName"], config["APP"]["contactNo"], config["APP"]["customerUsername"])


    finalFlight = searchFlight() #search for flights
    finalFlight.bookFlight(customer)  #book flight  and send SMS
    modifyDepartTime(NewDeptTime) #this will modify the actual flight time
    checkIfFlightIsDelayed(finalFlight) #it will check if flight is delayed and send SMS