Пример #1
0
def get_dwolla_client():
    client = dwolla.Client(
        id=settings.DWOLLA_API_KEY,
        secret=settings.DWOLLA_SECRET_KEY,
        environment='sandbox' if settings.USE_FAKE else 'production')

    return client.Auth.client()
Пример #2
0
def create_verified_customer(user):
    """
    Creates Dwolla verified customer
    and plugin to User model
    """
    client = dwollav2.Client(id=settings.DWOLLA_ID_SANDBOX,
                             secret=settings.DWOLLA_SECRET_SANDBOX,
                             environment=settings.PLAID_ENV)
    app_token = client.Auth.client()
    request_body = {
        'firstName': user.first_name,
        'lastName': user.last_name,
        'email': user.email,
        'type': user.type,
        'address1': user.address1,
        'city': user.city,
        'state': user.state,
        'postalCode': user.postal_code,
        'dateOfBirth': str(user.date_of_birth),
        'ssn': user.ssn
    }
    missed_fields = has_missed_fields(request_body)
    if missed_fields:
        return missed_fields
    customer = app_token.post('customers', request_body)
    user.dwolla_verified_url = customer.headers['location']
    user.save()

    return missed_fields
Пример #3
0
 def test_auth(self):
     client = dwollav2.Client(id=self.id, secret=self.secret)
     redirect_uri = "redirect-uri"
     self.assertEqual(
         client.auth(redirect_uri=redirect_uri).url,
         'https://accounts.dwolla.com/auth?client_id=client-id&redirect_uri=%s&response_type=code'
         % redirect_uri)
Пример #4
0
def clean_data(uid, phone):
    auth.delete_user(uid)  #Clear Firebase
    client = boto3.resource(
        'dynamodb',
        region_name='us-east-1',
        aws_access_key_id=keys['aws_access_key_id'],
        aws_secret_access_key=keys['aws_secret_access_key'])
    table = client.Table('DrackerUser')
    #Clear Entry in Dwolla
    item = table.get_item(Key={'phone': phone})
    url = item['Item']['customer_url']
    request_body = {'status': 'deactivated'}
    dwollaclient = dwollav2.Client(key=keys['dwolla_key'],
                                   secret=keys['dwolla_secret'],
                                   environment=keys['dwolla_env'])
    app_token = dwollaclient.Auth.client()
    app_token.post(url, request_body)
    #Clear Entry in DrackerUser
    table.delete_item(Key={'phone': phone})
    #Remove table
    while True:
        try:
            client.Table(uid).delete()
            break
        except client.meta.client.exceptions.ResourceInUseException:
            pass
Пример #5
0
 def __init__(self):
     self.client = dwollav2.Client(
         key=DWOLLA_SETTINGS.get('app_key'),
         secret=DWOLLA_SETTINGS.get('app_secret'),
         environment=DWOLLA_SETTINGS.get('environment'))
     self.url = DWOLLA_SETTINGS.get('url')
     self.token = self.client.Auth.client()
     self.webhook_secret = settings.SECRET_KEY
Пример #6
0
    def test_sets_on_grant(self):
        def on_grant(x):
            return x

        client = dwollav2.Client(id=self.id,
                                 secret=self.secret,
                                 on_grant=on_grant)
        self.assertEqual(on_grant, client.on_grant)
Пример #7
0
 def test_refresh_token_error(self):
     client = dwollav2.Client(id=self.id, secret=self.secret)
     responses.add(responses.POST,
                   client.token_url,
                   body='{"error": "bad"}',
                   status=200,
                   content_type='application/json')
     with self.assertRaises(dwollav2.Error):
         client.refresh_token(refresh_token='refresh-token')
Пример #8
0
 def test_refresh_token_success(self):
     client = dwollav2.Client(id=self.id, secret=self.secret)
     responses.add(responses.POST,
                   client.token_url,
                   body='{"access_token": "abc"}',
                   status=200,
                   content_type='application/json')
     token = client.refresh_token(refresh_token='refresh-token')
     self.assertEqual('abc', token.access_token)
Пример #9
0
 def test_instance_callback_success_with_none_on_grant(self):
     client = dwollav2.Client(id='id', secret='secret')
     auth = client.Auth(redirect_uri=self.redirect_uri,
                        scope=self.scope,
                        state=self.state)
     responses.add(responses.POST,
                   client.token_url,
                   body='{"access_token": "abc"}',
                   status=200,
                   content_type='application/json')
     params = {'state': self.state, 'code': 'def'}
     token = auth.callback(params)
     self.assertEqual('abc', token.access_token)
