Exemplo n.º 1
0
 def __ccsett(self): 
     uri = self.request.get('balancedCreditCardURI')        
     last4 = self.request.get('last4')   
     next = self.request.get('next_url')
     first_name = self.request.get('first_name')
     last_name = self.request.get('last_name')
     email = self.request.get('email')
     tel = self.request.get('tel')
     
     balanced.configure(baccount)        
     customer = create_cust(self.user_prefs)
     customer.add_card(uri)        
     self.user_prefs.cc = last4 
     self.user_prefs.first_name = first_name
     self.user_prefs.last_name = last_name
     if email:
         self.user_prefs.email = email
     if tel:
         self.user_prefs.tel = tel
     self.user_prefs.put()
     logging.info('Credit card recorded')
     taskqueue.add(url='/summary/selfpay/'+self.user_prefs.key.urlsafe(), method='get')
     # Update status of requests
     taskqueue.add(url='/request/updatecc/'+self.user_prefs.key.urlsafe(), method='get')
     self.redirect(next)
     return             
Exemplo n.º 2
0
    def prepare_customer(self, customer, payment_uri=None):
        api_key = customer.company.processor_key
        balanced.configure(api_key)

        self.logger.debug('Preparing customer %s with payment_uri=%s', 
                          customer.guid, payment_uri)
        # when payment_uri is None, it means we are going to use the 
        # default funding instrument, just return
        if payment_uri is None:
            return
        # get balanced customer record
        external_id = customer.external_id
        balanced_customer = self.customer_cls.find(external_id)
        # TODO: use a better way to determine type of URI?
        if '/bank_accounts/' in payment_uri:
            self.logger.debug('Adding bank account %s to %s', 
                              payment_uri, customer.guid)
            balanced_customer.add_bank_account(payment_uri)
            self.logger.info('Added bank account %s to %s', 
                             payment_uri, customer.guid)
        elif '/cards/' in payment_uri:
            self.logger.debug('Adding credit card %s to %s', 
                              payment_uri, customer.guid)
            balanced_customer.add_card(payment_uri)
            self.logger.info('Added credit card %s to %s', 
                             payment_uri, customer.guid)
        else:
            raise ValueError('Invalid payment_uri {}'.format(payment_uri))
Exemplo n.º 3
0
    def prepare_customer(self, customer, payment_uri=None):
        api_key = customer.company.processor_key
        balanced.configure(api_key)

        self.logger.debug('Preparing customer %s with payment_uri=%s',
                          customer.guid, payment_uri)
        # when payment_uri is None, it means we are going to use the
        # default funding instrument, just return
        if payment_uri is None:
            return
        # get balanced customer record
        external_id = customer.external_id
        balanced_customer = self.customer_cls.find(external_id)
        # TODO: use a better way to determine type of URI?
        if '/bank_accounts/' in payment_uri:
            self.logger.debug('Adding bank account %s to %s', payment_uri,
                              customer.guid)
            balanced_customer.add_bank_account(payment_uri)
            self.logger.info('Added bank account %s to %s', payment_uri,
                             customer.guid)
        elif '/cards/' in payment_uri:
            self.logger.debug('Adding credit card %s to %s', payment_uri,
                              customer.guid)
            balanced_customer.add_card(payment_uri)
            self.logger.info('Added credit card %s to %s', payment_uri,
                             customer.guid)
        else:
            raise ValueError('Invalid payment_uri {}'.format(payment_uri))
Exemplo n.º 4
0
def addBalancedBankAccount(request):
	bu = request.user.basicuser
	name = request.POST['name']
	uri = request.POST["uri"];
	fingerprint = request.POST["fingerprint"];
	bank_name = request.POST["bank_name"];
	bank_code = request.POST["bank_code"];
	account_number = request.POST["account_number"];
	if not doesBankAccountExist(bu,fingerprint):
		bankaccount = BalancedBankAccount(user=bu,name=name,uri=uri,fingerprint=fingerprint,bank_name=bank_name,bank_code=bank_code,account_number=account_number)
		bankaccount.save()
		# See if user has a balanced account
		balanced.configure(settings.BALANCED_API_KEY)
		if bu.balanceduri:
			customer = balanced.Customer.find(bu.balanceduri)
		# If not, create a Balanced Customer and update BU Profile
		else:
			customer = balanced.Customer(name=bu.name(),email=bu.email,phone=bu.phonenumber).save()
			bu.balanceduri = customer.uri
			bu.save()
		# Add bank account to the customer
		try:
			customer.add_bank_account(bankaccount.uri)
			bank_account = balanced.BankAccount.find(bankaccount.uri)
			#if not bu.payment_method:
				#bu.payment_method = bankaccount
			if not bu.payout_method:
				bu.payout_method = bankaccount
				email_view.composeEmailPayoutUpdated(bu)
			bu.save()
			return {'status':201,'bank':bankaccount,'error':'None','balanceduri':bu.balanceduri}
		except Exception,e:
			return {'status':500,'bank':bankaccount,'error':e}
Exemplo n.º 5
0
    def refund(self, transaction):
        api_key = transaction.subscription.plan.company.processor_key
        balanced.configure(api_key)

        # make sure we won't duplicate refund
        try:
            refund = self.refund_cls.query.filter(**{"meta.billy.transaction_guid": transaction.guid}).one()
        except balanced.exc.NoResultFound:
            refund = None
        if refund is not None:
            self.logger.warn("Balanced transaction refund for %s already " "exist", transaction.guid)
            return refund.uri

        charge_transaction = transaction.refund_to
        debit = self.debit_cls.find(charge_transaction.external_id)
        refund = debit.refund(
            amount=self._to_cent(transaction.amount),
            description=(
                "Generated by Billy from subscription {}, scheduled_at={}".format(
                    transaction.subscription.guid, transaction.scheduled_at
                )
            ),
            meta={"billy.transaction_guid": transaction.guid},
        )
        self.logger.info("Processed refund transaction %s, amount=%s", transaction.guid, transaction.amount)
        return refund.uri
