Example #1
0
    def refund_transaction(self, amount=None, comment=None):
        if self.status != TransactionStatus.Passed:
            logger.debug("Warning: Transaction is NOT PASSED not found. Can't refund.")
            return None

        if not self.aim_transaction_id:
            logger.debug("Warning: Transaction ID not found. Can't refund.")
            return None

        amount = amount or self.get_debit_total()
        profile = self.user.get_profile()
        billing = profile.get_billing_data()
        shipping = profile.get_shipping_data()
        aim_data = {
            'x_email': self.user.email,
            'x_cust_id': self.user.id,
        }

        aim = create_aim()
        if self.card_data:
            cc = self.card_data['number'][-4:]
        else:
            cc = self.payment_method[-4:]
        res = aim.refund(self.aim_transaction_id, amount, cc, billing, shipping, **aim_data)
        if res.response_code != 1:
            logger.debug("Error: Can't refund.")
            return res
        profile.store_credits += self.applied_credits
        profile.save()
        refund = Refund(payment=self, amount=amount, comment=comment,
                        aim_transaction_id=res.transaction_id)
        refund.save()
        return res
Example #2
0
    def take_charge(self, aim_data):
        charge_amount = self.get_charge_amount()
        aim_transaction_id = 0
        if charge_amount:
            try:
                aim = create_aim()

                def assert_res(res):
                    if res.response_code == 1:
                        return
                    if res.response_reason_code in [2, 3, 4]:
                        raise BuyCartCompleteException('Insufficient funds are available for this transaction.')
                    if res.avs_response == 'U':
                        raise BuyCartCompleteException('We do not accept prepaid cards.')
                    raise BuyCartCompleteException('We are unable to process you credit card at this time.')

                res = aim.authorize(charge_amount, **aim_data)
                logger.debug('Credit card preauth full amount ($%s) approved? %s', charge_amount, 'YES' if res.response_code == 1 else 'NO')
                assert_res(res)

                aim_transaction_id = res.transaction_id
                res = aim.prior_auth_capture(charge_amount, res.transaction_id)
                logger.debug('Capture full amount ($%s) approved? %s', charge_amount, 'YES' if res.response_code == 1 else 'NO')
                assert_res(res)
            except BuyCartCompleteException, e:
                msg = 'Failed to bill Shop Order #%s - %s' % (self.order_no(), e.message)
                logger.debug('Authorize.net error: %s', msg)
                self.change_status(BuyOrderStatus.Problem, e.message)
                return None
Example #3
0
 def create_form(data):
     return BillingForm(data,
                        melissa=get_melissa(),
                        request=request,
                        activate_correction=True,
                        shipping_address=profile.get_shipping_data(),
                        card_verification_callback=card_verification_callback,
                        aim=create_aim())
Example #4
0
def take_money(user_or_profile, amount, reason,
                invoice_num_func=None, description=None,
                take_tax=True, take_credits=True, payment_type="AUTH_CAPTURE"):
    """
    Takes money from user's CC and / or store credits.

    *Args*:
    ``amount``: e. g. Decimal('13.95')
    ``reason``: e. g. 'rent'
    ``invoice_num_func``: function that takes ``profile`` and ``billing_history``,
                            and returns ``invoice_num`` (e. g. 'RENT_SUBS_1_2')
    ``description``: e. g. 'Monthly Membership - Nov 5, 2011 - Dec 5, 2011'
    """
    profile = get_profile(user_or_profile)
    card = profile.billing_card
    aim_method = {
        "AUTH_CAPTURE": "capture"
    }[payment_type]
    tax_amount = 0
    if take_tax:
        tax_amount = get_tax_amount(amount, card.state, card.county)

    withdrawed_credits = withdraw_store_credits(profile, amount)
    logger.debug('Taking $%s store credits...', withdrawed_credits)
    amount -= withdrawed_credits
    aim_response = None

    billing_history = BillingHistory.create(
        profile.user, profile.get_billing_card_display(),
        debit=amount, reason=reason, type=TransactionType.RentPayment
    )

    if amount:
        logger.debug('Taking amount of $%s (+$%s tax)...', amount, tax_amount)
        aim = create_aim()
        invoice_num = invoice_num_func(profile, billing_history)
        aim_data = create_aim_data(amount, invoice_num, description, profile)
        aim_response = getattr(aim, aim_method)(amount, **aim_data)
        logger.debug('AIM aim_responseponse code: %s (%s)', aim_response.response_code, aim_response.response_reason_code)

    _create_billing_history(billing_history, profile, amount, tax_amount,
                            description, withdrawed_credits, aim_response)

    if amount:
        if aim_response.response_code != 1:
            if aim_response.response_code == 3 and aim_response.response_reason_code in [6, 7, 8]:
                raise PaymentError("Credit card is expired")
            elif aim_response.response_reason_code in [2, 3, 4]:
                raise PaymentError("Insufficient funds are available for this transaction.")
            elif aim_response.avs_response == "U":
                raise PaymentError("We do not accept prepaid cards.")
            else:
                raise PaymentError("We are unable to process you credit card at this time.")

    send_billing_charge_approved(profile, amount)

    return aim_response
