def __init__(self, **kwargs): self.validate_kwargs(**kwargs) with open(kwargs.get('key_file')) as file_key: rsa_key = file_key.read() credentials = PrivateCredentials(kwargs.get('consumer_key'), rsa_key) super(self.__class__, self).__init__(credentials)
def generate_account_number(profile): if "XERO_CONSUMER_KEY" in os.environ and "XERO_RSA_FILE" in os.environ: with open(os.environ.get('XERO_RSA_FILE')) as keyfile: rsa_key = keyfile.read() credentials = PrivateCredentials(os.environ.get('XERO_CONSUMER_KEY'), rsa_key) xero = Xero(credentials) contacts = xero.contacts.filter(includeArchived=True) for x in range(100, 999): account_number = profile.first_name[ 0] + profile.last_name[:2] + str(x) account_number = account_number.upper() if not any( d.get('AccountNumber', None) == account_number for d in contacts): profile.xero_account_number = account_number profile.save() print("Generated Xero Account: " + account_number) return profile.xero_account_number else: return False
def connect(self, request, company): """ Connects a company to Xero company must be included in the querystring /?company=<id> """ try: secret_keys = Utils.get_access_keys(company) consumer_key = secret_keys.client_id consumer_secret = secret_keys.client_secret global credentials call_back_uri = settings.XERO_CALL_BACK_URI + "/" + company # call_back_url = 'http://localhost/oauth' if AccountingConfiguration.PRIVATE == secret_keys.type: credentials = PrivateCredentials(consumer_key=consumer_key,rsa_key=consumer_secret) OAUTH_PERSISTENT_SERVER_STORAGE.update({'consumer_key':credentials.consumer_key}) OAUTH_PERSISTENT_SERVER_STORAGE.update({'rsa_key':credentials.rsa_key}) url = call_back_uri else: credentials = PublicCredentials(consumer_key, consumer_secret, callback_uri=call_back_uri) # Save generated credentials details to persistent storage for key, value in credentials.state.items(): OAUTH_PERSISTENT_SERVER_STORAGE.update({key: value}) LoginInfo.objects.create(company_id=company, status=LoginInfo.IN_PROGRESS, created=timezone.now()) url = credentials.url except Exception as e: auth_cancel_url = settings.QBO_AUTH_CANCEL_URL Utils.send_company_misconfig(company,e) return redirect(auth_cancel_url + '/error') return Utils.redirect_response(url)
def getCredentials(self, Renew=False): # Path = '/home/deepav/Desktop/privatekey.pem' # ConsumerKey = 'VNUIOH588GCAH6JMJVQXSEVTICLEU5' Config = request.env["ir.config_parameter"] Path = Config.sudo().get_param('xero.pem.path') ConsumerKey = Config.sudo().get_param('xero.consumer.key', default='') if Path == '/': _logger.warning('Xero Credentials Not Found: Pem file path missing !!') return False if ConsumerKey == '/': _logger.warning('Xero Credentials Not Found: Consumer Key missing !!') return False if Renew or not self._credentials: rsa_key = '' with open(Path) as keyfile: rsa_key = keyfile.read() credentials = PrivateCredentials(ConsumerKey, rsa_key) self._credentials = credentials else: credentials = self._credentials xero = False try: xero = Xero(credentials) except: e = sys.exc_info()[1] _logger.warning('Xero Credentials: %s'%(str(e))) return xero
def pyCreateInvoice(ContactID, cYear, cMonth, cDay, dYear, dMonth, dDay, vbLineItems): from xero import Xero from xero.auth import PrivateCredentials from ast import literal_eval import datetime with open(r"PATH TO YOUR PRIVATEKEY.PEM REGISTERED ON XERO") as keyfile: rsa_key = keyfile.read() credentials = PrivateCredentials("CONSUMER KEY HERE", rsa_key) xero = Xero(credentials) evalLineItems = literal_eval(vbLineItems) original = { 'Type': 'ACCREC', 'Contact': { 'ContactID': ContactID }, 'Date': datetime.date(cYear, cMonth, cDay), 'DueDate': datetime.date(dYear, dMonth, dDay), 'Status': 'DRAFT', 'LineAmountTypes': 'Exclusive', 'LineItems': evalLineItems, } pyInvoiceID = xero.invoices.put(original)[0]['InvoiceID'] pyInvoiceNumber = xero.invoices.get(pyInvoiceID)[0]['InvoiceNumber'] response = [pyInvoiceID, pyInvoiceNumber] return response
def __init__(self): print XERO_PATH_CERTIFICATE with open(XERO_PATH_CERTIFICATE) as keyfile: rsa_key = keyfile.read() credentials = PrivateCredentials(XERO_CONSUMER_KEY, rsa_key) self.credentials = credentials self.xero = Xero(credentials)
def XeroConnect(): #C:\Users\timbi\source\repos\JmanOps\JmanOps\app\static\app\xero with open(XERO_PRIVATE_KEY) as keyfile: rsa_key = keyfile.read() credentials = PrivateCredentials(XERO_CONSUMER_KEY, rsa_key) xero = Xero(credentials) return xero
def get_xero_contact(user): """ Returns an object with the xero contact details or None if it doesn't exist. :return: """ if "PORTAL_XERO_CONSUMER_KEY" in os.environ: with open(xero_rsa) as keyfile: rsa_key = keyfile.read() credentials = PrivateCredentials( os.environ.get("PORTAL_XERO_CONSUMER_KEY"), rsa_key) xero = Xero(credentials) email = xero.contacts.filter(EmailAddress=user.profile.email) name = xero.contacts.filter(Name=user.profile.get_full_name()) if email: return email elif name: return name return None else: return "Invalid Xero API details."
def generate_account_number(profile): if "PORTAL_XERO_CONSUMER_KEY" in os.environ: with open(xero_rsa) as keyfile: rsa_key = keyfile.read() credentials = PrivateCredentials( os.environ.get("PORTAL_XERO_CONSUMER_KEY", "/usr/src/data/xerkey.pem"), rsa_key, ) xero = Xero(credentials) contacts = xero.contacts.filter(includeArchived=True) for x in range(100, 999): account_number = profile.first_name[ 0] + profile.last_name[:2] + str(x) account_number = account_number.upper() if not any( d.get("AccountNumber", None) == account_number for d in contacts): profile.xero_account_number = account_number profile.save() print("Generated Xero Account: " + account_number) return profile.xero_account_number else: return False
def ready(self): with open(settings.XERO_CONFIG['private_key_file']) as keyfile: rsa_key = keyfile.read() credentials = PrivateCredentials(settings.XERO_CONFIG['consumer_key'], rsa_key) self.xero = Xero(credentials) super().ready()
def xero_post_contact(cleaned_data, contact_number): credentials = PrivateCredentials(settings.XERO_CREDENTIALS, settings.XERO_PRIVATE_KEY) xero = Xero(credentials) lookup_contact = xero.contacts.filter(ContactNumber=contact_number) if lookup_contact: return lookup_contact[0]['ContactID'] name = "%s (%s %s)" % (cleaned_data['organisation'], cleaned_data['name_first'], cleaned_data['name_last']) contact = { 'Addresses': [{ 'AddressType': 'POBOX', 'City': cleaned_data['city'], 'Country': cleaned_data['country'], 'PostalCode': cleaned_data['postcode'], 'Region': cleaned_data['region'], 'AddressLine1': cleaned_data['street_line_one'], 'AddressLine2': cleaned_data['street_line_two'], 'AddressLine3': cleaned_data['street_line_three'], }], 'EmailAddress': cleaned_data['email'], 'Name': name, 'ContactNumber': contact_number } results = xero.contacts.put(contact) contact = results[0] return contact['ContactID']
def __init__(self): with open('config.json') as config_file: self.config = json.load(config_file) with open('keys/privatekey.pem', 'r') as keyfile: rsa_key = keyfile.read() credentials = PrivateCredentials(self.config['consumer_key'], rsa_key) self.xero = xero = Xero(credentials)
def get_xero_client(): xeroIntegration = XeroIntegration.objects.first() consumer_key = xeroIntegration.consumer_key rsa_key = xeroIntegration.rsa_key credentials = PrivateCredentials(consumer_key, rsa_key) xero = Xero(credentials) return xero
def test_xero(id="INV4093"): # from xero import Xero # from xero.auth import PublicCredentials consumer_key = "06RRGPYM4SJXFEMRODT6F0GYJ42UKA" # consumer_secret = "COMNDKTM2AU54WADYU1I1YVBBRE4ZL" # credentials = PublicCredentials(consumer_key, consumer_secret) # print credentials.url from xero import Xero from xero.auth import PrivateCredentials import os file = "privatekey.pem" with open(os.path.dirname(os.path.abspath(__file__)) + '/data/' + file) as keyfile: rsa_key = keyfile.read() # print rsa_key credentials = PrivateCredentials(consumer_key, rsa_key) xero = Xero(credentials) invoices = xero.invoices.filter(raw='AmountDue > 0') # invoices = xero.invoices.filter(InvoiceNumber="INV4093") for inv in invoices: print inv inv = xero.invoices.get(inv['InvoiceNumber'])[0] inv_name = frappe.db.sql("""SELECT name FROM `tabSales Invoice` WHERE docstatus=1 AND outstanding_amount = 0.0 and name=%s""",(inv['InvoiceNumber'])) exists_so = frappe.db.sql("""SELECT Count(*) FROM `tabSales Order` WHERE name=%s""",(inv['InvoiceNumber'])) print ">>>>>>>>>>>", inv_name if inv_name != () and exists_so[0][0] != 0: # created_at = parser.parse(inv["Date"]) created_at = inv["Date"] # remove_imported_data(inv['InvoiceNumber']) remove_imported_data(inv['Reference']) pi = make_invoice(inv['Reference'], created_at, inv) # print inv frappe.db.commit() rename_doc("Sales Invoice", pi.name, inv['InvoiceNumber'], force=True) frappe.db.commit() if inv['AmountPaid']: payment_request = make_payment_request(dt="Sales Invoice", dn=inv['InvoiceNumber'], recipient_id="", submit_doc=True, mute_email=True, use_dummy_message=True, grand_total=float(inv['AmountPaid']), posting_date=created_at.date(), posting_time=str(created_at.time()), inflow_file=inv['Reference']) payment_entry = frappe.get_doc(make_payment_entry(payment_request.name)) payment_entry.posting_date = created_at.date() payment_entry.posting_time = str(created_at.time()) payment_entry.set_posting_time = 1 payment_entry.paid_amount = inv['AmountPaid'] payment_entry.inflow_file = inv['Reference'] payment_entry.submit()
def test_configurable_url(self): "Test configurable API url" url = "https//api-tls.xero.com" credentials = PrivateCredentials(consumer_key="key", rsa_key="rsa_key", api_url=url) self.assertEqual(credentials.base_url, url)
def __init__(self, config): self.session = requests.Session() if config["xero_app_type"] == "private": credentials = PrivateCredentials( config["consumer_key"], config["rsa_key"]) self.oauth = credentials.oauth else: self.oauth = build_oauth(config) self.user_agent = config.get("user_agent")
def configure(self, context): super().configure(context) con_key = self.consumer_key() with open('blocks/xero/keys/privatekey.pem') as keyfile: rsa_private_key = keyfile.read() self.credentials = PrivateCredentials(con_key, rsa_private_key) self.xero = Xero(self.credentials)
def __init__(self, config): self.config = config stripe.api_key = config.get('stripe', 'secret_key') with open(config.get('xero', 'private_key_file')) as keyfile: rsa_key = keyfile.read() credentials = PrivateCredentials(config.get('xero', 'consumer_key'), rsa_key) self.xero = Xero(credentials)
def xero_api(request): # Connect to Xero with open('privatekey.pem') as keyfile: rsa_key = keyfile.read() credentials = PrivateCredentials('MQNHWHQUGCSSIW1DBOJ7460LUCIR2O',rsa_key) xero = Xero(credentials) # Get all Yachts from Xero tracking_categories=xero.trackingcategories.filter(Name='Yacht') yachts = tracking_categories[0]['Options'] # Create list of all yachts from Xero xero_yachts = [] for yacht in yachts: xero_yachts.append(yacht['Name']) print (xero_yachts) # print (json.dumps(yachts, indent=1)) # Connect to airtable airtable = Airtable('appf5QcGhI1kMEZq7', 'Boats') # Get all boat names from airtable boat_names = airtable.get_all(fields=['Boat Name']) # Create list of all yachts from airtable air_yachts = [] for boat in boat_names: air_yachts.append(boat['fields']['Boat Name']) print (air_yachts) # print (json.dumps(boats, indent=1)) # Compare boat names and create list of boats to add to xero add_to_xero = [] for air_yacht in air_yachts: if air_yacht in xero_yachts: pass else: add_to_xero.append(air_yacht) # print('add to xero:', add_to_xero) xero_test = "New yacht" print (xero_test) xero.trackingcategories.put({'Name': 'Yacht', 'Options': {'Name': 'new_yachts', 'Status': 'ACTIVE'}}) # xero.contacts.put({'Name': 'New Xero Contact by Dave'}) THIS WORKED! '''for yacht_to_add in add_to_xero: xero.trackingcategories.put([{"TrackingCategoryID": "f645671f-db5b-4399-8501-f86a734f2eb5",'Name':yacht_to_add}]) ''' # Check projects functionality - SPOLIER: AttributeError: 'Xero' object has no attribute 'projects' projects = xero.projects.all() print (projects) return render(request, "xero_api.html")
def xero_get_payment_gateway(invoice_uuid): credentials = PrivateCredentials(settings.XERO_CREDENTIALS, settings.XERO_PRIVATE_KEY) xero = Xero(credentials) onlineinvoice_url = "%s/OnlineInvoice" % (invoice_uuid, ) invoice = xero.invoices.get(onlineinvoice_url) href = "%s?utm_source=emailpaynowbutton#paynow" % ( invoice['OnlineInvoices'][0]['OnlineInvoiceUrl'], ) return href
def xero_connect(): XERO_PRIVATE_KEYFILE = os.environ.get('XERO_PRIVATE_KEYFILE', None) XERO_CONSUMER_KEY = os.environ.get('XERO_CONSUMER_KEY', None) if XERO_PRIVATE_KEYFILE is None: raise Exception('XERO_PRIVATE_KEYFILE is not set') if XERO_CONSUMER_KEY is None: raise Exception('XERO_CONSUMER_KEY is not set') with open(XERO_PRIVATE_KEYFILE) as keyfile: rsa_key = keyfile.read() credentials = PrivateCredentials(XERO_CONSUMER_KEY, rsa_key) # used to connect to xero return Xero(credentials)
def get_invoice(request): with open(r'C:\Program Files\OpenSSL-Win64\bin\privatekey.pem' ) as keyfile: rsa_key = keyfile.read() credentials = PrivateCredentials('R5P0XUAGIBH2ARAHEUEPVFOEHRSOX7', rsa_key) xero = Xero(credentials) invoice_id = request.GET.get('invoice_id') xero_data = xero.invoices.filter(InvoiceID=invoice_id) return HttpResponse(xero_data)
def get_expenses(): from xero import Xero consumer_key = "06RRGPYM4SJXFEMRODT6F0GYJ42UKA" from xero.auth import PrivateCredentials import os file = "privatekey.pem" with open(os.path.dirname(os.path.abspath(__file__)) + '/data/' + file) as keyfile: rsa_key = keyfile.read() # print rsa_key credentials = PrivateCredentials(consumer_key, rsa_key) xero = Xero(credentials) print xero.expenseclaims.all()
def get_xero_instance(): ''' Returns an instance of the xero API connection :return: xero instance ''' with open(rp.PRIVATE_KEY_LOCATION) as keyfile: rsa_key = keyfile.read() credentials = PrivateCredentials(consumer_key=rp.CONSUMER_KEY, rsa_key=rsa_key) xero = Xero(credentials) return xero
def __init__(self, config): self.config = config with open(config.get('xero', 'private_key_file')) as keyfile: rsa_key = keyfile.read() credentials = PrivateCredentials(config.get('xero', 'consumer_key'), rsa_key) self.xero = Xero(credentials) gocardless.environment = config.get('gocardless', 'environment') gocardless.set_details(app_id=config.get('gocardless', 'app_id'), app_secret=config.get('gocardless', 'app_secret'), access_token=config.get('gocardless', 'access_token'), merchant_id=config.get('gocardless', 'merchant_id')) self.gc_client = gocardless.client
def get_contacts(): rsa_key_file = 'private/privatekey.pem' rsa_key_data = '' with open(rsa_key_file) as keyfile: rsa_key_data = keyfile.read() logging.info("rsa_key_data:\n%s" % rsa_key_data) from private import secret from xero import Xero from xero.auth import PrivateCredentials credentials = PrivateCredentials(secret.consumer_key, rsa_key_data) xero = Xero(credentials) all_contacts = xero.contacts.all() return all_contacts
def get_invoices(request): with open(r'C:\Program Files\OpenSSL-Win64\bin\privatekey.pem' ) as keyfile: rsa_key = keyfile.read() credentials = PrivateCredentials('R5P0XUAGIBH2ARAHEUEPVFOEHRSOX7', rsa_key) xero = Xero(credentials) xero_id = request.GET.get('xero_id') xero_data = xero.invoices.filter(Contact_ContactID=xero_id, order='DueDateString DESC', page=1) return JsonResponse({'xero_data': list(xero_data)})
def __init__(self, consumer_key, **kwargs): PKG_LOGGER.debug( "xero API args: consumer_key: %s, kwargs: %s", consumer_key, kwargs ) rsa_key = kwargs.get("rsa_key_raw") if not rsa_key: rsa_key_path = kwargs.get("rsa_key_path") rsa_key_path = os.path.expanduser(rsa_key_path) with open(rsa_key_path) as key_file: rsa_key = key_file.read() credentials = PrivateCredentials(consumer_key, rsa_key) super().__init__(credentials)
def xero_post_invoice(contact_id, unique_reference_id, quote, lines): credentials = PrivateCredentials(settings.XERO_CREDENTIALS, settings.XERO_PRIVATE_KEY) xero = Xero(credentials) today = date.today() due = date.today() + timedelta(days=30) if quote['vat_rate_percent'] == '0': if quote['Address::country_iso2'] in european_country: tax_type = 'ECZROUTPUTSERVICES' else: tax_type = 'ZERORATEDOUTPUT' else: tax_type = 'OUTPUT2' invoice = { 'Contact': { 'ContactID': contact_id, }, 'Date': today, 'DateString': today, 'DueDate': due, 'DueDateString': due, 'IsDiscounted': False, 'LineAmountTypes': 'Exclusive', 'LineItems': [], 'Reference': unique_reference_id, 'Status': 'AUTHORISED', 'Type': 'ACCREC', } for line in lines: description = "%s (quote: %s)" % (line['description'], quote['reference']) invoice['LineItems'].append({ "Description": description, "Quantity": line['quantity'], "UnitAmount": line['price'], "TaxType": 'OUTPUT2', "AccountCode": "REV-STD", ## TODO: lookup for account codes "TaxType": tax_type #TODO ItemCode }) results = xero.invoices.put(invoice) invoice = results[0] return invoice['InvoiceID']
def pyAttachPDF(fName, fPath, invID): from xero import Xero from xero.auth import PrivateCredentials from ast import literal_eval from os import chdir import datetime with open(r"PATH TO YOUR PRIVATEKEY.PEM REGISTERED ON XERO") as keyfile: rsa_key = keyfile.read() credentials = PrivateCredentials("CONSUMER KEY HERE", rsa_key) xero = Xero(credentials) chdir(fPath) pyFile = open(fName, 'rb') xero.invoices.put_attachment(invID, fName, pyFile, 'application/pdf') pyFile.close()