summercat

Square Script for review, Py2.7x

Jan 21st, 2018
109
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 6.27 KB | None | 0 0
  1. #!/usr/bin/python
  2. #Python 2.7+
  3. import httplib, json
  4. import datetime
  5.  
  6. #Used for debugging and making the JSON data easier to read
  7. def pretty_json(data):
  8.     print json.dumps(data, indent=2, separators=(',',': '))
  9.    
  10.  
  11. #Makes an httblib connection. request_path is a URL. Headers are a def, body and action are defaulted to empty and GET.    
  12. def get_data(request_path, request_body="",get_put="GET"):
  13.     connection = httplib.HTTPSConnection('connect.squareup.com')
  14.     connection.request(get_put, request_path, request_body, request_headers)
  15.     response = connection.getresponse()
  16.     me = json.loads(response.read())
  17.     return me
  18.    
  19. #gets each order passed to it from orders, prints to file.
  20. def output_order(order,f,state=False):
  21.     #f.write("\n")  
  22.     #Address
  23.    
  24.     print_data = "\n"
  25.     if state:
  26.         #f.write("\n"+order['state'])
  27.         print_data += "\n"+order['state']
  28.     #f.write("\n"+order['recipient_name']+"\n"+order['shipping_address']['address_line_1'])
  29.     print_data += "\n"+order['recipient_name']+"\n"+order['shipping_address']['address_line_1']
  30.     if order['shipping_address']['address_line_2']:
  31.         #f.write("\n"+order['shipping_address']['address_line_2'])
  32.         print_data += "\n"+order['shipping_address']['address_line_2']
  33.     #f.write("\n"+order['shipping_address']['locality']+", "+order['shipping_address']['administrative_district_level_1']+", "+order['shipping_address']['postal_code'])
  34.     print_data += "\n"+order['shipping_address']['locality']+", "+order['shipping_address']['administrative_district_level_1']+", "+order['shipping_address']['postal_code']
  35.    
  36.     #Gets the payment ID. If there's no payment ID, it's likely been Rejected. Payment ID needed to obtain items orderd.
  37.     try:
  38.         pay_id = order['payment_id']
  39.         req_path = base_req_path+"/payments/"+pay_id
  40.         payment = get_data(req_path)
  41.     except:
  42.         #f.write("\nNo Payment ID")
  43.         print_data += "\nNo Payment ID"
  44.  
  45.     #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
  46.     try:
  47.         items = payment['itemizations']
  48.         #f.write("\n\nPlease ship the following to the above address:")
  49.         print_data += "\n\nPlease ship the following to the above address:"
  50.         for i in items:
  51.             if i['name'] != "Custom Amount":
  52.                 qty = i['quantity'].split(".")[0]
  53.                 #f.write("\n-"+i['name']+" - Quantity: "+qty)
  54.                 print_data += "\n-"+i['name']+" - Quantity: "+qty
  55.         #f.write('\n')
  56.         print_data += "\n"
  57.                
  58.     except:
  59.         #f.write("\nNo Itemizations")
  60.         print_data += "\nNo Itemizations"
  61.     #f.write("\n---------------")
  62.     print_data += "\n---------------"
  63.        
  64.     f.write(print_data)
  65.  
  66. def send_email(filename,count):
  67.     from settings import email_username, email_password, toaddr
  68.     count=count
  69.     import smtplib
  70.     from email.MIMEMultipart import MIMEMultipart
  71.     from email.MIMEText import MIMEText
  72.  
  73.     fromaddr = email_username
  74.     msg = MIMEMultipart()
  75.     msg['From'] = fromaddr
  76.     msg['To'] = ", ".join(toaddr)
  77.     msg['Subject'] = "Furry Fuel Automated Order System"
  78.      
  79.      
  80.     if count > 0:
  81.         body = "New orders for Furry Fuel - \n"
  82.         f = open(filename+"_sent.txt","r")
  83.         for line in f:
  84.             body += line
  85.         f.close()
  86.     else:
  87.         body = "There are no new orders for this period. Please review last 25 orders:\n"
  88.         f = open(filename+".txt","r")
  89.         for line in f:
  90.             body += line
  91.         f.close()
  92.     msg.attach(MIMEText(body, 'plain'))
  93.      
  94.     server = smtplib.SMTP('smtp.gmail.com', 587)
  95.     server.starttls()
  96.     server.login(fromaddr, email_password)
  97.     text = msg.as_string()
  98.     server.sendmail(fromaddr, toaddr, text)
  99.     server.quit()
  100.  
  101.    
  102. # All requests to the Square Connect API require an access token in an
  103. # Authorization header. Specify your application's personal access token here.
  104. # Available from the Application Dashboard: https://connect.squareup.com/apps
  105. from settings import access_token
  106.  
  107. # In addition to an Authorization header, requests to the Connect API should
  108. # include the indicated Accept and Content-Type headers.
  109. request_headers = {'Authorization': 'Bearer ' + access_token,
  110.                    'Accept':        'application/json',
  111.                    'Content-Type':  'application/json'}
  112.  
  113.  
  114. #Obtains store location and sets base_req_path.
  115. locations = get_data("/v1/me/locations")
  116. loc = locations[0]
  117. loc_id = loc['id']
  118. base_req_path = "/v1/"+loc_id
  119.  
  120.  
  121.  
  122. if __name__ == "__main__":
  123.     #Opens orders.txt for writing
  124.     filename = datetime.date.today().isoformat()
  125.    
  126.     f = open(filename+".txt","w")
  127.     f_send = open(filename+"_sent.txt","w")
  128.     f.write("---------------")
  129.     f_send.write("---------------")
  130.    
  131.     #Obtains list of all orders, max 200, starting most recent
  132.     req_path = base_req_path+"/orders?order=DESC&limit=25"
  133.  
  134.     orders = get_data(req_path)
  135.     count = 0
  136.     for order in orders:
  137.  
  138.         #Checks for OPEN status orders that are awaiting being processed. Appends to Orders To Send, runs Output.
  139.         output_order(order,f,state=True)
  140.         if order['state'] == "OPEN":
  141.             count += 1
  142.            
  143.             #Need to alter the data on Square via PUT. The request_body of get_data() needs to be a json.
  144.             body = json.dumps({'action': 'COMPLETE',
  145.             '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!" })
  146.             req_path = base_req_path+"/orders/"+order['id']
  147.            
  148.             #Using Get_Data to send the Put and push alterations. Get_Data would return the modified.
  149.             x = get_data(req_path, request_body=body, get_put="PUT")
  150.            
  151.             #For verification
  152.             output_order(x,f_send)
  153.  
  154.     f.close()
  155.     f_send.close()
  156.     send_email(filename,count)
Advertisement
Add Comment
Please, Sign In to add comment