Пример #10
0
def lambda_handler(event, context):
    try:
        phone = event['phone']
        account_id = event['account_id']
        token = event['token']
        account_name = event["name"]
        institution_name = event["institution_name"]
        item = table.get_item(Key={'phone': phone})
        item = item['Item']
        customer_url = item['customer_url']
        plaid_client = Client(client_id=os.environ.get('plaid_client'),
                              secret=os.environ.get('plaid_secret'),
                              public_key=os.environ.get('plaid_public'),
                              environment=os.environ.get('plaid_env'))
        exchange_token_response = plaid_client.Item.public_token.exchange(
            token)
        access_token = exchange_token_response['access_token']
        dwolla_response = plaid_client.Processor.dwollaBankAccountTokenCreate(
            access_token, account_id)
        bank_account_token = dwolla_response['processor_token']
        request_body = {'plaidToken': bank_account_token, 'name': account_name}
        dwolla_client = dwollav2.Client(
            key=os.environ.get('dwolla_key'),
            secret=os.environ.get('dwolla_secret'),
            environment=os.environ.get('dwolla_env'))
        app_token = dwolla_client.Auth.client()
        funding_source = app_token.post('%s/funding-sources' % customer_url,
                                        request_body)
        source_url = funding_source.headers['location']
        new_account = {
            "url": source_url,
            "name": account_name,
            "institution": institution_name
        }
        if item.has_key('funding_source'):
            data = json.loads(item['funding_source'])
            data["list"].append(new_account)
            item['funding_source'] = json.dumps(data)
        else:
            data = {"default": new_account, "list": [new_account]}
            item['funding_source'] = json.dumps(data)
        table.put_item(Item=item)
        return {"message": "SUCCESS", "url": source_url}
    except Exception as exp:
        try:
            err = exp.body
            return {"message": "ERROR", "code": err["code"]}
        except:
            return {"message": "ERROR"}
Пример #11
0
def getDwollaCustomer(account_url):
    app_key = 'PNQRGggoMwGefS97PGFBt44KO6cGM21pUwiSql9oxptYCIatMs'
    app_secret = 'NToE2JWlzY0z8m6t0QYNxZ9hZgkBleSrQVntYWJd6z0gUvpYdp'
    client = dwollav2.Client(key=app_key,
                             secret=app_secret,
                             environment='sandbox')
    app_token = client.Auth.client()
    full_account_url = 'https://api-sandbox.dwolla.com/accounts/' + str(
        account_url)
    print('FULL ACCOUNT URL: ' + str(full_account_url))

    account = app_token.get(full_account_url)
    account.body['name']
    print('ACCOUNT: ' + str(account.body))
    return account.body
Пример #12
0
def dwolla_payment(request):
    data = {}

    if request.method == "POST":
        client = dwollav2.Client(key=settings.DWOLLA_KEY,
                                 secret=settings.DWOLLA_SECRET,
                                 environment=settings.DWOLLA_ENV
                                 )  # optional - defaults to production

        app_token = client.Auth.client()

        href = dwolla_get_account_href(app_token)
        funding_resource = dwolla_get_funding_sources(app_token, href)

        data["href"] = href
        data["funding_resource"] = funding_resource

    return render(request, "dwollaTest.html", {'data': data})
Пример #13
0
def lambda_handler(event, context):
  new_email = event['new_email']
  old_email = event['old_email']
  try:
      user = auth.get_user_by_email(old_email)
      phone = user.phone_number
      uid = user.uid
      auth.update_user(
          uid,
          email=new_email,
          email_verified=False)
      phone = phone[2:]
      item = table.get_item(
            Key={
            'phone': phone
            }
        )
      item = item['Item']
      client = dwollav2.Client(
        key = os.environ.get('dwolla_key'),
        secret = os.environ.get('dwolla_secret'),
        environment = os.environ.get('dwolla_env')
      )
      app_token = client.Auth.client()
      request_body = {
        'email': new_email
      }
      app_token.post(item['customer_url'], request_body)

      item['email'] = new_email
      table.put_item(Item=item)
      name = user.display_name
      send_verification_email(name, old_email, new_email, uid)
      return {"message" : "SUCCESS"}
  except Exception as new_user_exception:
      print(new_user_exception)
      try:
        error = new_user_exception.detail.response.content
        response = json.loads(error)
        error_code = response["error"]["message"]
        return {"message" : error_code}
      except Exception as err:
        print(err)
        return {"message" : "ERROR"}