Exemplo n.º 6
0
    def refund(self, transaction):
        api_key = transaction.subscription.plan.company.processor_key
        balanced.configure(api_key)

        # make sure we won't duplicate refund
        try:
            refund = (self.refund_cls.query.filter(
                **{
                    'meta.billy.transaction_guid': transaction.guid
                }).one())
        except balanced.exc.NoResultFound:
            refund = None
        if refund is not None:
            self.logger.warn(
                'Balanced transaction refund for %s already '
                'exist', transaction.guid)
            return refund.uri

        charge_transaction = transaction.refund_to
        debit = self.debit_cls.find(charge_transaction.external_id)
        refund = debit.refund(
            amount=self._to_cent(transaction.amount),
            description=(
                'Generated by Billy from subscription {}, scheduled_at={}'.
                format(transaction.subscription.guid,
                       transaction.scheduled_at)),
            meta={'billy.transaction_guid': transaction.guid},
        )
        self.logger.info('Processed refund transaction %s, amount=%s',
                         transaction.guid, transaction.amount)
        return refund.uri
Exemplo n.º 7
0
def addBalancedCard(request):
	uri = request.POST.get('uri','')
	brand = request.POST.get('brand','')
	cardhash = request.POST.get('hash','')
	expiration_month = request.POST.get('expiration_month','')
	expiration_year = request.POST.get('expiration_year','')
	last_four = request.POST.get('last_four','')
	try:
		print 'Adding balanced card'
		# Configure Balanced API
		balanced.configure(settings.BALANCED_API_KEY)
		# Either find or get the Balanced Customer
		bu = BasicUser.objects.get(user=request.user)
		# See if user has a balanced account
		if bu.balanceduri:
			customer = balanced.Customer.find(bu.balanceduri)
		# If not, create a Balanced Customer and update BU Profile
		else:
			customer = balanced.Customer(name=bu.name(),email=bu.email,phone=bu.phonenumber).save()
			bu.balanceduri = customer.uri
			bu.save()
		# If card not already saved, add the card to the customer and add the card to the database
		if not doesCardExist(bu,cardhash):
			customer.add_card(uri)
			new_card = BalancedCard(user=bu,uri=uri,brand=brand,cardhash=cardhash,expiration_month=expiration_month,expiration_year=expiration_year,last_four=last_four)
			new_card.save()
			if not bu.payment_method:
				bu.payment_method = new_card
				bu.save()
			return {'status':201,'card':new_card,'error':'None','balanceduri':bu.balanceduri} # Success
		return {'status':500,'error':'Card Already Saved'} # Card Already Saved
	except Exception,e:
		print 'Error Adding Card'
		print e
		return {'status':500,'error':e} # Failure
Exemplo n.º 8
0
    def test_invalid_funding_instrument(self):
        balanced.configure(self.processor_key)
        # create a card
        card = balanced.Card(
            name='BILLY_INTERGRATION_TESTER',
            number='5105105105105100',
            expiration_month='12',
            expiration_year='2020',
            security_code='123',
        ).save()
        card_uri = card.href + 'NOTEXIST'

        # create a company
        company = self.create_company()
        api_key = str(company['api_key'])

        # create a customer
        res = self.testapp.post('/v1/customers',
                                headers=[self.make_auth(api_key)],
                                status=200)
        customer = res.json
        self.assertEqual(customer['company_guid'], company['guid'])

        # create an invoice
        res = self.testapp.post('/v1/invoices',
                                dict(
                                    customer_guid=customer['guid'],
                                    amount=5566,
                                    funding_instrument_uri=card_uri,
                                ),
                                headers=[self.make_auth(api_key)],
                                status=400)
        self.assertEqual(res.json['error_class'], 'InvalidFundingInstrument')
Exemplo n.º 9
0
def payment_edit(request, id):
    context = {}
    payment = get_object_or_404(models.Payment, id=id)
    if request.method == 'POST':
        form = forms.PaymentEditForm(request.POST, instance=payment)
        form.fields['name'].required = False
        form.fields['message'].required = False
        refund_amount_before = payment.refund_amount
        if form.is_valid():
            refund_amount = form.cleaned_data['refund_amount']
            form.save()
            refund_amount_after = payment.refund_amount
            if refund_amount and refund_amount_after != refund_amount_before:
                balanced.configure(settings.BALANCED_API_KEY)
                debit = balanced.Debit.find(payment.balanced_uri)
                description = form.cleaned_data.get('description')
                if not description:
                    description = 'Refund for %s' % payment.item.identifier
                refund_cents = int(Decimal('100') * refund_amount_after)
                print debit.refund(
                    amount=refund_cents,
                    description=description,
                    meta={
                        'payment.id': str(payment.pk),
                        'item.identifier': payment.item.identifier,
                    }
                )
                #raise Exception(refund_amount_after)
            return redirect('manage:payments')
    else:
        form = forms.PaymentEditForm(instance=payment)
    form.fields['message'].widget.attrs['rows'] = 3
    context['form'] = form
    context['payment'] = payment
    return render(request, 'manage/payment_edit.html', context)
Exemplo n.º 10
0
    def debit_payments(self):
        balanced.configure(BALANCED['API_KEY'])

        payment_transactions_to_debit_list = PaymentTransaction.objects.filter(
            status=PAYMENT_TRANSACTION_STATUSES_CHOICES.pending)
        for payment_transaction in payment_transactions_to_debit_list:
            print 'running debit for transaction #'+str(payment_transaction.id)

            pledger_balanced_account = BalancedAccount.objects.get(pk=payment_transaction.balanced_account_id)
            balanced_account = balanced.Account.find(pledger_balanced_account.uri)

            with transaction.commit_on_success():
                total_amount_cents = int(Decimal(payment_transaction.total_amount*Decimal(100)).quantize((Decimal('1'))))
                balanced_debit = balanced_account.debit(appears_on_statement_as=payment_transaction.statement_text,
                                                        amount=total_amount_cents,
                                                        description=payment_transaction.description,
                                                        )

                if balanced_debit.status == 'succeeded':
                    payment_transaction.status = PAYMENT_TRANSACTION_STATUSES_CHOICES.paid
                    payment_transaction.datetime_debited = now()
                else:
                    payment_transaction.status = PAYMENT_TRANSACTION_STATUSES_CHOICES.rejected
                payment_transaction.balanced_status = balanced_debit.status
                try:
                    payment_transaction.balanced_transaction_number = balanced_debit.transaction_number
                    payment_transaction.source_uri = balanced_debit.source.uri
                    payment_transaction.uri = balanced_debit.uri
                except AttributeError:
                    pass
                payment_transaction.save()

                self.update_donation_transaction(payment_transaction)
                if payment_transaction.status == PAYMENT_TRANSACTION_STATUSES_CHOICES.paid:
                    self.update_project_balances(payment_transaction)
