Beispiel #1
0
def connect(plaid_credentials, bank, bank_credentials):
    client = Client(client_id=plaid_credentials.client_id, secret=plaid_credentials.secret)
    try:
        response = client.connect(bank, {
            'username': bank_credentials.username,
            'password': bank_credentials.password
        })

        data = json.loads(response.content)
        if response.status_code == 200:
            print data
            if "access_token" in data:
                client_access_token = data["access_token"]
                client = Client(client_id=plaid_credentials.client_id, secret=plaid_credentials.secret, access_token=client_access_token)
                response = client.connect_get()
                data = json.loads(response.content)
                with open("tx.json", "w") as f:
                    f.write(json.dumps(data))
        else:
            print "Something went horribly wrong..."
            print data

    except plaid_errors.UnauthorizedError as e:
         # handle this
        print e
Beispiel #2
0
    def requestTransactions(self):
        if "token" not in self.credentials["plaid"]:
            client = Client(client_id=self.credentials["plaid"]["client"],
                            secret=self.credentials["plaid"]["secret"])
            data = ""
            try:
                response = client.connect(self.bank, {
                    'username': self.login,
                    'password': self.password
                })
                data = response.json()
            except plaid_errors.UnauthorizedError as e:
                print("AHHH")
                print(e.message)
                exit()
            token = data['access_token']
            self.credentials["plaid"]["token"] = token

        client = Client(client_id=self.credentials["plaid"]["client"],
                        secret=self.credentials["plaid"]["secret"],
                        access_token=self.credentials["plaid"]["token"])
        if self.debug == True:
            options = {'pending': True, 'gte': '2017/01/01'}
        else:
            options = {'pending': True, 'gte': self.gte}
        response = client.connect_get(opts=options)
        self.data = response.json()
Beispiel #3
0
def create_client():
    '''Create a new client for testing.'''
    return Client(client_id=os.environ['CLIENT_ID'],
                  secret=os.environ['SECRET'],
                  environment='sandbox',
                  api_version="2019-05-29",
                  client_app="plaid-python-unit-tests")
    def setUp(self):
        """Initialization for the test cases

        This is executed prior to each test.
        """
        application.config['TESTING'] = True
        application.config['WTF_CSRF_ENABLED'] = False
        application.config['DEBUG'] = False
        self.app = application.test_client()
        # setup plaid client
        self.client = Client(ENV_VARS["PLAID_CLIENT_ID"],
                             ENV_VARS["PLAID_SECRET"],
                             ENV_VARS["PLAID_PUBLIC_KEY"], "sandbox")
        self.public_token = sandbox.PublicToken(self.client)
        db.drop_all()
        db.create_all()

        # Create a test user and test plaid item
        self.test_user = classes.User(first_name="first",
                                      last_name="last",
                                      email="*****@*****.**",
                                      phone="9876543210",
                                      password="******")
        db.session.add(self.test_user)
        db.session.commit()
        self.test_item = classes.PlaidItems(user=self.test_user,
                                            item_id="item",
                                            access_token="token")
        db.session.add(self.test_item)
        db.session.commit()
Beispiel #5
0
def test_institution():
    client = Client('test_id', 'test_secret')
    response = client.institution(
      to_json(client.institutions())[0]['id']
    )

    assert response.status_code == 200
Beispiel #6
0
def create_client():
    '''Create a new client for testing.'''
    return Client(os.environ['CLIENT_ID'],
                  os.environ['SECRET'],
                  os.environ['PUBLIC_KEY'],
                  'sandbox',
                  api_version="2017-03-08")
    def __init__(self, cache: Path = PLAID_CACHE, **kwargs) -> None:
        """
        cache: File to read/write transaction data from
        kwargs:
            CLIENT_ID
            SECRET
            PUBLIC_KEY
            ENV
            CHASE_TOKEN
        """
        self._CLIENT_ID = kwargs.get("CLIENT_ID", CLIENT_ID)
        self._SECRET = kwargs.get("SECRET", SECRET)
        self._PUBLIC_KEY = kwargs.get("PUBLIC_KEY", PUBLIC_KEY)
        self._ENV = kwargs.get("ENV", ENV)
        self._CHASE_TOKEN = kwargs.get("CHASE_TOKEN", CHASE_TOKEN)

        self._client = Client(
            self._CLIENT_ID, self._SECRET, self._PUBLIC_KEY, self._ENV
        )
        self._end_date = datetime.date.today().isoformat()
        self._get_chase_transactions = partial(
            self._client.Transactions.get, self._CHASE_TOKEN
        )

        self.cache = cache
        self._read()
def plaidclient():
    config = {
        'client_id': settings.PLAID_CLIENT_ID,
        'secret': settings.PLAID_SECRET,
        'environment': settings.PLAID_ENV
    }
    return Client(**config)