Пример #14
0
def attach_funding(user):
    res = api_instance.get_user(user['phone'])
    data = res.json()
    customer_url = data['customer_url']
    checking = random_checking()
    client = dwollav2.Client(key=keys['dwolla_key'],
                             secret=keys['dwolla_secret'],
                             environment=keys['dwolla_env'])
    app_token = client.Auth.client()
    client = boto3.resource(
        'dynamodb',
        region_name='us-east-1',
        aws_access_key_id=keys['aws_access_key_id'],
        aws_secret_access_key=keys['aws_secret_access_key'])
    table = client.Table('DrackerUser')
    item = table.get_item(Key={'phone': user['phone']})
    item = item['Item']
    funding_source = app_token.post('%s/funding-sources' % customer_url,
                                    checking)
    source_url = funding_source.headers['location']
    app_token.post('%s/micro-deposits' % source_url)
    #verify with micro deposits
    currency = random_currency()
    request_body = {
        "amount1": {
            "value": random_deposit(),
            "currency": currency
        },
        "amount2": {
            "value": random_deposit(),
            "currency": currency
        }
    }
    app_token.post('%s/micro-deposits' % source_url, request_body)
    new_account = {
        "url": source_url,
        "name": random_string(5),
        "institution": random_string(5)
    }
    data = {"default": new_account, "list": [new_account]}
    item['funding_source'] = json.dumps(data)
    table.put_item(Item=item)
    return source_url
Пример #15
0
 def __init__(self):
     self.keys = json.loads((open("keys.json", "r")).read())
     cred = credentials.Certificate(
         "./dracker-9443c-firebase-adminsdk-gmc2g-7d48bbd323.json")
     firebase_admin.initialize_app(cred)
     self.dynamodb = boto3.resource(
         'dynamodb',
         region_name='us-east-1',
         aws_access_key_id=self.keys['aws_access_key_id'],
         aws_secret_access_key=self.keys['aws_secret_access_key'])
     self.s3 = boto3.resource(
         's3',
         region_name='us-east-1',
         aws_access_key_id=self.keys['aws_access_key_id'],
         aws_secret_access_key=self.keys['aws_secret_access_key'])
     dwollaclient = dwollav2.Client(key=self.keys['dwolla_key'],
                                    secret=self.keys['dwolla_secret'],
                                    environment=self.keys['dwolla_env'])
     self.dwolla = dwollaclient.Auth.client()
Пример #16
0
def run(json_input, context):
    print(json_input)
    message_data = [
        record["Sns"]["MessageAttributes"] for record in json_input["Records"]
    ]

    for message in message_data:
        payer_id = message["PayerIdentifier"]["Value"]
        funding_source = message["PayerFundingSource"]["Value"]
        performer_id = message["PerformerIdentifier"]["Value"]
        payment_amount = int(message["PaymentAmount"]["Value"])

        # TODO: Record this somewhere.
        print("%s pays %s $%.2f" %
              (payer_id, performer_id, payment_amount / 100))

        client = dwollav2.Client(key=os.environ['DWOLLA_APP_KEY'],
                                 secret=os.environ['DWOLLA_APP_SECRET'],
                                 environment='sandbox')

        app_token = client.Auth.client()

        # Send Transaction
        request_body = {
            '_links': {
                'source': {
                    'href': funding_source
                },
                'destination': {
                    'href':
                    __dwolla_url('accounts',
                                 os.environ['DWOLLA_PAYMENT_DESTINATION'])
                }
            },
            'amount': {
                'currency': 'USD',
                'value': "%.2f" % payment_amount / 100
            },
            'metadata': {}
        }

        transfer = app_token.post('transfers', request_body)
        return transfer.headers['location']
Пример #17
0
def send_money(amount):

    with open("secrets.txt") as file:
        secrets = file.read().split(",")

    # Navigate to https://dashboard.dwolla.com/applications (production) or https://dashboard-sandbox.dwolla.com/applications (Sandbox) for your application key and secret.
    app_key = secrets[0]
    app_secret = secrets[1]
    client = dw.Client(key=app_key, secret=app_secret, environment='sandbox')

    app_token = client.Auth.client()

    # Make sure amount is valid
    if type(amount) != str or len(amount) != 4:
        print("Invalid amount")
        return

    request_body = {
        '_links': {
            "self": {
                "href": "https://api-sandbox.dwolla.com/sandbox-simulations",
                "type": "application/vnd.dwolla.v1.hal+json",
                "resource-type": "sandbox-simulation"
            },
            'source': {
                'href':
                f'https://api-sandbox.dwolla.com/funding-sources/{secrets[2]}'
            },
            'destination': {
                'href':
                f'https://api-sandbox.dwolla.com/funding-sources/{secrets[3]}'
            }
        },
        'amount': {
            'currency': 'USD',
            'value': amount
        }
    }

    transfer = app_token.post('transfers', request_body)
    return transfer.headers