Example #5
0
    def create(request, initial=None):
        profile = request.user.get_profile()
        shipping_data = profile.get_name_data()
        shipping_data.update(profile.get_shipping_address_data())
        billing_data = profile.get_billing_name_data()
        billing_data.update(profile.get_billing_address_data())
        billing_data.update(profile.get_billing_card_data())
        initial = {
            0: shipping_data,
            1: billing_data,
        }

#        initial[0].update({
#            'first_name': 'pavel',
#            'last_name': 'reznikov',
#            'address1': '312 courthouse sq',
#            'address2': '',
#            'city': 'bay minete',
#            'state': 'AL',
#            'zip_code': '36507',
#        })
#        initial[1].update({
#            'first_name': 'pavel1',
#            'last_name': 'reznikov1',
#            'address1': '312 courthouse sq1',
#            'address2': '1',
#            'city': 'bay minete1',
#            'state': 'AL',
#            'zip_code': '36501',
#        })

        keys = ['0-first_name', '0-last_name', '0-address1', '0-address2', '0-city', '0-state', '0-zip_code']
        shipping_info = dict([(x[2:], request.POST[x]) for x in filter(lambda z: z in keys, request.POST.keys())])
        billing_info = initial.get(1) 
        
        request.checkout_wizard = AuthenticatedCheckoutWizard(
            'cart/checkout/authenticated.html',
            [NameAndAddressForm, CheckoutForm],
            initial=initial,
            title='Checkout', 
            form_kwargs={
                0: {'melissa': get_melissa(), 
                    'activate_correction': True, 
                    'request': request, },
                1: {'melissa': get_melissa(), 
                    'activate_correction': True, 
                    'request': request,
                    'shipping_address': shipping_info,
#                    'billing_address': billing_info,
                    'aim': create_aim(), },
            },
            context={
                'shipping_info': shipping_info,
                'billing_info': billing_info,
            },)
        return request.checkout_wizard
Example #6
0
    def create(request, initial={}):
