Example #1
0
    def process_recurring_subscriptions(self, recurlist, testing=False):
        """Post all subscription requests."""

        results = []
        for recur in recurlist:
            success, reason, response, subscription_id = self.process_recurring_subscription(
                recur, testing=testing)
            if success:
                if not testing:
                    payment = self.record_payment(
                        order=self.order,
                        amount=recur['charged_today'],
                        transaction_id=subscription_id,
                        reason_code=reason)
                    results.append(
                        ProcessorResult(self.key,
                                        success,
                                        response,
                                        payment=payment))
            else:
                self.log.info(
                    "Failed to process recurring subscription, %s: %s", reason,
                    response)
                results = ProcessorResult(self.key, success, response)
                break

        return success, results
Example #2
0
 def process(self, *args, **kwargs):
     if self.order.paid_in_full:
         # marc order as succed to emit signals, if not present, 
         # orders with balance 0 not correctly notified
         self.order.order_success()
         return ProcessorResult('FREE', True, _('Success'))
     else:
         return ProcessorResult('FREE', False, _('This order does not have a zero balance'))
Example #3
0
    def capture_payment(self, testing=False, order=None, amount=None):
        """process the transaction through tclink"""
        if not order:
            order = self.order

        if amount is None:
            amount = order.balance

        if order.paid_in_full:
            self.log_extra('%s is paid in full, no capture attempted.', order)
            self.record_payment()
            return ProcessorResult(self.key, True,
                                   _("No charge needed, paid in full."))

        self.log_extra('Capturing payment for %s', order)

        self.prepare_post(order, amount)

        result = tclink.send(self.transactionData)
        status = result['status']
        payment = None
        success = False

        if status == 'approved':
            payment = self.record_payment(order=order,
                                          amount=amount,
                                          transaction_id="",
                                          reason_code=status)
            success = True
            msg = unicode(result)

        else:
            if status == 'decline':
                msg = _(u'Transaction was declined.  Reason: %s' %
                        result['declinetype'])
                failmsg = u'Transaction was declined.  Reason: %s' % result[
                    'declinetype']

            elif status == 'baddata':
                msg = _(u'Improperly formatted data. Offending fields: %s' %
                        result['offenders'])
                failmsg = u'Improperly formatted data. Offending fields: %s' % result[
                    'offenders']

            else:
                status = "error"
                msg = _(u'An error occurred: %s' % result['errortype'])
                failmsg = u'An error occurred: %s' % result['errortype']

            payment = self.record_failure(order=order,
                                          amount=amount,
                                          transaction_id="",
                                          reason_code=status,
                                          details=failmsg)

        return ProcessorResult(self.key, success, msg, payment=payment)
Example #4
0
    def authorize_payment(self, order=None, amount=None, testing=False):
        """
        Authorize a single payment.

        Returns: ProcessorResult
        """
        if order:
            self.prepare_data(order)
        else:
            order = self.order

        if order.paid_in_full:
            self.log_extra('%s is paid in full, no authorization attempted.',
                           order)
            result = ProcessorResult(self.key, True,
                                      _("No charge needed, paid in full."))
        else:
            self.log_extra('Authorizing payment of %s for %s', amount, order)

            data = self.get_charge_data(amount=amount)
            data['extras'] = [data['address'], data['ship_address'], 
                              data['customer_info'],]

            result = self.send_post(data=data, testing=testing,
                                    post_func=self.send_authorize_post,)

        return result
Example #5
0
    def capture_payment(self, testing=False, order=None, amount=None):
        """Process payments without an authorization step."""
        if order:
            self.prepare_data(order)
        else:
            order = self.order

        recurlist = self.get_recurring_charge_data()
        if recurlist:
            success, results = self.process_recurring_subscriptions(recurlist, testing)
            if not success:
                self.log_extra('recur payment failed, aborting the rest of the module')
                return results

        if order.paid_in_full:
            self.log_extra('%s is paid in full, no capture attempted.', order)
            results = ProcessorResult(self.key, True, _("No charge needed, paid in full."))
            self.record_payment()
        else:
            self.log_extra('Capturing payment for %s', order)

            standard = self.get_standard_charge_data(amount=amount)
            results = self.send_post(standard, testing)

        return results