Пример #18
0
def initiate_transfer(payer_phone, payee_phone, amount):
    transaction_payload = {}
    try:
        payer_resource = user_table.get_item(Key={'phone': payer_phone})
        payer_item = payer_resource['Item']
        payer_sources = json.loads(payer_item['funding_source'])
        dest = payer_sources['default']['url']
        payee_resource = user_table.get_item(Key={'phone': payee_phone})
        payee_item = payee_resource['Item']
        payee_sources = json.loads(payee_item['funding_source'])
        source = payee_sources['default']['url']
        client = dwollav2.Client(key=os.environ.get('dwolla_key'),
                                 secret=os.environ.get('dwolla_secret'),
                                 environment=os.environ.get('dwolla_env'))
        app_token = client.Auth.client()
        request_body = {
            '_links': {
                'source': {
                    'href': source
                },
                'destination': {
                    'href': dest
                }
            },
            'amount': {
                'currency': 'USD',
                'value': amount
            }
        }
        transfer = app_token.post('transfers', request_body)
        res = transfer.headers['location'].split('/')
        transaction_payload['transaction_id'] = res[-1]
        transaction_payload['amount'] = amount
        transaction_payload['email'] = payee_item['email']
        transaction_payload['phone'] = payee_item['phone']
        transaction_payload['bank_account'] = payee_sources['default'][
            'institution'] + ' - ' + payee_sources['default']['name']
        return {"message": "SUCCESS", "payload": transaction_payload}
    except Exception as err:
        print(err)
        return {"message": "ERROR"}
Пример #19
0
    def __init__(self):
        env = settings.DWOLLA_ENV
        if env not in ['production', 'development', 'sandbox']:
            raise ValueError('Incorrect value for DWOLLA_ENV in settings.')

        dwolla_id = None
        dwolla_secret = None

        if env == 'sandbox':
            dwolla_id = settings.DWOLLA_ID_SANDBOX
            dwolla_secret = settings.DWOLLA_SECRET_SANDBOX
        elif env == 'production':
            dwolla_id = settings.DWOLLA_ID_PROD
            dwolla_secret = settings.DWOLLA_SECRET_PROD
        else:
            raise ValueError('Incorrect value for DWOLLA_ENV in settings.')

        self.client = dwollav2.Client(
            id=dwolla_id,
            secret=dwolla_secret,
            environment=env
        )
        self.app_token = self.client.Auth.client()
Пример #20
0
def test_deep2():
    #Create first user
    user1 = create_data()
    res = api_instance.new_user(user1)
    data = res.json()
    user1['uid'] = data['uid']
    #Create second user
    user2 = create_data()
    res = api_instance.new_user(user2)
    data = res.json()
    user2['uid'] = data['uid']
    #Wait for DynamoDB resources to be created
    time.sleep(5)
    transaction, res = api_instance.create_transaction(user1, user2)
    transaction_id = sanatize(res.text)
    #Attach a bank account
    source1 = attach_funding(user1)
    source2 = attach_funding(user2)
    res = api_instance.settle_transaction(user1['uid'], user2['uid'],
                                          transaction_id)
    response_status = sanatize(res.text)
    if response_status == "200":
        print("Settle Transaction: Test Passed!")
    else:
        print("Settle Transaction: Test Failed!")

    #Cleanup dwolla
    client = dwollav2.Client(key=keys['dwolla_key'],
                             secret=keys['dwolla_secret'],
                             environment=keys['dwolla_env'])
    app_token = client.Auth.client()
    request_body = {'removed': True}
    app_token.post(source1, request_body)
    app_token.post(source2, request_body)
    #CleanUp
    clean_data(user1['uid'], user1['phone'])
    clean_data(user2['uid'], user2['phone'])