Exemplo n.º 11
0
    def handle(self, *args, **options):

        self.stdout.write('Payments for day: %r\n\n' %  strftime("%Y-%m-%d %H:%M:%S", gmtime()))
        
        #helper = BalancedPaymentsHelper()
        balanced.configure(settings.BALANCED_API_KEY)
        
        venues = Venue.objects.all()

        for venue in venues:
            venue_total = 0
            orders = BarOrder.objects.filter(venue=venue, current_status=4, payment_processed=True, venue_payment_processed=False)
            for order in orders:
                amount = int(round(float(order.grand_total), 2)*100) - 5
                venue_total += amount

                order.venue_payment_processed=True
                order.save()

            if venue_total > 0:
                merchant_account = balanced.Account.find(venue.bp_merchant)
                merchant_account.credit(amount=venue_total)
                
                #helper.payVenueMerchantAccount(venue=venue, amount=venue_total)

                self.stdout.write('Successfully paid %r a total of %r on %r\n' % (venue.name, venue_total, strftime("%Y-%m-%d %H:%M:%S", gmtime())))
            
        self.stdout.write('\n-----------------------------------\n\n')
Exemplo n.º 12
0
def payment(request):
    # TODO: get the form record from database and determine which account
    # for processing the payment, and what kind of limitation we have here
    _ = get_localizer(request)
    factory = FormFactory(_)
    PaymentForm = factory.make_payment_form()
    form = PaymentForm()

    if request.method == 'POST':
        check_csrf_token(request)

        # TODO: tokenlize the card
        payment_uri = request.params['payment_uri']
        print '#'*10, payment_uri

        balanced.configure('ef13dce2093b11e388de026ba7d31e6f')
        customer = balanced.Customer()
        customer.save()
        customer.add_card(payment_uri)
        customer.debit(
            amount=12345,
            source_uri=payment_uri,
            description='Payment made via EZ2Pay for XXX',
        )
        return dict(form=form, processed=True)
        # TODO: call the balanced API, charge the card

    return dict(form=form, processed=False)
Exemplo n.º 13
0
def checkoutPurchase(request,checkoutid):
	bu = request.user.basicuser
	
	# 1. Checkout Validation
	checkout = Checkout.objects.get(id=checkoutid)
	checkoutValid = checkoutValidCheck(checkout,request)
	if checkoutValid['status'] != 201:
		return HttpResponseRedirect('/checkout/verify/'+checkoutValid['error'])
	
	# 2. Make sure all the items are still available
	notavailable = allItemsAvailable(checkout)
	if notavailable:
		return render_to_response('checkout/checkout_review.html',{'checkout':checkout,'error':notavailable},context_instance=RequestContext(request))
	
	# 3. Make purchase
	try:
		if not hasattr(checkout.payment,'checkpayment'): # Only charge if its a bank account or cc
			if hasattr(checkout.payment,'balancedcard'):
				uri = checkout.payment.balancedcard.uri
			elif hasattr(checkout.payment,'balancedbankaccount'):
				uri = checkout.payment.balancedbankaccount.uri
			balanced.configure(settings.BALANCED_API_KEY) # Configure Balanced API
			customer = balanced.Customer.find(bu.balanceduri)
			amount = checkout.total()
			cd = customer.debit(appears_on_statement_as="Vet Cove",amount=amount,source_uri=uri)
			if not cd.status == "succeeded":
				raise Exception("Failed to Complete Transaction")
	except Exception,e:
		return render_to_response('checkout/checkout_review.html',{'checkout':checkout,'error':e},context_instance=RequestContext(request))
Exemplo n.º 14
0
    def test_invalid_funding_instrument(self):
        balanced.configure(self.processor_key)
        marketplace = balanced.Marketplace.find(self.marketplace_uri)
        # create a card
        card = marketplace.create_card(
            name="BILLY_INTERGRATION_TESTER",
            card_number="5105105105105100",
            expiration_month="12",
            expiration_year="2020",
            security_code="123",
        )
        card_uri = card.uri
        card.is_valid = False
        card.save()

        # create a company
        res = self.testapp.post("/v1/companies", dict(processor_key=self.processor_key), status=200)
        company = res.json
        api_key = str(company["api_key"])

        # create a customer
        res = self.testapp.post("/v1/customers", headers=[self.make_auth(api_key)], status=200)
        customer = res.json
        self.assertEqual(customer["company_guid"], company["guid"])

        # create an invoice
        res = self.testapp.post(
            "/v1/invoices",
            dict(customer_guid=customer["guid"], amount=5566, funding_instrument_uri=card_uri),
            headers=[self.make_auth(api_key)],
            status=400,
        )
        self.assertEqual(res.json["error_class"], "InvalidFundingInstrument")
Exemplo n.º 15
0
    def __confirm_hold(self,key):
        try:
            res = ndb.Key(urlsafe=key).get()
        except:
            self.abort(400)

        p = HoldAccount.by_reskey(res.key)

        balanced.configure(baccount)
        cust_id = p.userkey.get().cust_id
        customer = balanced.Customer.find('/v1/customers/' + cust_id)
        customer.add_card(p.uri)

        charge = res.rates*100
        if charge >0:
            customer.debit(amount=charge)

        hold = balanced.Hold.find(p.uri)
        hold.void()
        p.key.delete()

        res.confirmed=True
        res.put()
        d = Driver.by_userkey(res.driver)
        self.params = d.params_fill()
        self.params['reskey'] = key
        self.params.update(res.to_dict())

        self.params['disp_driver'] = True
        self.send_receipt(customer.email, res, self.params)
        # notify the driver?
        self.redirect('/reserve/'+key)
