This is a 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
Step 1
Prerequisites
keyboard_arrow_down
Pre-Requisites: For this project, external NuGet Packages are required (they are already included within the project):
Newtonsoft.Json: for JSON object handling
RestSharp: to send the requests to the API
You are free to use whatever method you feel will accomplish these functions within your own project
Step 2
Define FlightInformation Class
keyboard_arrow_down
Create the class for Flight details using id, from, to, departureTime, arriveTime, numberofSeats, availableSeats and messageHandler:
id: String
from: String
to: String
departureTime: String
arriveTime: String
numberofSeats: Integer
availableSeats: Integer
messageHandler: MessageHandler. Create a reference to the MessageHandler class to send the SMS
Create the getter/setter methods to access the attributes of the Flight class.
Add getAvailableSeatsAndAssign() function to return available seats with FlightID using numberofSeats and availableSeats variables, books the flight using bookFlight() function
Add bookFlight() function to book a seat on the desired flight, receives the customer info and sends a message to notify the user that the booking was completed
Add checkIfFlightIsDelayed() function, it receives a time and a customer's information, checks if the time is different and sends a message to the customer in case flight is delayed
Step 3
Instantiate MessageHandler
keyboard_arrow_down
Before you can use the API for sending SMS, we need to provide the basic configuration variables:
App Key
App Secret
Default Origin (number to be used to send the messages)
Proxy (optional)
See this site's Authentication section for more information
Step 4
Define Customer Class
keyboard_arrow_down
Define the class for Customer details using userName, firstName, lastName and phoneNumber:
userName: String
firstName: String
lastName: String
phoneNumber: String
Create the getter/setter methods to access the attributes of the Customer class
Step 5
Set Up Flight Information File
keyboard_arrow_down
The flights.json file acts as a temporary storage for the flights information.
The JSON file can be replaced by a database, which holds the Flight and Customer information
Step 6
Use MessageHandler Methods
keyboard_arrow_down
MessageHandler works as a container for the functionalities required to send SMS through the API. For this step we have created two methods:
GetAccessToken(): This method will take the app key and secret and combine them into a Base64 string, which will then be sent to the /api/oauth/token endpoint to generate and return the authentication token
sendMessage(): This method makes the POST request to the API to send the SMS; it receives a message to be sent, a recipient number, and optionally we can define a number from which we want to send the message
Step 7
Execute the Main Class
keyboard_arrow_down
Execute the main program. Create a Customer and read the flights file, book a seat for the customer, and finally check if the flight is delayed to notify the customer
usingSystem;usingSystem.Net;usingSystem.Text;// _Step_1usingNewtonsoft.Json;usingRestSharp;namespaceflightBooking.Class{publicclassMessageHandler{privateStringbaseUrl="http://livelink.sapdigitalinterconnect.com/api";privateStringappKey;privateStringappSecret;privateStringdefaultOrigin;privateWebProxyglobalProxy;publicMessageHandler(){}publicMessageHandler(StringappKey,StringappSecret,StringdefaultOrigin="",WebProxyproxy=null){this.appKey=appKey;this.appSecret=appSecret;this.defaultOrigin=defaultOrigin;this.globalProxy=proxy;}// _Step_6publicStringGetAccessToken(){StringoAuthUrl=this.baseUrl+"/oauth/token";Stringbearer=Convert.ToBase64String(Encoding.UTF8.GetBytes(this.appKey+":"+this.appSecret));RestClientclient=newRestClient(oAuthUrl);if(this.globalProxy!=null){client.Proxy=this.globalProxy;client.Proxy.Credentials=System.Net.CredentialCache.DefaultCredentials;}RestRequestrequest=newRestRequest(Method.POST);request.AddHeader("content-type","application/x-www-form-urlencoded");request.AddHeader("authorization","Basic "+bearer);request.AddParameter("application/x-www-form-urlencoded","grant_type=client_credentials",ParameterType.RequestBody);IRestResponse<oAuthToken>response=client.Execute<oAuthToken>(request);if(response.StatusCode!=HttpStatusCode.OK){Console.WriteLine("..... Error: "+response.StatusDescription);return"";}StringaccessToken=response.Data.access_token;returnaccessToken;}publicvoidsendMessage(Stringmessage,Stringdestination,Stringorigin="")//Phone numbers have to be in E.164 format.{StringmessageUrl=this.baseUrl+"/v2/sms";ObjectmessagePayload=new{message=message,origin=origin==""?this.defaultOrigin:origin,destination=destination};StringmessageData=JsonConvert.SerializeObject(messagePayload);Stringbearer=GetAccessToken();if(String.IsNullOrEmpty(bearer)){return;}RestClientclient=newRestClient(messageUrl);if(this.globalProxy!=null){client.Proxy=this.globalProxy;client.Proxy.Credentials=System.Net.CredentialCache.DefaultCredentials;}RestRequestrequest=newRestRequest(Method.POST);request.AddHeader("authorization","Bearer "+bearer);request.AddHeader("content-type","application/json");request.AddParameter("application/json",messageData,ParameterType.RequestBody);IRestResponseresponse=client.Execute(request);if(response.StatusCode!=HttpStatusCode.OK){Console.WriteLine("..... failed to send message.");Console.WriteLine("..... Error: "+response.ErrorMessage);}}}}
usingSystem;namespaceflightBooking.Class{// _Step_2publicclassFlight{privateStringid;privateStringfrom;privateStringto;privateStringdepartureTime;privateStringarriveTime;privateInt32numberOfSeats;privateInt32availableSeats;// _Step_3privateMessageHandlermessageHandler=newMessageHandler("","","");// Insert here your appkey, appSecret and default origin respectively.publicStringId{get=>id;set=>id=value;}publicStringFrom{get=>from;set=>from=value;}publicStringTo{get=>to;set=>to=value;}publicStringDepartureTime{get=>departureTime;set=>departureTime=value;}publicStringArriveTime{get=>arriveTime;set=>arriveTime=value;}publicInt32NumberOfSeats{get=>numberOfSeats;set=>numberOfSeats=value;}publicInt32AvailableSeats{get=>availableSeats;set=>availableSeats=value;}publicFlight(){}publicFlight(Stringid,Stringfrom,Stringto,StringdepartureTime,StringarriveTime,Int32numberOfSeats=10){this.id=id;this.from=from;this.to=to;this.departureTime=departureTime;this.arriveTime=arriveTime;this.numberOfSeats=numberOfSeats;this.availableSeats=numberOfSeats;}publicStringgetAvailableSeatsAndAssign(Int32numberOfSeatsToBook){if(numberOfSeatsToBook>this.availableSeats){return"Seats amount to book is higher than the seats avalaible for flight "+this.id;}this.availableSeats-=numberOfSeatsToBook;returnthis.id+"-"+this.availableSeats;}publicvoidbookFlight(Customercustomer){Stringmessage="Hi "+customer.FirstName+" your flight has been booked with seat number "+getAvailableSeatsAndAssign(1)+", from: "+this.from+", to: "+this.to+", departuring at "+this.departureTime;messageHandler.sendMessage(message,customer.PhoneNumber);}publicvoidcheckIfFlightIsDelayed(StringnewDepartureTime,Customercustomer){if(this.DepartureTime!=newDepartureTime){Stringmessage="Flight "+this.id+" from: "+this.from+" to: "+this.to+" is delayed, the new departure time will be at "+newDepartureTime;messageHandler.sendMessage(message,customer.PhoneNumber);}}}}
usingSystem;namespaceflightBooking.Class{// _Step_4publicclassFlight{privateStringid;privateStringfrom;privateStringto;privateStringdepartureTime;privateStringarriveTime;privateInt32numberOfSeats;privateInt32availableSeats;privateMessageHandlermessageHandler=newMessageHandler("","","");// Insert here your appkey, appSecret and default origin respectivelypublicStringId{get=>id;set=>id=value;}publicStringFrom{get=>from;set=>from=value;}publicStringTo{get=>to;set=>to=value;}publicStringDepartureTime{get=>departureTime;set=>departureTime=value;}publicStringArriveTime{get=>arriveTime;set=>arriveTime=value;}publicInt32NumberOfSeats{get=>numberOfSeats;set=>numberOfSeats=value;}publicInt32AvailableSeats{get=>availableSeats;set=>availableSeats=value;}publicFlight(){}publicFlight(Stringid,Stringfrom,Stringto,StringdepartureTime,StringarriveTime,Int32numberOfSeats=10){this.id=id;this.from=from;this.to=to;this.departureTime=departureTime;this.arriveTime=arriveTime;this.numberOfSeats=numberOfSeats;this.availableSeats=numberOfSeats;}publicStringgetAvailableSeatsAndAssign(Int32numberOfSeatsToBook){if(numberOfSeatsToBook>this.availableSeats){return"Seats amount to book is higher than the seats avalaible for flight "+this.id;}this.availableSeats-=numberOfSeatsToBook;returnthis.id+"-"+this.availableSeats;}publicvoidbookFlight(Customercustomer){Stringmessage="Hi "+customer.FirstName+" your flight has been booked with seat number "+getAvailableSeatsAndAssign(1)+", from: "+this.from+", to: "+this.to+", departuring at "+this.departureTime;messageHandler.sendMessage(message,customer.PhoneNumber);}publicvoidcheckIfFlightIsDelayed(StringnewDepartureTime,Customercustomer){if(this.DepartureTime!=newDepartureTime){Stringmessage="Flight "+this.id+" from: "+this.from+" to: "+this.to+" is delayed, the new departure time will be at "+newDepartureTime;messageHandler.sendMessage(message,customer.PhoneNumber);}}}}
usingSystem;usingNewtonsoft.Json;usingSystem.IO;usingSystem.Collections.Generic;usingflightBooking.Class;namespaceflightBooking{classMainClass{// _Step_7publicstaticvoidMain(string[]args){List<Flight>flights;Customercustomer=newCustomer("SAMS","Sam","Smith","+132948392423");//Create a customer, asign an id, first name, last name and the phone number to send the messageusing(StreamReaderinfo=File.OpenText(@"../../Resources/flights.json")){//Retrieve the flight informationJsonSerializerserializer=newJsonSerializer();flights=(List<Flight>)serializer.Deserialize(info,typeof(List<Flight>));}flights[0].bookFlight(customer);//Book a seat for the customerflights[1].checkIfFlightIsDelayed("11:50AM",customer);//Check if customer flight is delayed}}}