#        initial = {
#            0: {
#                'email': '*****@*****.**',
#                'username': '******',
#                'password': '******',
#                'confirm_password': '******',
#                'how_did_you_hear': 1,
#                'first_name': 'pavel',
#                'last_name': 'reznikov',
#                'address1': '312 courthouse sq',
#                'address2': '',
#                'city': 'bay minete',
#                'state': 'AL',
#                'zip_code': '36507',
#            },
#            1: {
#                'first_name': 'pavel',
#                'last_name': 'reznikov',
#                'address1': '65 E central blvd',
#                'address2': '',
#                'city': 'orlando',
#                'state': 'FL',
#                'zip_code': '32801-2401',
#                'number': '4149605050176387',
#                'exp_month': '1',
#                'exp_year': '2011',
#                'code': '123',
#            },
#        }

        keys = ['0-first_name', '0-last_name', '0-address1', '0-address2', '0-city', '0-state', '0-zip_code']
        shipping_info = dict([(x[2:], request.POST[x]) for x in filter(lambda z: z in keys, request.POST.keys())])
        billing_info = initial.get(1) 
        
        request.checkout_wizard = NonAuthenticatedCheckoutWizard(
            'cart/checkout/non_authenticated.html',
            [ProfileAndShippingForm, CheckoutForm],
            initial=initial,
            title='Checkout', 
            form_kwargs={
                0: {'melissa': get_melissa(),
                    'activate_correction': True, 
                    'request': request, },
                1: {'melissa': get_melissa(), 
                    'activate_correction': True, 
                    'request': request,
                    'shipping_address': shipping_info,
                    'aim': create_aim(), },
            },
            context={
                'shipping_info': shipping_info,
                'billing_info': billing_info,
            },)
        return request.checkout_wizard
    def setUp(self):
        shipping_data = billing_data = {
            "first_name": u"Test",
            "last_name": u"User",
            "address1": u"1 Test St",
            "address2": u"",
            "city": u"Test City",
            "state": u"AK",
            "zip_code": u"12345",
        }

        billing_card_data = {
            "type": u"visa",
            "number": u"4111111111111111",
            "code": u"123",
            "exp_month": u"1",
            "exp_year": u"2018",
        }

        self.profile = Profile.objects.build_and_create(
            username="******",
            email="*****@*****.**",
            password="******",
            shipping_data=shipping_data,
            billing_data=billing_data,
            billing_card_data=billing_card_data,
        )

        aim_data = build_aim_data(
            shipping_data, billing_data, billing_card_data,
            invoice_num="123",
            description="Test Payment",
            email=self.profile.user.email,
            tax=Decimal("1")
        )

        aim = create_aim()
        aim_response = aim.authorize(Decimal("10"), **aim_data)

        self.billing_history = BillingHistory.objects.create(
            user=self.profile.user,
            payment_method=self.profile.get_billing_card_display(),
            description="Test Payment",
            debit=Decimal("10"),
            reason="test-reason",
            type=TransactionType.Unknown,
            card_data=self.profile.get_billing_card_data(),
            tax=Decimal("1"),
            status=TransactionStatus.Authorized,
            aim_transaction_id=aim_response.transaction_id,
            aim_response=aim_response._as_dict,
            message=aim_response.response_reason_text
        )
Example #8
0
    def void_transaction(self):
        aim = create_aim()
        res = aim.void(self.aim_transaction_id, {})
        if res.response_code == 1:
            profile = self.user.get_profile()
            profile.store_credits += self.applied_credits
            profile.save()

            logger.debug('Transaction was voided')
            self.status = TransactionStatus.Canceled
            self.save()
        else:
            logger.debug('Transaction was FAILED to void')
Example #9
0
 def get_form_kwargs(self, step=None):
     return {
         "0": {"request": self.request},
         "1": {
             "melissa": get_melissa(),
             "activate_correction": True,
             "request": self.request,
         },
         "2": {
             "melissa": get_melissa(),
             "activate_correction": True,
             "request": self.request,
             "aim": create_aim()
         },
     }[step]
Example #10
0
 def get_form_kwargs(self, step=None):
     return {
         "0": {"request": self.request},
         "1": {
             "melissa": get_melissa(),
             "activate_correction": True,
             "request": self.request,
             "instances": [self.request.user, self.request.user.profile]
         },
         "2": {
             "melissa": get_melissa(),
             "activate_correction": True,
             "request": self.request,
             "aim": create_aim()
         },
     }[step]
