import json import requests import random import string import sys import datetime import time KEY = "YOUR API KEY HERE" SECRET = "YOUR API SECRET HERE" BASE_URL = "https://apicurrent-app.booker.ninja/WebService4/json/CustomerService.svc/" # Function which returns a call to the Web API for a given command # with arguments. This is a wrapper function for # the POST, PUT and GET methods in the requests library. def call(method, params, reqType="post"): url = BASE_URL + method headers = {'content-type': 'application/json; charset=utf-8'} if(reqType == "get"): if(params == ""): response = requests.get(url, headers=headers) else: response = requests.get(url, data=json.dumps(params), headers=headers) if(reqType == "post"): response = requests.post(url, data=json.dumps(params), headers=headers) elif(reqType == "put"): response = requests.put(url, data=json.dumps(params), headers=headers) output = json.loads(response.text) if("IsSuccess" in output.keys()): # All methods except GetAccessToken should have this. if(output['IsSuccess'] == False): print "Error: " + output["ErrorMessage"] sys.exit() if("error" in output.keys()): # Included to ensure that GetAccessToken works. if(output["error"] != None): print "Error: " + output["error_description"] sys.exit() return output # Strips the -0400 from the time zone for the date def stripTimeZone(date): return date[:19] + date[24:] #We choose some default parameters to pass to each method today = "/Date(" + str(time.mktime(datetime.datetime.now().timetuple()))[:-2] + "000)/"# Today's date as a unix millisecond timestamp in JSON date format start = "/Date(" + str(time.mktime((datetime.datetime.now()+datetime.timedelta(days = 7)).timetuple()))[:-2] + "000)/"# 7 days from today end = "/Date(" + str(time.mktime((datetime.datetime.now()+datetime.timedelta(days = 8)).timetuple()))[:-2] + "000)/"# 8 days from today # We have a default location, and use it to retrieve the rest of the information from the API defaultLocation = 3749 # Our default First/Last names of customer will be random strings defaultFirst = ''.join(random.choice(string.ascii_uppercase + string.digits) for x in range(10)) defaultLast = ''.join(random.choice(string.ascii_uppercase + string.digits) for x in range(10)) # We get an access token p = "" j = (call("access_token?client_id="+KEY+"&client_secret="+SECRET+"&grant_type=client_credentials",p,"get")) defaultToken = j["access_token"] print "Got access token" # We retrieve the treatmentID, category, and subcategory of a treatment from the location p = { "LocationID": defaultLocation, "access_token": defaultToken } j = call("/treatments",p,"post") defaultTreatment = j["Treatments"][0]["ID"] defaultCategory = j["Treatments"][0]["Category"]["ID"] defaultTreatmentSub = j["Treatments"][0]["SubCategory"]["ID"] print "Finding appointment for treatment " + str(defaultTreatment) + " with category " + str(defaultCategory) + " subcategory " + str(defaultTreatmentSub) # We get the first possible time using RunServiceAvailability p = { "EndDateTime": end, "LocationID": defaultLocation, "MaxTimesPerTreatment": 5, "StartDateTime": start, "TreatmentCategoryID": defaultTreatment, "TreatmentSubCategoryID": defaultTreatmentSub, "access_token": defaultToken } j = (call("availability/service",p)) # We extract the first available time from the returned JSON data # along with the treatment information. first = stripTimeZone(j['TreatmentAvailabilitySearchItems'][0]["FirstAvailableTime"]) defaultTreatment = j["TreatmentAvailabilitySearchItems"][0]["Treatment"]["ID"] defaultTreatmentSub = j["TreatmentAvailabilitySearchItems"][0]["Treatment"]["SubCategory"]["ID"] print "First available appointment is: " + str(first) #Create the appointment using CreateAppointment # Set parameters as a multi-line dictionary p = { "ItineraryTimeSlotList":[ { "CurrentPackagePrice": { "Amount": 0, "CurrencyCode": "" }, "IsPackage": False, "PackageID": None, "StartDateTime": first, "TreatmentTimeSlots": [ { "CurrentPrice": { "Amount": 0, "CurrencyCode": "" }, "Duration": None, "EmployeeID": None, "StartDateTime": str(first), "TreatmentID": str(defaultTreatment), } ] } ], "AppointmentPayment": { "PaymentItem": { "Amount": { "Amount": 0, "CurrencyCode": "" }, "CreditCard": { "BillingZip": "10005", "ExpirationDate": "/Date(1337832000000)/", "NameOnCard": "Test Customer", "Number": "4828641155472023", "SecurityCode": "123", "Type": { "ID": 1, "Name": "" }, "iDynamoSwipeData": "" }, "GiftCertificate": { "Number": "", "Type": { "ID": 1, "Name": "" } }, "Method": { "ID": 1, "Name": "" } }, "CouponCode": "holiday" }, "Customer": { "Address": { "City": "New York", "Country": { "ID": 1, "Name": "" }, "State": "NY", "Street1": "22 Cortlandt Street", "Street2": "", "Zip": "10007" }, "DateOfBirth": None, "Email": "testcustomer@gramercyone.com", "FirstName": defaultFirst, "GUID": "", "GenderID": None, "HomePhone": "1234567890", "ID": None, "LastName": str(defaultLast), "MobilePhone": "1234567890", "MobilePhoneCarrierID": 1, "OriginationID": None, "PreferredCommunicationMethodID": None, "SendEmail": True, "SendSMS": False, "WorkPhone": "" }, "LocationID": defaultLocation, "Notes": "", "RefCode": "", "TempCreditCardID": None, "access_token": defaultToken } j = (call("/appointment/create",p)) # Extract appointment information from JSON output aptTime = stripTimeZone(j['Appointment']['StartDateTime']) aptID = int(j['Appointment']['ID']) print "Created appointment at: " + str(aptTime) + "with ID " + str(aptID) # ConfirmAppointment p = {"ID":aptID, "access_token":defaultToken} j = (call("/appointment/confirm",p,"put")) confirmTime = stripTimeZone(j["Appointment"]['AppointmentTreatments'][0]["StartDateTime"]) print "Confirmed appointment at: " + str(confirmTime)