Example #6
0
    def send_post(self, data, post_func, testing=False):
        """
        Execute the post to PayflowPro.

        Params:
        - data: the argument expected by `post_func`. Usually a dict which this
                function knows how to use
        - post_func: a function that takes `data` as argument, and sends the
                     actual request to the PayflowPro Gateway. It should return
                     a 3-tuple (responses, unconsumed_data, record_* function)
        - testing: if true, then don't record the payment

        Returns:
        - ProcessorResult
        """
        self.log_extra("About to send PayflowPro a request: %s",
                       data['log_string'])

        if 'amount' in data:
            amount = data['amount'].amt
        else:
            amount = self.order.balance

        responses, unconsumed_data, record_function = post_func(data)
        self._handle_unconsumed(unconsumed_data)
        self._log_responses(responses)

        response = responses[0]

        success = response.result == '0'
        transaction_id = response.pnref
        response_text = response.respmsg
        reason_code = response.result
        if success:
            # success!
            self.log.info("successful %s for order #%d", post_func.__name__,
                          self.order.id)
            if not testing:
                self.log_extra("Success, calling %s", record_function.__name__)
                payment = record_function(order=self.order,
                                          amount=amount,
                                          transaction_id=transaction_id,
                                          reason_code=reason_code)
        else:
            # failure =(
            self.log.info("failed %s for order #%d", post_func.__name__,
                          self.order.id)
            if not testing:
                payment = self.record_failure(amount=amount,
                                              transaction_id=transaction_id,
                                              reason_code=reason_code,
                                              details=response_text)

        self.log_extra("Returning success=%s, reason=%s, response_text=%s",
                       success, reason_code, response_text)

        return ProcessorResult(self.key,
                               success,
                               response_text,
                               payment=payment)
Example #7
0
    def capture_payment(self, testing=False, order=None, amount=None):
        """
        Process payments without an authorization step.
        """
        if order:
            self.prepare_data(order)
        else:
            order = self.order

        if order.paid_in_full:
            self.log_extra('%s is paid in full, no capture attempted.', order)
            result = ProcessorResult(self.key, True,
                                     _("No charge needed, "
                                       "paid in full."))
            self.record_payment()
        else:
            self.log_extra('Capturing payment for %s', order)

            data = self.get_charge_data(amount=amount)
            data['extras'] = [
                data['address'],
                data['ship_address'],
                data['customer_info'],
            ]
            result = self.send_post(
                data=data,
                post_func=self.send_sale_post,
                testing=testing,
            )

        return result
Example #8
0
    def capture_authorized_payment(self,
                                   authorization,
                                   testing=False,
                                   order=None,
                                   amount=None):
        """
        Capture a single payment
        """
        if order:
            self.prepare_data(order)
        else:
            order = self.order

        if order.authorized_remaining == Decimal('0.00'):
            self.log_extra('No remaining authorizations on %s', order)
            return ProcessorResult(self.key, True, _("Already complete"))

        self.log_extra('Capturing Authorization #%i for %s', authorization.id,
                       order)
        data = self.get_charge_data()
        data['authorization_id'] = authorization.transaction_id
        result = self.send_post(
            data=data,
            testing=testing,
            post_func=self.send_capture_post,
        )

        return result
Example #9
0
    def capture_payment(self, testing=False, order=None, amount=None):
        """
        Creates and sends XML representation of transaction to Cybersource
        """
        if not order:
            order = self.order

        if order.paid_in_full:
            self.log_extra('%s is paid in full, no capture attempted.', order)
            self.record_payment()
            return ProcessorResult(self.key, True,
                                   _("No charge needed, paid in full."))

        self.log_extra('Capturing payment for %s', order)

        if amount is None:
            amount = order.balance

        self.prepare_content(order, amount)

        invoice = "%s" % order.id
        failct = order.paymentfailures.count()
        if failct > 0:
            invoice = "%s_%i" % (invoice, failct)

        # XML format is very simple, using ElementTree for generation would be overkill
        t = loader.get_template('shop/checkout/cybersource/request.xml')
        c = Context({
            'config': self.configuration,
            'merchantReferenceCode': invoice,
            'billTo': self.bill_to,
            'purchaseTotals': self.purchase_totals,
            'card': self.card,
        })
        request = t.render(c)
        conn = urllib2.Request(url=self.connection, data=request)
        try:
            f = urllib2.urlopen(conn)
        except urllib2.HTTPError, e:
            # we probably didn't authenticate properly
            # make sure the 'v' in your account number is lowercase
            return ProcessorResult(self.key, False, 'Problem parsing results')