Beispiel #9
0
    def load_statements_line_from_plaid(
            self,
            id_plaid='584f8ac239361943b6a40c2f',
            id_secret='2eb94d1cfb298020b6d4c1e396eb75',
            access_token='test_bofa'):
        # get transactions
        _logger.warning('\n\n\n Respuesta1: \n \n\n\n')

        client = Client(client_id=id_plaid,
                        secret=id_secret,
                        access_token='test_bofa')
        #PARA DELIMITAR CON FECFA response = client.connect_get(opts={'gte':'2014-06-01'}).json()
        response = client.connect_get().json()
        accounts = client.auth_get().json()
        #transactions = response.json()

        _logger.info('\n\n\n transaccion: \n %s \n\n\n' %
                     response['transactions'][0])

        _logger.info('\n\n\n Numero de Cuenta: \n %s \n\n\n' %
                     accounts['accounts'][2]['numbers']['account'])
        _logger.info('\n\n\n id de la cuenta: \n %s \n\n\n' %
                     accounts['accounts'][2]['_id'])
        _logger.info('\n\n\n id de la Cuenta en la transaccion: \n %s \n\n\n' %
                     response['transactions'][0]['_account'])
        _logger.info('\n\n\n Monto de la transaccion: \n %s \n\n\n' %
                     response['transactions'][0]['amount'])
        _logger.info('\n\n\n fecha de la transaccion: \n %s \n\n\n' %
                     response['transactions'][0]['date'])
        _logger.info(
            '\n\n\n nombre del partner que realiza transaccion: \n %s \n\n\n' %
            response['transactions'][0]['name'])

        #for account in accounts['accounts']:

        values = []
        for resp in response['transactions']:
            values.append((0, 0, {
                'name': resp['name'],
                'ref': resp['_id'],
                'amount': resp['amount'],
                'date': resp['date']
            }))

        #OBSOLETO
        #new_id = self.env['account.bank.statement'].create({'name':"Prueba5", 'journal_id':6, 'line_ids': [(0,0,{'name': 'pruebaline', 'ref': '00002-line', 'amount': 100})]})
        #new_id = self.env['account.bank.statement'].create({'name':"Prueba5", 'journal_id':6, 'line_ids': [(0,0,{'name': response['transactions'][0]['name'],
        #																										 'ref': response['transactions'][0]['_id'],
        #																										 'amount': response['transactions'][0]['amount'],
        #																										 'date': response['transactions'][0]['date']
        #																										 })]})
        #

        new_id = self.env['account.bank.statement'].create({
            'name': "Prueba5",
            'journal_id': 6,
            'line_ids': values
        })
        return True
Beispiel #10
0
 def __init__(self, subscriptions_table_filename,
              plaid_credentials_filename, bank_credentials_filename):
     self.subscriptions_table = pd.read_csv(subscriptions_table_filename)
     with open(plaid_credentials_filename, 'r') as f:
         self.client = Client(**json.load(f), environment='development')
     with open(bank_credentials_filename, 'r') as f:
         self.access_token = json.load(f)['access_token']
     self.client.Auth.get(self.access_token)
Beispiel #11
0
def create_client():
    '''Create a new client for testing.'''
    return Client(os.environ['CLIENT_ID'],
                  os.environ['SECRET'],
                  os.environ['PUBLIC_KEY'],
                  'sandbox',
                  api_version="2019-05-29",
                  client_app="plaid-python-unit-tests")
Beispiel #12
0
 def get(self, user):
     userData = User.get(User.username == user)
     userData = model_to_dict(userData)
     access_token = userData['accessToken']
     #print(access_token)
     client = Client(client_id=id, secret=secret, access_token=access_token)
     transactions = client.connect_get().json()
     return transactions
Beispiel #13
0
def test_connect_mfa_list():
    client = Client('test_id', 'test_secret')
    # These credentials erroneously still force mfa in the sandbox
    # Should disambiguate by disallowing institution on API level
    # for this particular calling
    response = client.connect('chase', no_mfa_credentials)
    assert response.status_code == 201
    assert to_json(response)['type'] == 'list'
Beispiel #14
0
def test_connect_step_device_email():
    client = Client('test_id', 'test_secret', access_token='test_chase')
    response = client.connect_step('chase', None, options={
      'send_method': {'type': 'email'}
    })
    assert response.status_code == 201
    assert to_json(response)['type'] == 'device'
    assert to_json(response)['mfa']['message'] == 'Code sent to [email protected]'
Beispiel #15
0
 def get(self, user):
     userData = User.get(User.username == user)
     userData = model_to_dict(userData)
     access_token = userData['accessToken']
     #print(access_token)
     client = Client(client_id=id, secret=secret, access_token=access_token)
     balance = client.balance().json()
     return balance
