Esempio n. 1
0
 def test_checkout_signature_blank_fields(self):
     """
     Fields with blank values should not be included in the signature.
     """
     data = _test_data()
     data['name_first'] = ''
     self.assertEqual(api.checkout_signature(data),
                      '6551205f0fee13cf09174b0b887ec5b3')
     data['name_last'] = ''
     self.assertEqual(api.checkout_signature(data),
                      '8f6435965cd9b00a9a965d93fc6c4c48')
Esempio n. 2
0
    def __init__(self, *args, **kwargs):
        get_first_name = getattr(settings, 'PAYFAST_GET_USER_FIRST_NAME', attrgetter('first_name'))
        get_last_name = getattr(settings, 'PAYFAST_GET_USER_LAST_NAME', attrgetter('last_name'))

        user = kwargs.pop('user', None)
        if user:

            if get_first_name is not None:
                kwargs['initial'].setdefault('name_first', get_first_name(user))
            if get_last_name is not None:
                kwargs['initial'].setdefault('name_last', get_last_name(user))

            # Django 1.11 adds AbstractBaseUser.get_email_field_name()
            email_address = (user.email if django.VERSION < (1, 11) else
                             getattr(user, get_user_model().get_email_field_name()))
            kwargs['initial'].setdefault('email_address', email_address)

        kwargs['initial'].setdefault('notify_url', notify_url())
        kwargs['initial'].setdefault('merchant_id', conf.MERCHANT_ID)
        kwargs['initial'].setdefault('merchant_key', conf.MERCHANT_KEY)

        super(PayFastForm, self).__init__(*args, **kwargs)

        if 'm_payment_id' in self.initial:
            # If the caller supplies m_payment_id, find the existing order, or create it.
            (self.order, created) = PayFastOrder.objects.get_or_create(
                m_payment_id=self.initial['m_payment_id'],
                defaults=dict(
                    user=user,
                    amount_gross=self.initial['amount'],
                ),
            )
            if not created:
                # If the order is existing, check the user and amount fields,
                # and update if necessary.
                #
                # XXX: Also consistency-check that the order is not paid yet?
                #
                if not (self.order.user == user and
                        self.order.amount_gross == self.initial['amount']):
                    self.order.user = user
                    self.order.amount_gross = self.initial['amount']
                    self.order.save()
        else:
            # Old path: Create a new PayFastOrder each time form is instantiated.
            self.order = PayFastOrder.objects.create(
                user=user,
                amount_gross=self.initial['amount'],
            )

            # Initialise m_payment_id from the pk.
            self.order.m_payment_id = str(self.order.pk)
            self.order.save()

            self.initial['m_payment_id'] = self.order.m_payment_id

        # Coerce values to strings, for signing.
        data = {k: str(v) for (k, v) in self.initial.items()}
        self._signature = self.fields['signature'].initial = api.checkout_signature(data)
Esempio n. 3
0
    def __init__(self, *args, **kwargs):
        user = kwargs.pop('user', None)
        if user:
            kwargs['initial'].setdefault('name_first', user.first_name)
            kwargs['initial'].setdefault('name_last', user.last_name)
            kwargs['initial'].setdefault('email_address', user.email)

        kwargs['initial'].setdefault('notify_url', notify_url())
        kwargs['initial'].setdefault('merchant_id', conf.MERCHANT_ID)
        kwargs['initial'].setdefault('merchant_key', conf.MERCHANT_KEY)

        super(PayFastForm, self).__init__(*args, **kwargs)

        if 'm_payment_id' in self.initial:
            # If the caller supplies m_payment_id, find the existing order, or create it.
            (self.order, created) = PayFastOrder.objects.get_or_create(
                m_payment_id=self.initial['m_payment_id'],
                defaults=dict(
                    user=user,
                    amount_gross=self.initial['amount'],
                ),
            )
            if not created:
                # If the order is existing, check the user and amount fields,
                # and update if necessary.
                #
                # XXX: Also consistency-check that the order is not paid yet?
                #
                if not (self.order.user == user
                        and self.order.amount_gross == self.initial['amount']):
                    self.order.user = user
                    self.order.amount_gross = self.initial['amount']
                    self.order.save()
        else:
            # Old path: Create a new PayFastOrder each time form is instantiated.
            self.order = PayFastOrder.objects.create(
                user=user,
                amount_gross=self.initial['amount'],
            )

            # Initialise m_payment_id from the pk.
            self.order.m_payment_id = str(self.order.pk)
            self.order.save()

            self.initial['m_payment_id'] = self.order.m_payment_id

        # Coerce values to strings, for signing.
        data = {k: str(v) for (k, v) in self.initial.items()}
        self._signature = self.fields[
            'signature'].initial = api.checkout_signature(data)
def do_checkout(
        checkout_data,  # type: Dict[str, str]
        sign_checkout,  # type: bool
):  # type: (...) -> Dict[str, str]
    """
    Common test helper: do a checkout, and assert results.

    This takes unsigned checkout data, and will add a signature if `sign_checkout` is true.

    Return the checkout page's parse.
    """
    # Expected values for result assertions:
    try:
        expected_amount = '{:.2f}'.format(
            decimal.Decimal(checkout_data['amount']))
    except decimal.InvalidOperation:
        # We may be testing a value that isn't Decimal-parseable;
        # in that case, just expect it unmodified.
        expected_amount = checkout_data['amount']
    expected_item_name = checkout_data['item_name'].strip(
    )  # PayFast strips this for display.
    expected_payment_summary = (
        '{} Payment total R {} ZAR'.format(expected_item_name,
                                           expected_amount).
        strip()  # Strip to handle item names that render empty.
    )

    if sign_checkout:
        assert 'signature' not in checkout_data, checkout_data
        checkout_data['signature'] = api.checkout_signature(checkout_data)

    response = post_sandbox_checkout(checkout_data)
    parsed = parse_payfast_page(response)
    assert {
        'session_type': 'p-sb',
        'session_id': parsed.get('session_id', 'MISSING'),
        'payment_summary': expected_payment_summary,
        'payment_method': '1',
        'pay_button': 'Complete Payment',
    } == parsed

    return parsed
Esempio n. 5
0
 def test_checkout_signature(self):
     data = _test_data()
     self.assertEqual(api.checkout_signature(data),
                      '481366608545707be67c6514386b3fb1')