Example #10
0
    def capture_payment(self, testing=False, order=None, amount=None):
        """
        Check is always successful.
        """
        if not order:
            order = self.order

        # Check always results in a full balance until the check arrives.
        payment = self.record_payment(order=order, amount=0,
            transaction_id="CHECK", reason_code='0')

        return ProcessorResult(self.key, True, _('Success'), payment)
Example #11
0
    def authorize_payment(self, order=None, testing=False, amount=None):
        """
        Make an authorization for an order.  This payment will then be captured when the order
        is set marked 'shipped'.
        """
        if order == None:
            order = self.order

        if amount is None:
            amount = order.balance

        cc = order.credit_card
        if cc:
            ccn = cc.decryptedCC
            ccv = cc.ccv
            if ccn == '4222222222222':
                if ccv == '222':
                    self.log_extra('Bad CCV forced')
                    payment = self.record_failure(amount=amount,
                                                  transaction_id='2',
                                                  reason_code='2',
                                                  details='CCV error forced')
                    return ProcessorResult(self.key, False,
                                           _('Bad CCV - order declined'),
                                           payment)
                else:
                    self.log_extra(
                        'Setting a bad credit card number to force an error')
                    payment = self.record_failure(
                        amount=amount,
                        transaction_id='2',
                        reason_code='2',
                        details='Credit card number error forced')
                    return ProcessorResult(
                        self.key, False,
                        _('Bad credit card number - order declined'), payment)

        orderauth = self.record_authorization(amount=amount, reason_code="0")
        return ProcessorResult(self.key, True, _('Success'), orderauth)
Example #12
0
    def capture_payment(self, testing=False, order=None, amount=None):
        if not order:
            order = self.order

        if amount is None:
            amount = order.balance

        payment = self.record_payment(order=order,
                                      amount=amount,
                                      transaction_id="AUTO",
                                      reason_code='0')

        return ProcessorResult(self.key, True, _('Success'), payment)
Example #13
0
    def capture_authorized_payment(self, authorization, amount=None):
        """
        Given a prior authorization, capture remaining amount not yet captured.
        """
        if amount is None:
            amount = authorization.remaining()

        orderpayment = self.record_payment(amount=amount,
                                           reason_code="0",
                                           transaction_id="dummy",
                                           authorization=authorization)

        return ProcessorResult(self.key, True, _('Success'), orderpayment)
Example #14
0
    def capture_payment(self, testing=False, order=None, amount=None):
        """
        Process the transaction and return a ProcessorResponse
        """
        if not order:
            order = self.order

        if amount is None:
            amount = order.balance

        payment = None

        valid_gc = False
        if self.order.paid_in_full:
            success = True
            reason_code = "0"
            response_text = _("No balance to pay")
            self.record_payment()

        else:
            try:
                gc = GiftCertificate.objects.from_order(self.order)
                valid_gc = gc.valid

            except GiftCertificate.DoesNotExist:
                success = False
                reason_code = "1"
                response_text = _("No such Gift Certificate")

            if not valid_gc:
                success = False
                reason_code = "2"
                response_text = _("Bad Gift Certificate")

            else:
                gc.apply_to_order(self.order)
                payment = gc.orderpayment
                reason_code = "0"
                response_text = _("Success")
                success = True

                if not self.order.paid_in_full:
                    response_text = _(
                        "%s balance remains after gift certificate was applied"
                    ) % moneyfmt(self.order.balance)

        return ProcessorResult(self.key,
                               success,
                               response_text,
                               payment=payment)
    def capture_payment(self, testing=False, order=None, amount=None):
        if not order:
            order = self.order

        if amount is None:
            amount = order.balance

        payment = self.record_payment(order=order,
                                      amount=amount,
                                      transaction_id="%s-ORDER-#%s" %
                                      (self.method_name.upper(), order.pk),
                                      reason_code='0')

        return ProcessorResult(self.key, True, _('Success'), payment)