Пример #21
0
    def __init__(self):
        self.rs = settings.REDIS_DB

        self.mode = settings.DWOLLA_API_MODE
        if self.mode not in ['PROD', 'DEV']:
            raise ValueError('Dwolla API mode should be "PROD" or "DEV"')

        environment = 'sandbox' if self.mode == 'DEV' else 'production'

        self.client_id = getattr(settings, 'DWOLLA_ID_{}'.format(self.mode))
        self.client_secret = getattr(settings,
                                     'DWOLLA_SECRET_{}'.format(self.mode))

        # Recepient Donkies LLC bank account's email.
        self.donkies_email = getattr(
            settings, 'DONKIES_DWOLLA_EMAIL_{}'.format(self.mode))

        self.client = dwollav2.Client(id=settings.DWOLLA_ID_SANDBOX,
                                      secret=settings.DWOLLA_SECRET_SANDBOX,
                                      environment='sandbox')
        # self.client_id,
        # self.client_secret,
        # environment
        self.token = self.client.Auth.client()
Пример #22
0
def lambda_handler(event, context):
    try:
        phone = event['phone']
        url = event['url']
        client = dwollav2.Client(key=os.environ.get('dwolla_key'),
                                 secret=os.environ.get('dwolla_secret'),
                                 environment=os.environ.get('dwolla_env'))
        app_token = client.Auth.client()
        request_body = {'removed': True}
        app_token.post(url, request_body)
        item = table.get_item(Key={'phone': phone})
        table_row = item['Item']
        data = json.loads(table_row['funding_source'])
        sources = []
        for item in data["list"]:
            if item["url"] != url:
                sources.append(item)
        data["list"] = sources
        table_row['funding_source'] = json.dumps(data)
        table.put_item(Item=table_row)
        return {"message": "SUCCESS"}
    except Exception as err:
        print(err)
        return {"message": "ERROR"}
Пример #23
0
def create_dwolla_entry(first, last, email, street, city, state, zipcode, ssn,
                        birthdate):
    client = dwollav2.Client(key=os.environ.get('dwolla_key'),
                             secret=os.environ.get('dwolla_secret'),
                             environment=os.environ.get('dwolla_env'))
    app_token = client.Auth.client()
    request_body = {
        'firstName': first,
        'lastName': last,
        'email': email,
        'type': 'personal',
        'address1': street,
        'city': city,
        'state': state,
        'postalCode': zipcode,
        'dateOfBirth': birthdate,
        'ssn': ssn
    }
    try:
        customer = app_token.post('customers', request_body)
        customer_url = customer.headers['location']
        return {"message": "SUCCESS", "customer_url": customer_url}
    except Exception as exp:
        return {"message": 'ERROR'}
Пример #24
0
import dwollav2
import os
import json
import urllib.request
from dotenv import load_dotenv

load_dotenv()

client = dwollav2.Client(
    key=os.environ['DWOLLA_APP_KEY'],
    secret=os.environ['DWOLLA_APP_SECRET'],
    environment='sandbox',  # defaults to 'production'
)
app_token = client.Auth.client()

# https://docs.dwolla.com/#create-a-funding-source-for-an-account
# creating funding source for JAMIIE

# https://docs.dwolla.com/#idempotency-key
# To prevent multiple post req
headers = {'Idempotency-Key': '19051a62-3403-11e6-ac61-9e71128cae77'}


def owner_acc_details():
    r = app_token.get('/')
    indented_json = json.dumps(r.body,
                               indent=4,
                               separators=(',', ': '),
                               sort_keys=True)
    print(indented_json)
    print(r.body['_links']['account']['href'])
 def __init__(self):
     self.client = dwollav2.Client(key=app_key,
                                   secret=app_secret,
                                   environment='sandbox')
     self.app_token = self.client.Auth.client()
Пример #26
0
 def test_sets_id_and_key_when_id_provided(self):
     client = dwollav2.Client(id=self.id, secret=self.secret)
     self.assertEqual(self.id, client.id)
     self.assertEqual(self.id, client.key)
Пример #27
0
 def test_api_url(self):
     client = dwollav2.Client(id=self.id, secret=self.secret)
     self.assertEqual(client.ENVIRONMENTS[client.environment]['api_url'],
                      client.api_url)
Пример #28
0
 def test_sets_on_grant(self):
     on_grant = lambda x: x
     client = dwollav2.Client(id=self.id,
                              secret=self.secret,
                              on_grant=on_grant)
     self.assertEqual(on_grant, client.on_grant)
Пример #29
0
 def test_raises_if_invalid_environment(self):
     with self.assertRaises(ValueError):
         dwollav2.Client(id=self.id,
                         secret=self.secret,
                         environment='invalid')
Пример #30
0
 def test_sets_environment(self):
     client = dwollav2.Client(id=self.id,
                              secret=self.secret,
                              environment='sandbox')
     self.assertEqual('sandbox', client.environment)