Exemplo n.º 16
0
def newbank_chargecommission(request,itemid):
	item = Item.objects.get(id=itemid)
	if item.commission_paid == True:
		return HttpResponse(json.dumps({'status':201}), content_type='application/json')
	if request.user.basicuser == item.user and request.method == 'POST':
		balanced_addBankAccount = payment_view.addBalancedBankAccount(request)
		if balanced_addBankAccount['status'] != 201:
			return HttpResponse(json.dumps({'status':balanced_addBankAccount['status'],'error':balanced_addBankAccount['error']}), content_type='application/json')	
		try:
			bank = balanced_addBankAccount['bank']
			bu = request.user.basicuser
			bank_uri = bank.uri
			balanced.configure(settings.BALANCED_API_KEY) # Configure Balanced API
			customer = balanced.Customer.find(balanced_addBankAccount['balanceduri'])
			amount = commission.commission(item)
			debit = customer.debit(appears_on_statement_as="Vet Cove Fee",amount=amount,source_uri=bank_uri)
			if not debit.status == "succeeded":
				return HttpResponse(json.dumps({'status':501,'error':'Failed to charge your bank account.'}), content_type='application/json')
			item.commission_paid = True
			item.save()
			commission_obj = Commission(item=item,price=item.price,amount=amount,payment=bank,transcation_number=debit.transaction_number)
			commission_obj.save()
			email_view.composeEmailCommissionCharged(request,bu,commission_obj)
			return HttpResponse(json.dumps({'status':201}), content_type='application/json')
		except Exception,e:	
			print e
			return HttpResponse(json.dumps({'status':501,'error':'Failed to charge your bank account.'}), content_type='application/json')
Exemplo n.º 17
0
def gatePayment(request,paymentid,itemid):
	item = Item.objects.get(id=itemid)
	if item.commission_paid == True:
		return HttpResponseRedirect('/account/messages/'+str(item.id))
	if request.user.basicuser == item.user and request.method == 'POST':
		try:
			payment = Payment.objects.get(id=paymentid)
			if payment.user == request.user.basicuser:
				bu = request.user.basicuser
				balanced.configure(settings.BALANCED_API_KEY) # Configure Balanced API
				customer = balanced.Customer.find(bu.balanceduri)
				amount = commission.commission(item)
				uri = payment.balancedcard.uri if hasattr(payment,'balancedcard') else payment.balancedbankaccount.uri
				debit = customer.debit(appears_on_statement_as="Vet Cove Fee",amount=amount,source_uri=uri)
				if not debit.status == "succeeded":
					return HttpResponseRedirect('/account/messages/'+str(item.id)+"?e=fail")
				item.commission_paid = True
				item.save()
				commission_obj = Commission(item=item,price=item.price,amount=amount,payment=payment,transaction_number=debit.transaction_number)
				commission_obj.save()
				email_view.composeEmailCommissionCharged(bu,commission_obj)
				return HttpResponseRedirect('/account/messages/'+str(item.id))
		except Exception,e:
			print e
			return HttpResponseRedirect('/account/messages/'+str(item.id)+"?e=fail")
Exemplo n.º 18
0
def newcard_chargecommission(request,itemid):
	item = Item.objects.get(id=itemid)
	# If commission already paid, skip to messages
	if item.commission_paid == True:
		return HttpResponse(json.dumps({'status':201}), content_type='application/json')
	if request.user.basicuser == item.user and request.method == 'POST':
		balanced_addCard = payment_view.addBalancedCard(request)
		# If adding the card fails, serve an error message
		if balanced_addCard['status'] != 201:
			return HttpResponse(json.dumps({'status':balanced_addCard['status'],'error':balanced_addCard['error']}), content_type='application/json')	
		try:
			card = balanced_addCard['card']
			bu = request.user.basicuser
			card_uri = card.uri
			balanced.configure(settings.BALANCED_API_KEY) # Configure Balanced API
			customer = balanced.Customer.find(balanced_addCard['balanceduri'])
			amount = commission.commission(item)
			description = "Charge for item "+str(item.id)
			debit = customer.debit(appears_on_statement_as="Vet Cove Fee",amount=amount,source_uri=card_uri,description=description)
			if not debit.status == "succeeded":
				return HttpResponse(json.dumps({'status':501,'error':'Failed to charge your card.'}), content_type='application/json')
			item.commission_paid = True
			item.save()
			commission_obj = Commission(item=item,price=item.price,amount=amount,payment=card,transaction_number=debit.transaction_number)
			commission_obj.save()
			email_view.composeEmailCommissionCharged(bu,commission_obj)
			return HttpResponse(json.dumps({'status':201}), content_type='application/json')
		except Exception,e:
			print e
			return HttpResponse(json.dumps({'status':501,'error':'Failed to charge your card.'}), content_type='application/json')
 def setUpClass(cls):
     balanced.config.root_uri = 'http://127.0.0.1:5000/'
     if not balanced.config.api_key_secret:
         api_key = balanced.APIKey().save()
         balanced.configure(api_key.secret)
         cls.api_key = api_key
         cls.merchant = api_key.merchant
         balanced.Marketplace().save()
Exemplo n.º 20
0
 def __create_anon(self,email=None,tel=None, name=None):
     #create anonymous customer
     balanced.configure(baccount)
     if email and tel:
         customer = balanced.Customer(email=email, phone=tel, name=name).save()
     else:
         customer = balanced.Customer(name=name).save()
     return customer
Exemplo n.º 21
0
    def create_customer(self, customer):
        api_key = customer.company.processor_key
        balanced.configure(api_key)

        self.logger.debug("Creating Balanced customer for %s", customer.guid)
        record = self.customer_cls(**{"meta.billy_customer_guid": customer.guid}).save()
        self.logger.info("Created Balanced customer for %s", customer.guid)
        return record.uri
Exemplo n.º 22
0
def clean_balanced_processor_key(event):
    """This ensures we won't leave the API key of balanced to the same thread
    (as there is a thread local object in Balanced API), in case of using it
    later by accident, or for security reason.

    """
    import balanced
    balanced.configure(None)