Example #16
0
    def capture_payment(self, testing=False, amount=None):
        """
        Process the transaction and return a ProcessorResult:

        Example:
        >>> from livesettings.functions import config_get_group
        >>> settings = config_get_group('PAYMENT_DUMMY')
        >>> from payment.modules.dummy.processor import PaymentProcessor
        >>> processor = PaymentProcessor(settings)
        # If using a normal payment module, data should be an Order object.
        >>> data = {}
        >>> processor.prepare_data(data)
        >>> processor.process()
        ProcessorResult: DUMMY [Success] Success
        """

        orderpayment = self.record_payment(amount=amount, reason_code="0")
        return ProcessorResult(self.key, True, _('Success'), orderpayment)
Example #17
0
    def capture_authorized_payment(self, authorization, testing=False, order=None, amount=None):
        """Capture a single payment"""
        if order:
            self.prepare_data(order)
        else:
            order = self.order

        if order.authorized_remaining == Decimal('0.00'):
            self.log_extra('No remaining authorizations on %s', order)
            return ProcessorResult(self.key, True, _("Already complete"))

        self.log_extra('Capturing Authorization #%i for %s', authorization.id, order)
        data = self.get_prior_auth_data(authorization, amount=amount)
        results = None
        if data:
            results = self.send_post(data, testing)

        return results
Example #18
0
    def authorize_payment(self, order=None, amount=None, testing=False):
        """Authorize a single payment.

        Returns: ProcessorResult
        """
        if order:
            self.prepare_data(order)
        else:
            order = self.order

        if order.paid_in_full:
            self.log_extra('%s is paid in full, no authorization attempted.', order)
            results = ProcessorResult(self.key, True, _("No charge needed, paid in full."))
        else:
            self.log_extra('Authorizing payment of %s for %s', amount, order)

            standard = self.get_standard_charge_data(authorize=True, amount=amount)
            results = self.send_post(standard, testing)

        return results
Example #19
0
    def send_post(self, data, testing=False, amount=None):
        """Execute the post to Authorize Net.

        Params:
        - data: dictionary as returned by get_standard_charge_data
        - testing: if true, then don't record the payment

        Returns:
        - ProcessorResult
        """
        self.log.info("About to send a request to authorize.net: %(connection)s\n%(logPostString)s", data)

        conn = urllib2.Request(url=data['connection'], data=data['postString'])
        try:
            f = urllib2.urlopen(conn)
            all_results = f.read()
            self.log_extra('Authorize response: %s', all_results)
        except urllib2.URLError, ue:
            self.log.error("error opening %s\n%s", data['connection'], ue)
            return ProcessorResult(self.key, False, _('Could not talk to Authorize.net gateway'))