Beispiel #16
0
    def __init__(self, client_id=None, secret=None):
        if client_id and secret:
            self.client_id = client_id
            self.secret = secret
        else:
            self.client_id, self.secret = cm.get_plaid_config()

        self.client = Client(self.client_id, self.secret, "development", suppress_warnings=True)
Beispiel #17
0
def test_ResourceNotFound_categories_with_suppressed_error():
    Client.config({'suppress_http_errors': True})
    client = Client('test_id', 'test_secret')
    response = client.category('pnc')
    assert response.status_code == 404
    assert (
      json.loads(response.content)['message'] == 'unable to find category'
    )
Beispiel #18
0
 def get(self, user):
     userData = User.get(User.username == user)
     userData = model_to_dict(userData)
     access_token = userData['accessToken']
     #print(access_token)
     client = Client(client_id=id, secret=secret, access_token=access_token)
     #client.upgrade('info')
     info = client.info_get().json()
     return info
Beispiel #19
0
def get_transactions():
    print('Which bank shall we pull transactions from?')
    bank = choices(banks)
    print('Please select the appropriate account:')
    account = choices(bank['accounts'])
    start_date = input("input a start date 'YYYY-MM-DD': ")
    end_date = input("input an end date 'YYYY-MM-DD': ")
    client = Client(client_id='5850e87d3936192710fb73fc',
                    secret='7c1a63bbe4fb6ddac2fb555244de05',
                    environment='development')
    response = client.Transactions.get(bank['token'],
                                       start_date=start_date,
                                       end_date=end_date)
    transactions = response['transactions']

    # the transactions in the response are paginated, so make multiple calls while increasing the offset to
    # retrieve all transactions
    while len(transactions) < response['total_transactions']:
        response = client.Transactions.get(bank['token'],
                                           start_date=start_date,
                                           end_date=end_date,
                                           offset=len(transactions))
        transactions.extend(response['transactions'])
    upload = ''
    display_title_bar()
    while upload.upper() != 'Y' and upload.upper() != 'N':
        upload = input(
            "Would you like to upload these transactions to Manager? [Y/N]: ")
        if upload.upper() == 'Y':
            for transaction in tqdm(transactions):
                if transaction['account_id'] == account['id']:
                    if transaction['amount'] < 0:
                        trans_type = 'Receipt'
                    else:
                        trans_type = 'Payment'
                    date = transaction['date']
                    bank_account = bank['manager_account']
                    description = transaction['name']
                    amount = abs(transaction['amount'])
                    data = receipts_payments(trans_type, date, bank_account,
                                             description, amount)
                    r = s.post(url + '699401fe-23fd-4b52-9699-b88b36fa6b26',
                               data=json.dumps(data))
                    if r.status_code == 201:
                        tqdm.write('Success!')
                    else:
                        tqdm.write(
                            f'Something went wrong. Error: {r.status_code}')
                        tqdm.write(json.dumps(data))
                else:
                    pass
        elif upload.upper() == 'N':
            display_title_bar()
            print('Very well, the transactions will not be uploaded')
        else:
            display_title_bar()
            print('The choice selected was not recognized. Try again.')
Beispiel #20
0
def get_plaid_client():
    Client.config({
        'url': settings.PLAID_API_URL
    })

    return Client(
        client_id=settings.PLAID_CLIENT_ID,
        secret=settings.PLAID_CLIENT_SECRET
    )
Beispiel #21
0
 def use_token(self, username):
     obj = SQLConnection()
     token = obj.get_plaid_token(username)
     self.client = Client(client_id='57cccae6cfbf49f67b01fd5a',
                          secret='2c13981884395fc691fda11148ed67',
                          access_token=token)
     response = self.client.connect_get(token)
     self.plaid_results = response.content
     return response.content
Beispiel #22
0
def exchangeToken(publicToken):
    #Takes sandbox secret
    client = Client(client_id='5b343307c323c00011448c73',
                    secret='1960ae345a207270c000ecf9698019',
                    public_key=publicToken,
                    environment='sandbox')
    exchangeResponse = client.Item.public_token.exchange(publicToken)
    print('ACCESS TOKEN: ' + exchangeResponse['access_token'])
    return exchangeResponse
