Exemple #1
0
def get_accounts(django_user):
    plaid_user = getattr(django_user, 'plaid_user', False)
    if not plaid_user:
        logger.error("There is no Plaid user corresponding to user {0}".format(
            django_user))
        return None

    access_token = getattr(plaid_user, 'access_token', False)
    if not access_token:
        logger.error("User {0} has a Plaid User but no access token".format(
            django_user))
        return None

    client = PlaidClient(client_id=client_id,
                         secret=secret,
                         public_key=public_key,
                         environment=environment)
    try:
        resp = client.Accounts.get(access_token=access_token)
    except Exception as e:
        logger.error("Unable to retrieve plaid accounts for user {0}".format(
            django_user))
        logger.error(e)
        return None

    return resp['accounts']
Exemple #2
0
def create_plaid_client():
    '''Create a new client for testing.'''
    return PlaidClient(PLAID_CLIENT_ID,
                  PLAID_SECRET,
                  PLAID_PUBLIC_KEY,
                  'sandbox',
                  api_version="2019-05-29")
Exemple #3
0
def create_access_token(django_user, public_token):
    client = PlaidClient(client_id=client_id,
                         secret=secret,
                         public_key=public_key,
                         environment=environment)
    try:
        resp = client.Item.public_token.exchange(public_token)
    except Exception as e:
        logger.error(
            "Unable to exchange public token for access token for user {0}".
            format(django_user))
        logger.error(e)
        return False

    # else "client.access_token" should now be populated with
    # a valid access_token for making authenticated requests

    # Get the plaid user for this django user; make one if nec.
    if not getattr(django_user, 'plaid_user', False):
        plaid_user = PlaidUser(user=django_user)
        plaid_user.save()

    plaid_user = django_user.plaid_user
    plaid_user.access_token = resp['access_token']
    plaid_user.save()
    return True
Exemple #4
0
def register_stripe_user():
    """Create Stripe customer"""
    client = PlaidClient(client_id=PLAID_CLIENT_ID,
                         secret=PLAID_SECRET,
                         public_key=PLAID_PUBLIC_KEY,
                         environment=PLAID_ENV)

    # exchange_token_response is obtained from the Client-side aka front-end
    exchange_token_response = client.Item.public_token.exchange(public_token)

    access_token = exchange_token_response['access_token']
    response = client.Accounts.get(access_token)
    assert response['accounts'] is not None

    print("response:", response)
    account_id = response['accounts'][0]['account_id']

    access_token = exchange_token_response['access_token']

    stripe_response = client.Processor.stripeBankAccountTokenCreate(
        access_token, account_id)
    bank_account_token = stripe_response['stripe_bank_account_token']
    print(bank_account_token)

    return True
Exemple #5
0
def nook_number(event, lambda_context):
    PLAID_CLIENT_ID = os.environ['plaid_client_id']
    PLAID_SECRET = os.environ['plaid_secret']
    PLAID_PUBLIC_KEY = os.environ['plaid_public_key']
    PLAID_ACCESS_TOKEN = os.environ['plaid_access_token']

    TWILIO_ACCOUNT_SID = os.environ['twilio_account_sid']
    TWILIO_AUTH_TOKEN = os.environ['twilio_auth_token']

    plaid_client = PlaidClient(client_id=PLAID_CLIENT_ID,
                               secret=PLAID_SECRET,
                               public_key=PLAID_PUBLIC_KEY,
                               environment='development')

    response = plaid_client.Accounts.balance.get(PLAID_ACCESS_TOKEN)

    account_balance_data = response['accounts'][0]['balances']

    account_limit = account_balance_data['limit']
    account_available = account_balance_data['available']
    account_balance = '%.2f' % (account_limit - account_available)

    account_balance_string = f'You currently have a balance of ${account_balance} on your credit card.'
    print(account_balance_string)

    twilio_client = TwilioClient(TWILIO_ACCOUNT_SID, TWILIO_AUTH_TOKEN)

    print(twilio_client)

    message = twilio_client.messages.create(body=account_balance_string,
                                            from_=os.environ['from_number'],
                                            to=os.environ['to_number'])

    print(message)
Exemple #6
0
 def access_transactions(client_id,secret_key,public_key,env,access_token,str_date,end_date):
     plaid_client =  PlaidClient(client_id = client_id, secret=secret_key,
                       public_key=public_key, environment=env, api_version='2019-05-29',suppress_warnings = True)
     def get_trans(access_token : str,str_date:str, end_date:str):
         return plaid_client.Transactions.get(access_token,str_date,end_date)
     trans = get_trans(access_token,str_date,end_date)
     return trans
