Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #!/usr/bin/python
- #Python 2.7+
- import httplib, json
- import datetime
- #Used for debugging and making the JSON data easier to read
- def pretty_json(data):
- print json.dumps(data, indent=2, separators=(',',': '))
- #Makes an httblib connection. request_path is a URL. Headers are a def, body and action are defaulted to empty and GET.
- def get_data(request_path, request_body="",get_put="GET"):
- connection = httplib.HTTPSConnection('connect.squareup.com')
- connection.request(get_put, request_path, request_body, request_headers)
- response = connection.getresponse()
- me = json.loads(response.read())
- return me
- #gets each order passed to it from orders, prints to file.
- def output_order(order,f,state=False):
- #f.write("\n")
- #Address
- print_data = "\n"
- if state:
- #f.write("\n"+order['state'])
- print_data += "\n"+order['state']
- #f.write("\n"+order['recipient_name']+"\n"+order['shipping_address']['address_line_1'])
- print_data += "\n"+order['recipient_name']+"\n"+order['shipping_address']['address_line_1']
- if order['shipping_address']['address_line_2']:
- #f.write("\n"+order['shipping_address']['address_line_2'])
- print_data += "\n"+order['shipping_address']['address_line_2']
- #f.write("\n"+order['shipping_address']['locality']+", "+order['shipping_address']['administrative_district_level_1']+", "+order['shipping_address']['postal_code'])
- print_data += "\n"+order['shipping_address']['locality']+", "+order['shipping_address']['administrative_district_level_1']+", "+order['shipping_address']['postal_code']
- #Gets the payment ID. If there's no payment ID, it's likely been Rejected. Payment ID needed to obtain items orderd.
- try:
- pay_id = order['payment_id']
- req_path = base_req_path+"/payments/"+pay_id
- payment = get_data(req_path)
- except:
- #f.write("\nNo Payment ID")
- print_data += "\nNo Payment ID"
- #Trys to obtain all items ordered. If it has them, it ignores anything that's not Custom Amount (Shipping modifier) and formats it to Name and whole int quantity
- try:
- items = payment['itemizations']
- #f.write("\n\nPlease ship the following to the above address:")
- print_data += "\n\nPlease ship the following to the above address:"
- for i in items:
- if i['name'] != "Custom Amount":
- qty = i['quantity'].split(".")[0]
- #f.write("\n-"+i['name']+" - Quantity: "+qty)
- print_data += "\n-"+i['name']+" - Quantity: "+qty
- #f.write('\n')
- print_data += "\n"
- except:
- #f.write("\nNo Itemizations")
- print_data += "\nNo Itemizations"
- #f.write("\n---------------")
- print_data += "\n---------------"
- f.write(print_data)
- def send_email(filename,count):
- from settings import email_username, email_password, toaddr
- count=count
- import smtplib
- from email.MIMEMultipart import MIMEMultipart
- from email.MIMEText import MIMEText
- fromaddr = email_username
- msg = MIMEMultipart()
- msg['From'] = fromaddr
- msg['To'] = ", ".join(toaddr)
- msg['Subject'] = "Furry Fuel Automated Order System"
- if count > 0:
- body = "New orders for Furry Fuel - \n"
- f = open(filename+"_sent.txt","r")
- for line in f:
- body += line
- f.close()
- else:
- body = "There are no new orders for this period. Please review last 25 orders:\n"
- f = open(filename+".txt","r")
- for line in f:
- body += line
- f.close()
- msg.attach(MIMEText(body, 'plain'))
- server = smtplib.SMTP('smtp.gmail.com', 587)
- server.starttls()
- server.login(fromaddr, email_password)
- text = msg.as_string()
- server.sendmail(fromaddr, toaddr, text)
- server.quit()
- # All requests to the Square Connect API require an access token in an
- # Authorization header. Specify your application's personal access token here.
- # Available from the Application Dashboard: https://connect.squareup.com/apps
- from settings import access_token
- # In addition to an Authorization header, requests to the Connect API should
- # include the indicated Accept and Content-Type headers.
- request_headers = {'Authorization': 'Bearer ' + access_token,
- 'Accept': 'application/json',
- 'Content-Type': 'application/json'}
- #Obtains store location and sets base_req_path.
- locations = get_data("/v1/me/locations")
- loc = locations[0]
- loc_id = loc['id']
- base_req_path = "/v1/"+loc_id
- if __name__ == "__main__":
- #Opens orders.txt for writing
- filename = datetime.date.today().isoformat()
- f = open(filename+".txt","w")
- f_send = open(filename+"_sent.txt","w")
- f.write("---------------")
- f_send.write("---------------")
- #Obtains list of all orders, max 200, starting most recent
- req_path = base_req_path+"/orders?order=DESC&limit=25"
- orders = get_data(req_path)
- count = 0
- for order in orders:
- #Checks for OPEN status orders that are awaiting being processed. Appends to Orders To Send, runs Output.
- output_order(order,f,state=True)
- if order['state'] == "OPEN":
- count += 1
- #Need to alter the data on Square via PUT. The request_body of get_data() needs to be a json.
- body = json.dumps({'action': 'COMPLETE',
- 'completed_note': "Thank you for your purchase! Your order has been processed and will be shipped from the manufacturing facility in a few days. Due to the nature of how Fedex handles third party shipping, there may be a delay before they provide us with a tracking number for your package. We will provide you with a tracking number as soon as we can. Thank you for purchasing from us!" })
- req_path = base_req_path+"/orders/"+order['id']
- #Using Get_Data to send the Put and push alterations. Get_Data would return the modified.
- x = get_data(req_path, request_body=body, get_put="PUT")
- #For verification
- output_order(x,f_send)
- f.close()
- f_send.close()
- send_email(filename,count)
Advertisement
Add Comment
Please, Sign In to add comment