Exemplo n.º 23
0
 def __test(self):
     balanced.configure(testaccount)
     # buyer = balanced.Marketplace.my_marketplace.create_buyer(
     # '*****@*****.**', name='Elaien Ou',
 # card_uri='/v1/marketplaces/TEST-MP59PrHkpa0ko7BaYwp0CkH5/cards/CC5voIUOldIsY8MUi14myQPR'
 # )
     customer = balanced.Customer().save()
     logging.info(customer.id)
Exemplo n.º 24
0
 def setUpClass(cls):
     super(BalancedHarness, cls).setUpClass()
     cls.balanced_api_key = balanced.APIKey().save().secret
     balanced.configure(cls.balanced_api_key)
     mp = balanced.Marketplace.my_marketplace
     if not mp:
         mp = balanced.Marketplace().save()
     cls.balanced_marketplace = mp
Exemplo n.º 25
0
 def setUpClass(cls):
     super(BalancedHarness, cls).setUpClass()
     cls.balanced_api_key = balanced.APIKey().save().secret
     balanced.configure(cls.balanced_api_key)
     mp = balanced.Marketplace.my_marketplace
     if not mp:
         mp = balanced.Marketplace().save()
     cls.balanced_marketplace = mp
Exemplo n.º 26
0
 def setUpClass(cls):
     balanced.config.root_uri = 'http://127.0.0.1:5000/'
     if not balanced.config.api_key_secret:
         api_key = balanced.APIKey().save()
         balanced.configure(api_key.secret)
         cls.api_key = api_key
         cls.merchant = api_key.merchant
         balanced.Marketplace().save()
Exemplo n.º 27
0
def clean_balanced_processor_key(event):
    """This ensures we won't leave the API key of balanced to the same thread
    (as there is a thread local object in Balanced API), in case of using it
    later by accident, or for security reason.

    """
    import balanced
    balanced.configure(None)
Exemplo n.º 28
0
def createCard(request):
	# configure api key: https://dashboard.balancedpayments.com/#/start
	balanced.configure('ak-test-1k3ToGXhUzsAVWnjlUbLelZv92kMLQAwF')
	#create a new balanced customer
	customer = balanced.Customer().save()
	if request.POST.get('submit') == 'cc':
		#get tokenized card and save to customer
		customer.add_card(request.POST.get('uri'))
		c = Customer(name='', uri=customer.uri,created_at=datetime.datetime.now())
		c.save()
		#debit customer
		trans=customer.debit(amount=5000, appears_on_statement_as='test', description='test description')
	elif request.POST.get('submit') == 'ba':
		#get tokenized bank account  and create a verification
		bank_account = balanced.BankAccount.find(request.POST.get('uri'))
		customer.add_bank_account(bank_account)
		verification = bank_account.verify()
		#TODO: Bring to a new form where customer inputs the amounts deposited into their account
		#get customers verification amounts and verify with verify.save()
		verification.amount_1 = 1
		verification.amount_2 = 1
		verified = verification.save()
		#create new customer and debit if verified
		c = Customer(name='', uri=customer.uri,created_at=datetime.datetime.now())
		c.save()
		if verified.state == 'verified':
			trans = customer.debit(amount=1000)
	if request.POST.get('recurring') == 'true' and trans.status == 'succeeded':
		r = RecurringTransaction(customer=c,
			amount=5000,
			date_first_transacted=datetime.datetime.now(), 
			transaction_type=1, #choice between bank account and card?
			soft_descriptor="test",
			description="test description",
			last_transaction = datetime.datetime.now(),
			date_to_charge= datetime.datetime.now().day, 
		)
		r.save()
	elif request.POST.get('recurring') == 'false' and trans.status == 'succeeded':
		t = Transaction(customer=c,
			amount=5000,
			date_first_transacted=datetime.datetime.now(), 
			transaction_type=1, #choice between bank account and card?
			soft_descriptor="test",
			description="test description",
		)
		t.save()
	else:
		HttpResponse(status=400)
	return HttpResponse(status=201)






	#djangocron or billy
	#create models for transactions and customers and maybe cards with last 4 digits?
Exemplo n.º 29
0
 def test_empty_list(self):
     # Notice: we need a whole new marketplace to reproduce the bug,
     # otherwise, it's very likely we will consume records created
     # by other tests
     balanced.configure(None)
     api_key = balanced.APIKey().save()
     balanced.configure(api_key.secret)
     balanced.Marketplace().save()
     self.assertEqual(balanced.Credit.query.all(), [])
Exemplo n.º 30
0
    def create_customer(self, customer):
        api_key = customer.company.processor_key
        balanced.configure(api_key)

        self.logger.debug('Creating Balanced customer for %s', customer.guid)
        record = self.customer_cls(**{
            'meta.billy_customer_guid': customer.guid,
        }).save()
        self.logger.info('Created Balanced customer for %s', customer.guid)
        return record.uri
Exemplo n.º 31
0
 def __init__(self):
     import json
     
     # To keep the API key a secret while still being able to showcase this script, a config script is used instead
     f = open('balance.sfu', 'r')
     self.api_key = json.loads(f.read())
     f.close()
     
     self.key = self.api_key['token']['testing']
     balanced.configure(self.key)
Exemplo n.º 32
0
    def __init__(self):
        import json

        # To keep the API key a secret while still being able to showcase this script, a config script is used instead
        f = open('balance.sfu', 'r')
        self.api_key = json.loads(f.read())
        f.close()

        self.key = self.api_key['token']['testing']
        balanced.configure(self.key)
Exemplo n.º 33
0
 def marketplace(self):
     if not self.secret:
         logger.debug('creating api key')
         self.secret = balanced.APIKey().save().secret
     balanced.configure(self.secret)
     try:
         marketplace = balanced.Marketplace.mine
     except balanced.exc.NoResultFound:
         logger.debug('creating marketplace')
         marketplace = balanced.Marketplace().save()
     return marketplace
 def setUp(self):
     self.target_url = os.environ.get(
         'BILLY_TEST_URL', 
         'http://127.0.0.1:6543')
     self.processor_key = os.environ.get(
         'BILLY_TEST_PROCESSOR_KEY', 
         'ef13dce2093b11e388de026ba7d31e6f')
     self.marketplace_uri = os.environ.get(
         'BILLY_TEST_MARKETPLACE_URI', 
         '/v1/marketplaces/TEST-MP6lD3dBpta7OAXJsN766qA')
     balanced.configure(self.processor_key)