Exemple #7
0
def get_accounts(django_user):

    plaid_user = getattr(django_user, 'plaid_user', False)
    if not plaid_user:
        logger.error("There is no Plaid user corresponding to user {0}".format(
            django_user))
        return None

    # else
    access_token = getattr(plaid_user, 'access_token', False)
    if not access_token:
        logger.error("User {0} has a Plaid User but no access token".format(
            django_user))
        return None

    # else
    client = PlaidClient(client_id=client_id,
                         secret=secret,
                         access_token=access_token)
    resp = client.auth_get()
    if resp.status_code != 200:
        logger.error("Unable to retrieve client accounts for user {0}".format(
            django_user))
        return None

    # else
    return resp.json()['accounts']
Exemple #8
0
def create_client():
    '''Create a new client for testing.'''
    return PlaidClient(PLAID_CLIENT_ID,
                       PLAID_SECRET,
                       PLAID_PUBLIC_KEY,
                       'sandbox',
                       api_version="2019-05-29",
                       client_app="plaid-python-unit-tests")
Exemple #9
0
def create_public_token():
    """]
    Public tokens are coming from Plaid on the frontend, this function is
    purely for testing purposes.
    """
    client = PlaidClient(client_id=client_id,
                         secret=secret,
                         public_key=public_key,
                         environment=environment)
    resp = client.Item.create(credentials=dict(username='******',
                                               password='******'),
                              institution_id='ins_109508',
                              initial_products=['auth'])
    return resp
Exemple #10
0
def create_access_token(django_user, public_token):
    client = PlaidClient(client_id=client_id, secret=secret)
    resp = client.exchange_token(public_token)
    if resp.status_code != 200:
        logger.error(
            "Unable to exchange public token for access token for user {0}".
            format(django_user))
        return None

    # else "client.access_token" should now be populated with
    # a valid access_token for making authenticated requests

    # Get the plaid user for this django user; make one if nec.
    if not getattr(django_user, 'plaid_user', False):
        plaid_user = PlaidUser(user=django_user)
        plaid_user.save()

    plaid_user = django_user.plaid_user
    plaid_user.access_token = client.access_token
    plaid_user.save()
    return True
Exemple #11
0
def get_stripe_account_token(django_user, plaid_account_id):
    """
    Retrieves a stripe_bank_account_token for plaid-stripe integration.
    """
    plaid_user = getattr(django_user, 'plaid_user', False)
    if not plaid_user:
        logger.error("There is no Plaid user corresponding to user {0}".format(
            django_user))
        return None

    access_token = getattr(plaid_user, 'access_token', False)
    if not access_token:
        logger.error("User {0} has a Plaid User but no access token".format(
            django_user))
        return None

    client = PlaidClient(client_id=client_id,
                         secret=secret,
                         public_key=public_key,
                         environment=environment)
    try:
        stripe_response = client.Processor.stripeBankAccountTokenCreate(
            access_token, plaid_account_id)
    except Exception as e:
        logger.error(
            "Unable to create stripe bank account token for user {} account_id {}"
            .format(django_user, plaid_account_id))
        logger.error(e)
        return None

    bank_account_token = stripe_response.get('stripe_bank_account_token', None)
    if bank_account_token is None:
        logger.error("Unable to exchange token")
        logger.error(stripe_response)

    return bank_account_token
import os
from pprint import pprint
from typing import List
from plaid import Client as PlaidClient

plaid_client = PlaidClient(client_id=os.getenv('PLAID_CLIENT_ID'),
                           secret=os.getenv('PLAID_SECRET'),
                           public_key=os.getenv('PLAID_PUBLIC_KEY'),
                           environment=os.getenv('PLAID_ENV'))


def get_bank_transactions(access_token: str, start_date: str,
                          end_date: str) -> List[dict]:
    return plaid_client.Transactions.get(access_token,
                                         start_date,
                                         end_date,
                                         count=500)


#def get_bank_balance(access_token: str):
#	return plaid_client.Accounts.Balance.get(access_token)

wells_bank_transactions = get_bank_transactions(
    os.getenv('WELLS_ACCESS_TOKEN'), '1972-01-01', '2020-05-26')

coastal_bank_transactions = get_bank_transactions(
    os.getenv("COASTAL_ACCESS_TOKEN"), '1972-01-01', '2020-05-26')