Example #11
0
    def take_penalty_payment(self):
        if self.penalty_payment != None:
            return True, None
        
        aim = create_aim()
        profile = self.user.get_profile()
        card = profile.get_billing_card_data()
        data = {
            'amount': decimal.Decimal('50.0'),
            'number': card['number'], 
            'exp': '/'.join(('%s' % card['exp_month'], ('%s' % card['exp_year'])[-2:])),
            'code': card['code'],
            'billing': profile.get_billing_data(), 
            'shipping': profile.get_shipping_data(), 
            'invoice_num': 'RENT_CLAIM_%s_%s' % (self.user.id, self.id), 
            'description': '%s - Unreturned Game Fees' % self.get_title(),
            'x_email': self.user.email,
            'x_cust_id': self.user.id,
        }
        res = aim.capture(**data)

        billing_history = BillingHistory(user=self.user, 
                                         payment_method=profile.get_payment_card().display_number, 
                                         description=data['description'], 
                                         debit=data['amount'], 
                                         reason='rent', 
                                         type=TransactionType.RentPayment,
                                         status=TransactionStatus.Passed,
                                         card_data=card,
                                         aim_transaction_id=res.transaction_id,
                                         aim_response=res._as_dict,
                                         message=res.response_reason_text)

        if res.response_code != 1:
            self.penalty_payment_tries += 1
            self.next_penalty_payment_date = datetime.now() + timedelta(2)
            self.save()
            billing_history.status = TransactionStatus.Declined
            billing_history.save()
            return False, res
        billing_history.save()
        self.next_penalty_payment_date = None
        self.penalty_payment = billing_history
        self.save()
        return True, res
Example #12
0
    def capture(self):
        if self.status != TransactionStatus.Authorized:
            return None

        try:
            return BillingHistory.objects.get(refered_transaction=self, status=TransactionStatus.Passed)
        except BillingHistory.DoesNotExist:
            pass

        aim = create_aim()
        profile = self.user.get_profile()
        aim_data = {
            'x_email': self.user.email,
            'x_cust_id': self.user.id,
        }
        res = aim.prior_auth_capture(self.get_debit_total(),
                                     self.aim_transaction_id,
                                     profile.get_billing_data(),
                                     profile.get_shipping_data(),
                                     **aim_data)

        success = True
        status = TransactionStatus.Passed

        if res.response_code != 1:
            success = False
            status = TransactionStatus.Declined

        billing_history = BillingHistory(user=self.user,
                                         payment_method=self.payment_method,
                                         description=self.description,
                                         debit=self.debit,
                                         reason=self.reason,
                                         type=self.type,
                                         card_data=self.card_data,
                                         tax=self.tax,
                                         refered_transaction=self,
                                         status=status,
                                         aim_transaction_id=res.transaction_id,
                                         aim_response=res._as_dict,
                                         message=res.response_reason_text)
        billing_history.save()
        return success, billing_history
Example #13
0
    def create(request, initial={}):
        plan = request.POST.get('0-plan')
        if plan is not None:
            plan = plan or '0'
            plan = RentalPlan.get_details(int(plan))

        keys = ['1-first_name', '1-last_name', '1-address1', '1-address2',
                '1-city', '1-state', '1-zip_code']
        shipping_info = dict([(x[2:], request.POST[x]) for x in
                              filter(lambda z: z in keys, request.POST.keys())])
        billing_info = initial.get(2)
        email = request.POST.get('1-email')
        free_trial = False
        all_plans = NewRentalPlan.objects.available_for_signup(request)
        if "free_trial" in [p.slug for p in all_plans]:
            free_trial = True

        request.rent_wizard = NonMemberRentSignUpWizard(
            'members/rent/wizards/non-member-signup.html',
            [PaymentPlanForm, ProfileAndShippingForm, FinishRentalPlanForm],
            initial=initial,
            title='Rental Signup',
            form_kwargs={
                0: {"request": request},
                1: {'melissa': get_melissa(), 'activate_correction': True, },
                2: {'melissa': get_melissa(),
                    'activate_correction': True,
                    'request': request,
                    'email': email,
                    'shipping_address': shipping_info,
                    'aim': create_aim()},
            },
            context={
                'plan': plan,
                'all_plans': all_plans,
                'shipping_info': shipping_info,
                'billing_info': billing_info,
                "free_trial": free_trial,
            }
        )
        return request.rent_wizard