Exemplo n.º 35
0
def billing(env):
    balanced.configure(env.balanced_api_secret)

    if env.braintree_sandbox_mode:
        braintree_env = braintree.Environment.Sandbox
    else:
        braintree_env = braintree.Environment.Production

    braintree.Configuration.configure(braintree_env, env.braintree_merchant_id,
                                      env.braintree_public_key,
                                      env.braintree_private_key)
Exemplo n.º 36
0
 def setUpClass(cls):
     cls.processor_key = os.environ.get('BILLY_TEST_PROCESSOR_KEY', None)
     cls.marketplace_uri = os.environ.get('BILLY_TEST_MARKETPLACE_URI', None)
     if cls.processor_key is None:
         api_key = balanced.APIKey().save()
         cls.processor_key = api_key.secret
         balanced.configure(cls.processor_key)
     try:
         cls.marketplace_uri = balanced.Marketplace.my_marketplace.href
     except (NoResultFound, balanced.exc.NoResultFound):
         cls.marketplace_uri = balanced.Marketplace().save().href
Exemplo n.º 37
0
 def __create_cust(self,email=None):
     #create customer
     # balanced.configure(testaccount)
     balanced.configure(baccount)
     if not self.user_prefs.cust_id:
         customer = balanced.Customer(email=email, facebook=self.user_prefs.userid).save()
         u = self.user_prefs.key.get()
         u.cust_id = customer.id
         u.put()
     else:
         customer = balanced.Customer.find('/v1/customers/' + self.user_prefs.cust_id)
     return customer
Exemplo n.º 38
0
def create_cust(user):
    #create customer
    # balanced.configure(testaccount)
    balanced.configure(baccount)
    if not user.cust_id:
        customer = balanced.Customer(email=user.email, facebook=user.userid).save()
        user.cust_id = customer.id
        user.put()
    else:
        customer = balanced.Customer.find('/v1/customers/' + user.cust_id)
    return customer
        
Exemplo n.º 39
0
 def setUpClass(cls):
     cls.processor_key = os.environ.get('BILLY_TEST_PROCESSOR_KEY', None)
     cls.marketplace_uri = os.environ.get('BILLY_TEST_MARKETPLACE_URI',
                                          None)
     if cls.processor_key is None:
         api_key = balanced.APIKey().save()
         cls.processor_key = api_key.secret
         balanced.configure(cls.processor_key)
     try:
         cls.marketplace_uri = balanced.Marketplace.my_marketplace.href
     except (NoResultFound, balanced.exc.NoResultFound):
         cls.marketplace_uri = balanced.Marketplace().save().href
 def marketplace(self):
     balanced.config.root_uri = self.root_uri
     if not self.secret:
         logger.debug('creating api key')
         self.secret = balanced.APIKey().save().secret
     balanced.configure(self.secret)
     try:
         marketplace = balanced.Marketplace.mine
     except balanced.exc.NoResultFound:
         logger.debug('creating marketplace')
         marketplace = balanced.Marketplace().save()
     return marketplace
Exemplo n.º 41
0
    def setUpClass(cls):
        with balanced.key_switcher(None):
            cls.api_key = balanced.APIKey().save()
        balanced.configure(cls.api_key.secret)
        cls.marketplace = balanced.Marketplace().save()
        cls.user = User.objects.create_user('john', '*****@*****.**', 'pass')
        cls.user.save()

        card = balanced.Card(**FIXTURES['card']).save()
        cls.card = models.Card.create_from_card_uri(cls.user, card.uri)
        cls.buyer = cls.card.user.balanced_account
        # put some money in the escrow account
        cls.buyer.debit(100 * 100, 'test')  # $100.00
Exemplo n.º 42
0
    def setUpClass(cls):
        with balanced.key_switcher(None):
            cls.api_key = balanced.APIKey().save()
        balanced.configure(cls.api_key.secret)
        cls.marketplace = balanced.Marketplace().save()
        cls.user = User.objects.create_user('john', '*****@*****.**', 'pass')
        cls.user.save()

        card = balanced.Card(**FIXTURES['card']).save()
        cls.card = models.Card.create_from_card_uri(cls.user, card.uri)
        cls.buyer = cls.card.user.balanced_account
        # put some money in the escrow account
        cls.buyer.debit(100 * 100, 'test')  # $100.00
Exemplo n.º 43
0
 def test_register_callback(self):
     balanced.configure(self.processor_key)
     # create a company
     company = self.create_company()
     guid = company['guid']
     callback_key = str(company['callback_key'])
     callbacks = balanced.Callback.query.all()
     callback_urls = set()
     for callback in callbacks:
         callback_urls.add(callback.url)
     expected_url = urlparse.urljoin(
         self.target_url,
         '/v1/companies/{}/callbacks/{}/'.format(guid, callback_key))
     self.assertIn(expected_url, callback_urls)
Exemplo n.º 44
0
    def __init__(self, *args, **kwargs):
        kwargs['static_folder'] = config['TEMPLATES']['STATIC_DIR']
        kwargs['static_url_path'] = ''
        super(RentMyBike, self).__init__(config['APPLICATION_NAME'], *args, **kwargs)
        self.debug = self.config['DEBUG']

        self._register_error_handler(None, Exception, self.error_handler)
        self._register_error_handler(None, 500, self.error_handler)
        self.before_request(self.inject_csrf_token)
        self.teardown_request(self.session_cleanup)

        self.emailer = Mail()
        self.emailer.init_app(self)

        balanced.configure(self.config['BALANCED_SECRET'])
        self.marketplace_href = balanced.Marketplace.mine.href
Exemplo n.º 45
0
    def test_config_does_not_change_across_threads(self):
        threads = []

        for _ in xrange(2):
            t = TestConfigThread()
            threads.append(t)

        # change configuration once the threads are created
        balanced.configure('test')

        for t in threads:
            t.start()

        for t in threads:
            t.join(len(threads))
            self.assertTrue(t.key)