Example #20
0
    def capture_payment(self, testing=False, order=None, amount=None):
        """Execute the post to Sage Pay VSP DIRECT"""
        if not order:
            order = self.order

        if order.paid_in_full:
            self.log_extra('%s is paid in full, no capture attempted.', order)
            self.record_payment()
            return ProcessorResult(self.key, True,
                                   _("No charge needed, paid in full."))

        self.log_extra('Capturing payment for %s', order)

        if amount is None:
            amount = order.balance

        self.prepare_post(order, amount)

        if self.valid:
            if self.settings.SKIP_POST.value:
                self.log.info(
                    "TESTING MODE - Skipping post to server.  Would have posted %s?%s",
                    self.url, self.postString)
                payment = self.record_payment(order=order,
                                              amount=amount,
                                              transaction_id="TESTING",
                                              reason_code='0')

                return ProcessorResult(self.key,
                                       True,
                                       _('TESTING MODE'),
                                       payment=payment)

            else:
                self.log_extra("About to post to server: %s?%s", self.url,
                               self.postString)
                conn = urllib.request.Request(self.url, data=self.postString)
                try:
                    f = urllib.request.urlopen(conn)
                    result = f.read()
                    self.log_extra('Process: url=%s\nPacket=%s\nResult=%s',
                                   self.url, self.packet, result)

                except urllib.error.URLError as ue:
                    self.log.error("error opening %s\n%s", self.url, ue)
                    return ProcessorResult(
                        self.key, False, 'Could not talk to Sage Pay gateway')

                try:
                    self.response = dict(
                        [row.split('=', 1) for row in result.splitlines()])
                    status = self.response['Status']
                    success = (status == 'OK')
                    detail = self.response['StatusDetail']

                except KeyError as e:
                    self.log.info('Error submitting payment: %s', e)
                    payment = self.record_failure(
                        order=order,
                        amount=amount,
                        transaction_id="",
                        reason_code="error",
                        details='Invalid response from payment gateway')

                    return ProcessorResult(
                        self.key, False,
                        _('Invalid response from payment gateway'))

                payment = None
                transaction_id = ""
                if success:
                    vpstxid = self.response.get('VPSTxID', '')
                    txauthno = self.response.get('TxAuthNo', '')
                    transaction_id = "%s,%s" % (vpstxid, txauthno)
                    self.log.info('Success on order #%i, recording payment',
                                  self.order.id)
                    payment = self.record_payment(
                        order=order,
                        amount=amount,
                        transaction_id=transaction_id,
                        reason_code=status)

                else:
                    payment = self.record_failure(
                        order=order,
                        amount=amount,
                        transaction_id=transaction_id,
                        reason_code=status,
                        details=detail)

                return ProcessorResult(self.key,
                                       success,
                                       detail,
                                       payment=payment)
        else:
            return ProcessorResult(self.key, False,
                                   _('Error processing payment.'))
Example #21
0
class PaymentProcessor(BasePaymentProcessor):
    """
    Cybersource payment processing module
    You must have an account with Cybersource in order to use this module

    """
    def __init__(self, settings):
        super(PaymentProcessor, self).__init__('cybersource', settings)
        self.contents = ''
        if settings.LIVE.value:
            self.testflag = 'FALSE'
            self.connection = settings.CONNECTION.value
        else:
            self.testflag = 'TRUE'
            self.connection = settings.CONNECTION_TEST.value

        self.configuration = {
            'merchantID' : settings.MERCHANT_ID.value,
            'password' : settings.TRANKEY.value,
            }

    def prepare_content(self, order, amount):
        self.bill_to = {
            'firstName' : order.bill_first_name,
            'lastName' : order.bill_last_name,
            'street1': order.full_bill_street,
            'city': order.bill_city,
            'state' : order.bill_state,
            'postalCode' : order.bill_postal_code,
            'country': order.bill_country,
            'email' : order.contact.email,
            'phoneNumber' : order.contact.primary_phone,
            # Can add additional info here if you want to but it's not required
            }
        exp = order.credit_card.expirationDate.split('/')
        self.card = {
            'accountNumber' : order.credit_card.decryptedCC,
            'expirationMonth' : exp[0],
            'expirationYear' : exp[1],
            'cvNumber' : order.credit_card.ccv
            }
        currency = self.settings.CURRENCY_CODE.value
        currency = currency.replace("_", "")
        self.purchase_totals = {
            'currency' : currency,
            'grandTotalAmount' : trunc_decimal(amount, 2),
        }

    def capture_payment(self, testing=False, order=None, amount=None):
        """
        Creates and sends XML representation of transaction to Cybersource
        """
        if not order:
            order = self.order

        if order.paid_in_full:
            self.log_extra('%s is paid in full, no capture attempted.', order)
            self.record_payment()
            return ProcessorResult(self.key, True, _("No charge needed, paid in full."))

        self.log_extra('Capturing payment for %s', order)

        if amount is None:
            amount = order.balance

        self.prepare_content(order, amount)

        invoice = "%s" % order.id
        failct = order.paymentfailures.count()
        if failct > 0:
            invoice = "%s_%i" % (invoice, failct)

        # XML format is very simple, using ElementTree for generation would be overkill
        t = loader.get_template('shop/checkout/cybersource/request.xml')
        c = Context({
            'config' : self.configuration,
            'merchantReferenceCode' : invoice,
            'billTo' : self.bill_to,
            'purchaseTotals' : self.purchase_totals,
            'card' : self.card,
        })
        request = t.render(c)
        conn = urllib2.Request(url=self.connection, data=request)
        try:
            f = urllib2.urlopen(conn)
        except urllib2.HTTPError, e:
            # we probably didn't authenticate properly
            # make sure the 'v' in your account number is lowercase
            return ProcessorResult(self.key, False, 'Problem parsing results')

        f = urllib2.urlopen(conn)
        all_results = f.read()
        tree = fromstring(all_results)
        parsed_results = tree.getiterator('{urn:schemas-cybersource-com:transaction-data-1.26}reasonCode')
        try:
            reason_code = parsed_results[0].text
        except KeyError:
            return ProcessorResult(self.key, False, 'Problem parsing results')

        response_text = CYBERSOURCE_RESPONSES.get(reason_code, 'Unknown Failure')

        if reason_code == '100':
            payment = self.record_payment(order=order, amount=amount,
                transaction_id="", reason_code=reason_code)
            return ProcessorResult(self.key, True, response_text, payment=payment)
        else:
            payment = self.record_failure(order=order, amount=amount,
                transaction_id="", reason_code=reason_code,
                details=response_text)

            return ProcessorResult(self.key, False, response_text)