Example #14
0
    def create(request, initial=None):
        plan = request.POST.get('0-plan')
        if plan is not None:
            plan = RentalPlan.get_details(int(plan))
        profile = request.user.get_profile()
        form2_initial = profile.get_billing_data()
        form2_initial.update(profile.get_billing_card_data())
        initial = {
            1: profile.get_shipping_data(),
            2: form2_initial,
        }

        keys = ['1-first_name', '1-last_name', '1-address1', '1-address2',
                '1-city', '1-state', '1-zip_code']
        shipping_info = dict([(x[2:], request.POST[x]) for x in
                              filter(lambda z: z in keys, request.POST.keys())])
        billing_info = form2_initial

        request.rent_wizard = MemberRentSignUpWizard('members/rent/wizards/member-signup.html',
            [PaymentPlanForm, ShippingInformationForm, FinishRentalPlanForm],
            initial=initial,
            title='Rental Signup',
            form_kwargs={
                1: {'melissa': get_melissa(), 'activate_correction': True, },
                2: {'melissa': get_melissa(),
                    'activate_correction': True,
                    'request': request,
                    'shipping_address': shipping_info,
                    'aim': create_aim()},
            },
            context={
                'plan': plan,
                'rental_plans': get_rental_plans_info(request),
                'all_plans': get_all_rental_plans_info(request),
                'shipping_info': shipping_info,
                'billing_info': billing_info,
            })
        return request.rent_wizard
Example #15
0
    def make_first_payment(self, user, profile, billing_card, customer_ip):
        """
        Being used when we would like to bill user for the first time and he doesn't
        have ``MemberRentalPlan`` associated yet.

        May raise ``PaymentError``.
        """
        billing_data = {
            "first_name": billing_card.first_name,
            "last_name": billing_card.last_name,
            "address1": billing_card.address1,
            "address2": billing_card.address2,
            "city": billing_card.city,
            "state": billing_card.state,
            "county": billing_card.county,
            "zip_code": billing_card.zip,
        }
        billing_card_data = billing_card.data.copy()
        shipping_data = {
            "first_name": user.first_name,
            "last_name": user.last_name,
            "address1": profile.shipping_address1,
            "address2": profile.shipping_address2,
            "city": profile.shipping_city,
            "state": profile.shipping_state,
            "county": profile.shipping_county,
            "zip_code": profile.shipping_zip,
        }
        email = user.email

        first_payment_amount = self.get_next_payment_amount()
        first_payment_type = self.get_next_payment_type()
        tax_amount = get_tax_amount(first_payment_amount, billing_data["state"], billing_data.get("county"))

        billing_history = BillingHistory.objects.create(
            payment_method=get_card_display_number(billing_card_data["number"]),
            debit=Decimal(first_payment_amount),
            reason="rent",
            type=TransactionType.RentPayment,
            card_data=billing_card_data,
            tax=tax_amount,
        )

        invoice_num, description = self.get_first_payment_description(billing_history.pk)
        aim_data = build_aim_data(
            shipping_data, billing_data, billing_card_data, invoice_num, description, email, customer_ip, tax_amount
        )

        aim = create_aim()
        success_status = TransactionStatus.Passed
        if first_payment_type == "AUTH_ONLY":
            aim_response = aim.authorize(first_payment_amount, **aim_data)
            success_status = TransactionStatus.Authorized
        elif first_payment_type == "AUTH_CAPTURE":
            aim_response = aim.capture(first_payment_amount, **aim_data)

        billing_history.description = description
        billing_history.aim_transaction_id = aim_response.transaction_id
        billing_history.aim_response = aim_response._as_dict
        billing_history.message = aim_response.response_reason_text
        if aim_response.response_code == 1:
            billing_history.status = success_status
            billing_history.save()
            return billing_history
        else:
            billing_history.status = TransactionStatus.Declined
            billing_history.save()
            raise PaymentError(aim_response.response_reason_text)