Exemplo n.º 46
0
def main():
    balanced_key = 'ef13dce2093b11e388de026ba7d31e6f'
    mp_uri = '/v1/marketplaces/TEST-MP6lD3dBpta7OAXJsN766qA'
    endpoint = 'http://127.0.0.1:6543'

    balanced.configure(balanced_key)
    marketplace = balanced.Marketplace.find(mp_uri)
    # create a card to charge
    card = marketplace.create_card(
        name='BILLY_INTERGRATION_TESTER',
        card_number='5105105105105100',
        expiration_month='12',
        expiration_year='2020',
        security_code='123',
    )

    api = BillyAPI(None, endpoint=endpoint)
    company = api.create_company(processor_key=balanced_key)
    api_key = company.api_key

    api = BillyAPI(api_key, endpoint=endpoint)
    customer = company.create_customer()
    plan = company.create_plan(
        plan_type=Plan.TYPE_DEBIT,
        frequency=Plan.FREQ_MONTHLY,
        amount=500,
    )
    subscription = plan.subscribe(
        customer_guid=customer.guid,
        funding_instrument_uri=card.uri,
    )
    invoice = customer.invoice(
        amount=1000,
        appears_on_statement_as='FooBar Hosting',
        items=[
            dict(name='Hosting Service A', amount=1000),
        ],
        adjustments=[dict(amount=-100, reason='Coupon discount')])

    with open(sys.argv[1], 'wt') as output:
        dump_resource(output, 'Company', company)
        dump_resource(output, 'Customer', customer)
        dump_resource(output, 'Plan', plan)
        dump_resource(output, 'Subscription', subscription)
        dump_resource(output, 'Invoice', invoice)
        dump_resource(output, 'Transaction',
                      list(subscription.list_transactions())[0])
Exemplo n.º 47
0
    def bootstrap(cls, ctx):
        # api conf
        if ctx.storage.get('api_location') != ctx.api_location:
            ctx.storage.clear()
            ctx.storage['api_location'] = ctx.api_location
        balanced.config.root_uri = ctx.storage['api_location']
        if 'api_key' not in ctx.storage:
            ctx.storage.clear()
            ctx.storage['api_location'] = ctx.api_location
            logger.debug('creating api key')
            key = balanced.APIKey().save()
            ctx.storage['api_key'] = key.secret
        balanced.configure(ctx.storage['api_key'])

        # marketplace
        if 'marketplace_id' not in ctx.storage:
            logger.debug('creating marketplace')
            marketplace = balanced.Marketplace().save()
            ctx.storage['marketplace_uri'] = marketplace.uri
            ctx.storage['marketplace_id'] = marketplace.id

        # card
        if 'card_id' not in ctx.storage:
            logger.debug('creating card')
            card = ctx.marketplace.create_card(
                **{
                    'name': 'Benny Riemann',
                    'card_number': '4111111111111111',
                    'expiration_month': 4,
                    'expiration_year': 2014,
                    'security_code': 323,
                    'street_address': '167 West 74th Street',
                    'postal_code': '10023',
                    'country_code': 'USA',
                    'phone_number': '+16509241212'
                })
            ctx.marketplace.create_buyer(None, card.uri)
            ctx.storage['card_uri'] = card.uri
            ctx.storage['card_id'] = card.id

        # escrow
        thresh_h, thresh_l = 10000000, 100000
        if ctx.marketplace.in_escrow < thresh_l:
            amount = thresh_h - ctx.marketplace.in_escrow
            logger.debug('incrementing escrow balanced %s', amount)
            ctx.card.debit(amount)
Exemplo n.º 48
0
    def _do_transaction(self, transaction, resource_cls, method_name,
                        extra_kwargs):
        api_key = transaction.subscription.plan.company.processor_key
        balanced.configure(api_key)
        # make sure we won't duplicate the transaction
        try:
            record = (resource_cls.query.filter(
                **{
                    'meta.billy.transaction_guid': transaction.guid
                }).one())
        except balanced.exc.NoResultFound:
            record = None
        # We already have a record there in Balanced, this means we once did
        # transaction, however, we failed to update database. No need to do
        # it again, just return the id
        if record is not None:
            self.logger.warn(
                'Balanced transaction record for %s already '
                'exist', transaction.guid)
            return record.uri

        # TODO: handle error here
        # get balanced customer record
        external_id = transaction.subscription.customer.external_id
        balanced_customer = self.customer_cls.find(external_id)

        # prepare arguments
        kwargs = dict(
            amount=self._to_cent(transaction.amount),
            description=(
                'Generated by Billy from subscription {}, scheduled_at={}'.
                format(transaction.subscription.guid,
                       transaction.scheduled_at)),
            meta={'billy.transaction_guid': transaction.guid},
        )
        kwargs.update(extra_kwargs)

        method = getattr(balanced_customer, method_name)
        self.logger.debug('Calling %s with args %s', method.__name__, kwargs)
        record = method(**kwargs)
        self.logger.info('Called %s with args %s', method.__name__, kwargs)
        return record.uri
Exemplo n.º 49
0
    def do(self):
    	balanced.configure('ak-test-LgwABu1X3Lz1oi1pFbyL8dxkd62hFMYq')
    	#get all transactions 
        #import pdb; pdb.set_trace();
        today= datetime.datetime.now().day
        tomorrow= datetime.datetime.now() + datetime.timedelta(days=1)
        if tomorrow.day == 1:
            RecurringTransactions = RecurringTransaction.objects.filter(date_to_charge__gte = today).filter( last_transaction__lt=datetime.datetime.now())
        else:
            RecurringTransactions = RecurringTransaction.objects.filter(date_to_charge =today).filter(last_transaction__lt=datetime.datetime.now())
    	for transaction in RecurringTransactions:
            customerToCharge = balanced.Customer.find(transaction.customer.uri)
            customerToCharge.debit(transaction.amount)
            #change soft descriptor
            transaction.last_transaction = datetime.datetime.now()
            transaction.save()
            print('charged '+ transaction.customer.name )
        pass    # do your thing here

        