Example #22
0
    def capture_payment(self, testing=False, order=None, amount=None):
        """Process payments without an authorization step."""
        if braintree_wrapper_server:
            transaction_sale = braintree_wrapper_server._sale_transaction
        else:
            braintree_settings = config_get_group('PAYMENT_SATCHMO_BRAINTREE')

            # Configure Braintree
            Configuration.configure(
                Environment.Production
                if getattr(django_settings, 'IS_PROD', False) else
                Environment.Sandbox, braintree_settings.MERCHANT_ID.value,
                braintree_settings.PUBLIC_KEY.value,
                braintree_settings.PRIVATE_KEY.value)

            transaction_sale = Transaction.sale

        if order:
            self.prepare_data(order)
        else:
            order = self.order

        if order.paid_in_full:
            self.log_extra('%s is paid in full, no capture attempted.', order)
            results = ProcessorResult(self.key, True,
                                      _("No charge needed, paid in full."))
            self.record_payment()
        else:
            self.log_extra('Capturing payment for %s', order)
            amount = order.balance
            if braintree_wrapper_server:
                data = {}
            else:
                data = {
                    "amount": amount,
                    # "order_id": "123",
                    "credit_card": {
                        "number": order.credit_card.decryptedCC,
                        "expiration_date":
                        order.credit_card.expirationDate,  # 05/2012 ?
                        "cvv": order.credit_card.ccv
                    },
                    "customer": {
                        "first_name": order.contact.first_name,
                        "last_name": order.contact.last_name,
                    },
                    "billing": {
                        "first_name": order.contact.first_name,
                        "last_name": order.contact.last_name,
                        "street_address": order.full_bill_street,
                        "locality": order.bill_city,
                        "region": order.bill_state,
                        "postal_code": order.bill_postal_code,
                    },
                    "options": {
                        "submit_for_settlement": True
                    }
                }
            signals.satcho_braintree_order_validate.send(sender=self,
                                                         data=data,
                                                         order=order)

            result = transaction_sale(data)

            if result.is_success:
                payment = self.record_authorization(
                    order=order,
                    amount=amount,
                    transaction_id=result.transaction.id)
                response_text = 'Success'
            else:
                response_text = ''
                for error in result.errors.deep_errors:
                    response_text += '%s ' % error.message
                payment = self.record_failure(amount=amount)

            return ProcessorResult(self.key,
                                   result.is_success,
                                   response_text,
                                   payment=payment)
            # standard = self.get_standard_charge_data(amount=amount)
            # results = self.send_post(standard, testing)

        return results
Example #23
0
                payment = None
                transaction_id = ""
                if success:
                    vpstxid = self.response.get('VPSTxID', '')
                    txauthno = self.response.get('TxAuthNo', '')
                    transaction_id = "%s,%s" % (vpstxid, txauthno)
                    self.log.info('Success on order #%i, recording payment',
                                  self.order.id)
                    payment = self.record_payment(
                        order=order,
                        amount=amount,
                        transaction_id=transaction_id,
                        reason_code=status)

                else:
                    payment = self.record_failure(
                        order=order,
                        amount=amount,
                        transaction_id=transaction_id,
                        reason_code=status,
                        details=detail)

                return ProcessorResult(self.key,
                                       success,
                                       detail,
                                       payment=payment)
        else:
            return ProcessorResult(self.key, False,
                                   _('Error processing payment.'))