# bank_balance = get_bank_balance(os.getenv('WELLS_ACCESS_TOKEN'))

print(
    f'Wells Fargo: there are {wells_bank_transactions["total_transactions"]} total transactions between those dates.'
Exemple #13
0
import logging
import re
import hashlib
import os
import datetime
import requests

from plaid import Client as PlaidClient

# Logging
log = logging.getLogger(__name__)

# Plaid
plaid_client = PlaidClient(client_id=os.environ["PLAID_CLIENT_ID"],
                           secret=os.environ["PLAID_SECRET"],
                           public_key=os.environ["PLAID_PUBLIC_KEY"],
                           environment=os.environ["PLAID_ENV"])


def get_transactions(item_id, access_token, redis, get_inserted=False):
    transactions_key = "bank:transactions:" + item_id
    done = False
    accounts_loaded = False

    date_from = (datetime.datetime.now() -
                 datetime.timedelta(weeks=4)).strftime("%Y-%m-%d")
    date_to = datetime.datetime.now().strftime("%Y-%m-%d")

    transactions = []
    offset = 0
def budget_notifier(event, context):
    def get_creds(session):
        ssm = session.client('ssm')
        client_id = ssm.get_parameter(
            Name='/daily_budget_notification/client_id', WithDecryption=True)
        secret_key = ssm.get_parameter(
            Name='/daily_budget_notification/secret_key', WithDecryption=True)
        public_key = ssm.get_parameter(
            Name='/daily_budget_notification/public_key', WithDecryption=True)
        environment = ssm.get_parameter(
            Name='/daily_budget_notification/environment')
        discover_tkn = ssm.get_parameter(
            Name='/daily_budget_notification/tokens/discover',
            WithDecryption=True)
        chase_tkn = ssm.get_parameter(
            Name='/daily_budget_notification/tokens/chase',
            WithDecryption=True)
        amex_tkn = ssm.get_parameter(
            Name='/daily_budget_notification/tokens/amex', WithDecryption=True)
        steven_cell = ssm.get_parameter(
            Name='/daily_budget_notification/contact/steven_cell',
            WithDecryption=True)
        michelle_cell = ssm.get_parameter(
            Name='/daily_budget_notification/contact/michelle_cell',
            WithDecryption=True)

        cl_id = client_id['Parameter']['Value']
        s_key = secret_key['Parameter']['Value']
        p_key = public_key['Parameter']['Value']
        envmnt = environment['Parameter']['Value']
        d_tkn = discover_tkn['Parameter']['Value']
        c_tkn = chase_tkn['Parameter']['Value']
        a_tkn = amex_tkn['Parameter']['Value']
        s_cell = steven_cell['Parameter']['Value']
        m_cell = michelle_cell['Parameter']['Value']

        return cl_id, s_key, p_key, envmnt, d_tkn, c_tkn, a_tkn, s_cell, m_cell

    def get_some_transactions(access_token: str, start_date: str,
                              end_date: str) -> List[dict]:
        MAX_TRANSACTIONS_PER_PAGE = 500
        # Categories from the returned transaction JSON that we are not counting in the budget sum
        OMIT_CATEGORIES = [
            "Credit", "Deposit", "Payment", "Healthcare", "Community",
            "Gyms and Fitness Centers", "Interest", "Cable",
            "Telecommunication Services", "Utilities"
        ]
        # Subtypes from the returned transaction JSON that we are not counting in the budget sum
        OMIT_ACCOUNT_SUBTYPES = ['cd', 'savings', 'checking']

        # Adding all accounts that are not part of the "OMIT_ACCOUNT_SUBTYPES" variable above
        account_ids = []
        for account in plaid_client.Accounts.get(access_token)['accounts']:
            if account['subtype'] not in OMIT_ACCOUNT_SUBTYPES:
                account_ids.append(account['account_id'])


#    account_ids = [account['account_id'] for account in plaid_client.Accounts.get(access_token)['accounts']
#        if account['subtype'] not in OMIT_ACCOUNT_SUBTYPES]

# Fins number of transactions per page so we can iterate over them
        num_available_transactions = plaid_client.Transactions.get(
            access_token, start_date, end_date,
            account_ids=account_ids)['total_transactions']
        num_pages = math.ceil(num_available_transactions /
                              MAX_TRANSACTIONS_PER_PAGE)

        # Start with empty array named transactions, then add a transaction to it whenever the category is none OR when none of the categories are part of the blacklist
        transactions = []
        for page_num in range(num_pages):
            for transaction in plaid_client.Transactions.get(
                    access_token,
                    start_date,
                    end_date,
                    account_ids=account_ids,
                    offset=page_num * MAX_TRANSACTIONS_PER_PAGE,
                    count=MAX_TRANSACTIONS_PER_PAGE)['transactions']:
                if transaction['category'] is None:
                    if 'kinder' in transaction['name']:
                        None
                elif (category in OMIT_CATEGORIES
                      for category in transaction['category']):
                    None
                else:
                    transactions += transaction

        return transactions

    def get_yesterdays_transactions() -> List[dict]:
        today = datetime.date.today()
        # Finds the most recent Sunday and creates an interval between that Sunday and yesterday
        idx = (today.weekday() + 3) % 7
        yesterday = (today - datetime.timedelta(days=1)).strftime('%Y-%m-%d')
        start = (today - datetime.timedelta(idx)).strftime('%Y-%m-%d')

        # Collect all of yesterdays transactions from each credit card
        y_trx = []
        for access_id in [c_tkn, d_tkn, a_tkn]:
            y_trx += get_some_transactions(access_id, yesterday, yesterday)

        # Collect all of this weeks transactions from each credit card
        w_trx = []
        for access_id in [c_tkn, d_tkn, a_tkn]:
            w_trx += get_some_transactions(access_id, start, yesterday)

        return y_trx, w_trx, start, idx

    def sms(session, y_trx, w_trx):
        y_total_spent = round(
            sum(transaction['amount'] for transaction in y_trx), 2)
        w_total_spent = round(
            sum(transaction['amount'] for transaction in w_trx), 2)
        y_body = '${0} spent yesterday.'.format(y_total_spent)
        w_body = '${0} spent this week.'.format(w_total_spent)
        r_body = '${0} available for the next {1} days.'.format(
            round(500 - w_total_spent, 2), (7 - idx))

        sns = session.client('sns')
        contact_list = [s_cell]
        for num in contact_list:
            try:
                sns.publish(PhoneNumber=num,
                            Message=(str(y_body) + '\n' + str(w_body) + '\n' +
                                     str(r_body)))
                print('sns number sent to ' + str(num))
            except Exception as e:
                print(e)

    session = boto3.session.Session()
    cl_id, s_key, p_key, envmnt, d_tkn, c_tkn, a_tkn, s_cell, m_cell = get_creds(
        session)
    plaid_client = PlaidClient(client_id=cl_id,
                               secret=s_key,
                               public_key=p_key,
                               environment=envmnt)
    y_trx, w_trx, start, idx = get_yesterdays_transactions()
    try:
        sms(session, y_trx, w_trx)
        print('yesterdays value: ' + str(y_trx) + ', week value: ' +
              str(w_trx))
    except Exception as e:
        print(e)
Exemple #15
0
from dotenv import load_dotenv
load_dotenv()
import math
import datetime
from plaid import Client as PlaidClient

PLAID_CLIENT_ID = os.getenv('PLAID_CLIENT_ID')
PLAID_SECRET = os.getenv('PLAID_SECRET')
PLAID_PUBLIC_KEY = os.getenv('PLAID_PUBLIC_KEY')
PLAID_ENV = os.getenv('PLAID_ENV')
BOFA_ACCESS_TOKEN = os.getenv('BOFA_ACCESS_TOKEN')
CHASE_ACCESS_TOKEN = os.getenv('CHASE_ACCESS_TOKEN')
#VENMO_ACCESS_TOKEN=os.getenv('VENMO_ACCESS_TOKEN')

plaid_client = PlaidClient(client_id=PLAID_CLIENT_ID,
                           secret=PLAID_SECRET,
                           public_key=PLAID_PUBLIC_KEY,
                           environment=PLAID_ENV)

# https://plaid.com/docs/api/#transactions
MAX_TRANSACTIONS_PER_PAGE = 500
#OMIT_CATEGORIES = ["Transfer", "Credit Card", "Deposit"]
OMIT_CATEGORIES = ["Transfer", "Credit Card", "Deposit", "Payment"]
OMIT_ACCOUNT_SUBTYPES = ['cd', 'savings']


def get_some_transactions(access_token, start_date, end_date):
    account_ids = [
        account['account_id']
        for account in plaid_client.Accounts.get(access_token)['accounts']
        #if account['subtype'] not in ['cd', 'savings']]
        if account['subtype'] not in OMIT_ACCOUNT_SUBTYPES