Exemplo n.º 50
0
    def debit_payments(self):
        balanced.configure(BALANCED['API_KEY'])

        payment_transactions_to_debit_list = PaymentTransaction.objects.filter(
            status=PAYMENT_TRANSACTION_STATUSES_CHOICES.pending)
        for payment_transaction in payment_transactions_to_debit_list:
            print 'running debit for transaction #' + str(
                payment_transaction.id)

            pledger_balanced_account = BalancedAccount.objects.get(
                pk=payment_transaction.balanced_account_id)
            balanced_account = balanced.Account.find(
                pledger_balanced_account.uri)

            with transaction.commit_on_success():
                total_amount_cents = int(
                    Decimal(payment_transaction.total_amount *
                            Decimal(100)).quantize((Decimal('1'))))
                balanced_debit = balanced_account.debit(
                    appears_on_statement_as=payment_transaction.statement_text,
                    amount=total_amount_cents,
                    description=payment_transaction.description,
                )

                if balanced_debit.status == 'succeeded':
                    payment_transaction.status = PAYMENT_TRANSACTION_STATUSES_CHOICES.paid
                    payment_transaction.datetime_debited = now()
                else:
                    payment_transaction.status = PAYMENT_TRANSACTION_STATUSES_CHOICES.rejected
                payment_transaction.balanced_status = balanced_debit.status
                try:
                    payment_transaction.balanced_transaction_number = balanced_debit.transaction_number
                    payment_transaction.source_uri = balanced_debit.source.uri
                    payment_transaction.uri = balanced_debit.uri
                except AttributeError:
                    pass
                payment_transaction.save()

                self.update_donation_transaction(payment_transaction)
                if payment_transaction.status == PAYMENT_TRANSACTION_STATUSES_CHOICES.paid:
                    self.update_project_balances(payment_transaction)
Exemplo n.º 51
0
            'janet',
            is_suspicious=False,
            claimed_time='now',
            balanced_customer_href=self.janet_href,
            last_bill_result='')
        self.homer = self.make_participant(
            'homer',
            is_suspicious=False,
            claimed_time='now',
            balanced_customer_href=self.homer_href,
            last_ach_result='')


with use_cassette('BalancedHarness'):
    cls = BalancedHarness
    balanced.configure(balanced.APIKey().save().secret)
    mp = balanced.Marketplace.my_marketplace
    if not mp:
        mp = balanced.Marketplace().save()
    cls.balanced_marketplace = mp

    cls.david_href = cls.make_balanced_customer()

    cls.janet_href = cls.make_balanced_customer()
    cls.card = balanced.Card(
        number='4111111111111111',
        expiration_month=10,
        expiration_year=2020,
        address={
            'line1': "123 Main Street",
            'state': 'Confusion',
Exemplo n.º 52
0
import balanced

balanced.configure('ak-test-2eKlj1ZDfAcZSARMf3NMhBHywDej0avSY')

card = balanced.Card.fetch('/cards/CC4zyuNpxY0A0eAf87SeULCR')
card.meta = {
    'twitter.id': '1234987650',
    'facebook.user_id': '0192837465',
    'my-own-customer-id': '12345'
}
card.save()
Exemplo n.º 53
0
from __future__ import unicode_literals

import balanced

api_key = balanced.APIKey().save()
balanced.configure(api_key.secret)
marketplace = balanced.Marketplace().save()

# https://docs.balancedpayments.com/1.1/overview/resources/#test-credit-card-numbers

declined_card = balanced.Card(
    number='4444444444444448',
    expiration_month='12',
    expiration_year='2015',
).save()

bank_account = balanced.BankAccount(
    account_number='1234567890',
    routing_number='321174851',
    name='Jack Q Merchant',
).save()

# see https://github.com/balanced/balanced-api/blob/master/fixtures/_models/error.json for all possible error codes
try:
    declined_card.debit(amount=100)
except balanced.exc.BalancedError as ex:
    assert ex.category_code == 'card-declined'

try:
    bank_account.credit(amount=1000)
except balanced.exc.HTTPError as ex:
Exemplo n.º 54
0
import balanced

balanced.configure('ak-test-1p1Tsac7gHeMQowL2seB7ieliuAJAufyq')

bank_account = balanced.BankAccount.find(
    '/v1/bank_accounts/BA6wDj2MwJTwkPA4s4rEMq2y')
credits = bank_account.credits.all()
Exemplo n.º 55
0
import balanced

balanced.configure("c72cb360d3ae11e29593026ba7d31e6f")

customer = balanced.Customer.find('/v1/customers/CU6W5pSk2CUXQxhENqyGRvQe')
holds = customer.holds.all()
Exemplo n.º 56
0
import balanced

balanced.configure("46c08048cd8811e2acae026ba7c1aba6")

refund = balanced.Refund.find(
    "/v1/marketplaces/TEST-MP29J5STPtZVvnjAFndM0N62/refunds/RF3n0NOGtl7IeHTwp1c5Bvfw"
)
Exemplo n.º 57
0
def billing():
    stripe.api_key = os.environ['STRIPE_SECRET_API_KEY']
    stripe.publishable_api_key = os.environ['STRIPE_PUBLISHABLE_API_KEY']
    balanced.configure(os.environ['BALANCED_API_SECRET'])
from flask import Flask, render_template, request, send_file, abort, redirect, make_response, url_for, jsonify, flash
from pprint import pprint
from modules.models import *
from modules.forms import *
from modules.custom_jinja_filters import *
import balanced

app = Flask(__name__)
app.config.from_pyfile('config.py', silent=False)
app.jinja_env.filters['format_currency'] = format_currency
balanced.configure(app.config['BALANCED_API_KEY'])


@app.route("/", methods=['GET', 'POST'])
def index():
    form = demoForm(csrf_enabled=False)
    if form.validate_on_submit():
        pprint(request.form)
        return redirect(
            url_for('order',
                    username=form.merchant.data,
                    item=form.item.data,
                    price=form.amount.data))

    return render_template('index.html', form=form)


@app.route("/order/<username>/<item>/<float:price>", methods=['GET', 'POST'])
@app.route("/order/<username>/<item>/<int:price>", methods=['GET', 'POST'])
def order(username, item, price):
    form = orderDetailsForm()
Exemplo n.º 59
0
 def setUp(self):
     balanced.configure('not-test')
Exemplo n.º 60
0
 def tearDown(self):
     balanced.configure(None)