Example #24
0
                    transaction_id=transaction_id, reason_code=reason_code)
            else:
                if amount <= 0:
                    self.log_extra('Success, recording refund')
                else:
                    self.log_extra('Success, recording payment')
                authorization = data.get('authorization', None)
                payment = self.record_payment(order=self.order, amount=amount,
                    transaction_id=transaction_id, reason_code=reason_code, authorization=authorization)

        elif not testing:
            payment = self.record_failure(amount=amount, transaction_id=transaction_id,
                reason_code=reason_code, details=response_text)

        self.log_extra("Returning success=%s, reason=%s, response_text=%s", success, reason_code, response_text)
        return ProcessorResult(self.key, success, response_text, payment=payment)

if __name__ == "__main__":
    """
    This is for testing - enabling you to run from the command line and make
    sure everything is ok
    """
    import os
    from livesettings.functions import config_get_group

    # Set up some dummy classes to mimic classes being passed through Satchmo
    class testContact(object):
        pass
    class testCC(object):
        pass
    class testOrder(object):
Example #25
0
    def capture_payment(self, request, testing=False, order=None, amount=None):
        """
        Process the transaction and return a ProcessorResponse
        """

        if not order:
            order = self.order

        if amount is None:
            amount = order.balance

        payment = None

        points = int(request.POST.get('points', None))

        if self.order.paid_in_full:
            success = True
            reason_code = "0"
            response_text = _("No balance to pay")
            self.record_payment()

        else:
            #contact = Contact.objects.from_request(request)
            if points:
                reward, created = Reward.objects.get_or_create(
                    contact=order.contact)

                if points > reward.points:
                    success = False
                    reason_code = "0"
                    response_text = _(
                        "You Do not have that many reward points.")
                    return ProcessorResult(self.key,
                                           success,
                                           response_text,
                                           payment=payment)

                point_modifier = config_value('PAYMENT_REWARD', 'POINTS_VALUE')
                point_value = point_modifier * points

                if point_value > order.balance:
                    success = False
                    reason_code = "0"
                    response_text = _(
                        "You are trying to use too many points for this order."
                    )
                    return ProcessorResult(self.key,
                                           success,
                                           response_text,
                                           payment=payment)
                else:
                    points_used = points
                    point_value_used = point_value

                    orderpayment = self.record_payment(order=order,
                                                       amount=point_value_used)
                    reward_item = RewardItem.objects.add_order_payment(
                        reward, order, orderpayment, points_used,
                        point_value_used)

                    reason_code = "0"
                    response_text = _("Success")
                    success = True

                if not self.order.paid_in_full:
                    url = reverse('satchmo_balance_remaining')
                    response_text = _("%s balance remains after using points"
                                      ) % moneyfmt(self.order.balance)
            else:
                success = False
                reason_code = "0"
                response_text = _(
                    "Please enter the amount of reward points you want to redeem"
                )

        return ProcessorResult(self.key,
                               success,
                               response_text,
                               payment=payment)