Beispiel #23
0
def create_account(account):
    try:
        _create_directory_tree(FILE_DEFAULTS.config_file)
        config = configparser.ConfigParser(interpolation=None)
        config[account] = OrderedDict()
        plaid = config[account]
        client_id, secret = get_plaid_config()
        # client_id = prompt('Enter your Plaid client_id: ', validator=NullValidator())
        # plaid['client_id'] = client_id
        # secret = prompt('Enter your Plaid secret: ', validator=NullValidator())
        # plaid['secret'] = secret
        
        configs = {
            'user': {
                'client_user_id': '123-test-user-id',
            },
            'products': ['transactions'],
            'client_name': "Plaid Test App",
            'country_codes': ['US'],
            'language': 'en',
        }

        # create link token
        client = Client(client_id, secret, "development", suppress_warnings=True)
        response = client.LinkToken.create(configs)
        link_token = response['link_token']

        generate_auth_page(link_token)
        print("\n\nPlease open " + FILE_DEFAULTS.auth_file + " to authenticate your account with Plaid")
        public_token = prompt('Enter your public_token from the auth page: ', validator=NullValidator())
        # plaid['public_token'] = public_token

        response = client.Item.public_token.exchange(public_token)
        access_token = response['access_token']
        plaid['access_token'] = access_token
        item_id = response['item_id']
        plaid['item_id'] = item_id

        response = client.Accounts.get(access_token)

        accounts = response['accounts']

        print("\n\nAccounts:\n")
        for item in accounts:
            print(item['name'] + ":")
            print(item['account_id'])
        account_id = prompt('\nEnter account_id of desired account: ', validator=NullValidator())
        plaid['account'] = account_id

    except plaid_errors.ItemError as ex:
        print("    %s" % ex, file=sys.stderr )
        sys.exit(1)
    else:
        with open(FILE_DEFAULTS.config_file, mode='a') as f:
            config.write(f)
    return True
Beispiel #24
0
    def __init__(self):
        env = settings.PLAID_ENV
        if env not in ['production', 'development', 'sandbox']:
            raise ValueError('Incorrect value for PLAID_ENV in settings.')

        self.client = Client(
            client_id=settings.PLAID_CLIENT_ID,
            secret=settings.PLAID_SECRET,
            public_key=settings.PLAID_PUBLIC_KEY,
            environment=env)
Beispiel #25
0
 def __init__(self,
              client_id=None,
              secret=None,
              account_id=None,
              access_token=None):
     if client_id and secret:
         self.client_id = client_id
         self.secret = secret
     else:
         self.client_id, self.secret = cm.get_plaid_config()
     self.client = Client(client_id=self.client_id, secret=self.secret)
def get_plaid_client():
    try:
        client = Client(client_id=PLAID_CLIENT_ID,
                        secret=PLAID_SECRET_KEY,
                        public_key=PLAID_PUBLIC_KEY,
                        environment=PLAID_ENV)
        return client
    except Exception as e:
        logger.error(
            'Exception raised when trying to create Plaid client. Exception: {}'.format(e))
        raise Exception("Error creating Plaid client")
Beispiel #27
0
 def __init__(self):
     """
     Initializes an instance.
     NOTE: We don't use the Lazy pattern here because the Plaid Client caches access tokens between method calls.
     """
     self._client = Client(
         client_id=os.environ["PLAID_CLIENT_ID"],
         secret=os.environ["PLAID_SECRET"],
         public_key=os.environ["PLAID_PUBLIC_KEY"],
         environment=os.environ["PLAID_ENV"],
     )
Beispiel #28
0
def getTransaction(accessToken, startDate, endDate):
    publicToken = '707d6df9798a9bf35257173c18e86b'
    client = Client(client_id='5b343307c323c00011448c73',
                    secret='1960ae345a207270c000ecf9698019',
                    public_key=publicToken,
                    environment='sandbox')
    transactionResponse = client.Transactions.get(accessToken,
                                                  start_date=startDate,
                                                  end_date=endDate)
    transactions = transactionResponse['transactions']
    return transactions
Beispiel #29
0
def account_data(plaid_access_token):
    # Returns all account data for plaid_access_token account
    from plaid import Client

    client = Client(client_id='5a54dbbdefe64e49ca4ae233', secret='e46141f14d9a73d68f2dc58a7a9c3b',
                    public_key='cc5eca9a7b42c6fd2dee4ebad4e959', environment='sandbox')

    # Retrieve Auth information for the Item, which includes high-level
    # account information and account numbers for depository accounts.
    auth_response = client.Auth.get(plaid_access_token)
    return auth_response
Beispiel #30
0
def create_client():
    '''Create a new client for testing.'''
    if SESSION_MANAGER['session'] is None or SESSION_MANAGER['session'].closed:
        print('Opening aio http session!')
        SESSION_MANAGER['session'] = aiohttp.ClientSession()
    return Client(os.environ['CLIENT_ID'],
                  os.environ['SECRET'],
                  os.environ['PUBLIC_KEY'],
                  'sandbox',
                  SESSION_MANAGER['session'],
                  api_version="2019-05-29",
                  client_app="plaid-python-unit-tests")