Example #26
0
    def send_post(self, data, testing=False, amount=None):
        """Execute the post to Authorize Net.

        Params:
        - data: dictionary as returned by get_standard_charge_data
        - testing: if true, then don't record the payment

        Returns:
        - ProcessorResult
        """
        self.log.info(
            "About to send a request to authorize.net: %(connection)s\n%(logPostString)s",
            data)
        if sys.version_info >= (3, ):
            post_data = data['postString'].encode("utf-8")
        else:
            post_data = data['postString']
        conn = urllib.request.Request(url=data['connection'], data=post_data)
        try:
            f = urllib.request.urlopen(conn)
            all_results = f.read()
            if isinstance(all_results, bytes):
                all_results = all_results.decode("utf-8")
            self.log_extra('Authorize response: %s', all_results)
        except urllib.error.URLError as ue:
            self.log.error("error opening %s\n%s", data['connection'], ue)
            return ProcessorResult(
                self.key, False, _('Could not talk to Authorize.net gateway'))

        parsed_results = all_results.split(
            data['configuration']['x_delim_char'])
        response_code = parsed_results[0]
        reason_code = parsed_results[1]
        response_text = parsed_results[3]
        transaction_id = parsed_results[6]
        success = response_code == '1'
        if amount is None:
            amount = data['amount']

        payment = None
        if success and not testing:
            if data.get('authorize_only', False):
                self.log_extra('Success, recording authorization')
                payment = self.record_authorization(
                    order=self.order,
                    amount=amount,
                    transaction_id=transaction_id,
                    reason_code=reason_code)
            else:
                if amount <= 0:
                    self.log_extra('Success, recording refund')
                else:
                    self.log_extra('Success, recording payment')
                authorization = data.get('authorization', None)
                payment = self.record_payment(order=self.order,
                                              amount=amount,
                                              transaction_id=transaction_id,
                                              reason_code=reason_code,
                                              authorization=authorization)

        elif not testing:
            payment = self.record_failure(amount=amount,
                                          transaction_id=transaction_id,
                                          reason_code=reason_code,
                                          details=response_text)

        self.log_extra("Returning success=%s, reason=%s, response_text=%s",
                       success, reason_code, response_text)
        return ProcessorResult(self.key,
                               success,
                               response_text,
                               payment=payment)
Example #27
0
    def capture_payment(self, testing=False, order=None, amount=None):
        """
        Creates and sends XML representation of transaction to Cybersource
        """
        if not order:
            order = self.order

        if order.paid_in_full:
            self.log_extra('%s is paid in full, no capture attempted.', order)
            self.record_payment()
            return ProcessorResult(self.key, True,
                                   _("No charge needed, paid in full."))

        self.log_extra('Capturing payment for %s', order)

        if amount is None:
            amount = order.balance

        self.prepare_content(order, amount)

        invoice = "%s" % order.id
        failct = order.paymentfailures.count()
        if failct > 0:
            invoice = "%s_%i" % (invoice, failct)

        # XML format is very simple, using ElementTree for generation would be overkill
        t = loader.get_template('shop/checkout/cybersource/request.xml')
        c = {
            'config': self.configuration,
            'merchantReferenceCode': invoice,
            'billTo': self.bill_to,
            'purchaseTotals': self.purchase_totals,
            'card': self.card,
        }
        request = t.render(c)
        conn = urllib.request.Request(url=self.connection, data=request)
        try:
            f = urllib.request.urlopen(conn)
        except urllib.error.HTTPError as e:
            # we probably didn't authenticate properly
            # make sure the 'v' in your account number is lowercase
            return ProcessorResult(self.key, False, 'Problem parsing results')

        f = urllib.request.urlopen(conn)
        all_results = f.read()
        tree = fromstring(all_results)
        parsed_results = tree.getiterator(
            '{urn:schemas-cybersource-com:transaction-data-1.26}reasonCode')
        try:
            reason_code = parsed_results[0].text
        except KeyError:
            return ProcessorResult(self.key, False, 'Problem parsing results')

        response_text = CYBERSOURCE_RESPONSES.get(reason_code,
                                                  'Unknown Failure')

        if reason_code == '100':
            payment = self.record_payment(order=order,
                                          amount=amount,
                                          transaction_id="",
                                          reason_code=reason_code)
            return ProcessorResult(self.key,
                                   True,
                                   response_text,
                                   payment=payment)
        else:
            payment = self.record_failure(order=order,
                                          amount=amount,
                                          transaction_id="",
                                          reason_code=reason_code,
                                          details=response_text)

            return ProcessorResult(self.key, False, response_text)
Example #28
0
 def process(self, *args, **kwargs):
     if self.order.paid_in_full:
         return ProcessorResult('FREE', True, _('Success'))
     else:
         return ProcessorResult('FREE', False, _('This order does not have a zero balance'))
Example #29
0
 def release_authorized_payment(self, order=None, auth=None, testing=False):
     """Release a previously authorized payment."""
     auth.complete = True
     auth.save()
     return ProcessorResult(self.key, True, _('Success'))