Process a payment response.
330813
def process_response(data):
    """"""
    # We check if the signature is valid. If not return
    if not is_signature_valid(data):
        logger.warning(
            "Django-Payzen : Response signature detected as invalid",
            extra={"stack": True}
        )
        return None

    from . import forms
    from . import models

    # The signature is valid
    vads_trans_id = data.get("vads_trans_id")
    vads_trans_date = data.get("vads_trans_date")
    vads_site_id = data.get("vads_site_id")
    try:
        instance = models.PaymentResponse.objects.get(
            vads_trans_id=vads_trans_id,
            vads_trans_date=vads_trans_date,
            vads_site_id=vads_site_id)
        form = forms.PaymentResponseForm(data, instance=instance)
    except models.PaymentResponse.DoesNotExist:
        form = forms.PaymentResponseForm(data)
    if form.is_valid():
        response = form.save()
        logger.info("Django-Payzen : Transaction {} response received !"
                    .format(response.vads_trans_id))
    else:
        logger.error("Django-Payzen : Response could not be saved - {} {}"
                     .format(form.errors, data),
                     extra={"stack": True})
        response = None
    return response
561019
def process_response(self, request, response, resource, req_succeeded):
        """"""
        self.logger.info(self._generate_combined_log(request, response))
939456
def process_response(self, response):
        """"""
        self.response_headers = [(k, v) for k, v in sorted(response.headers.items())]
730981
def processPointOfSalePayment(request):
    '''
    
    '''
    print('Request data is: %s' % request.GET)

    # iOS transactions put all response information in the data key:
    data = json.loads(request.GET.get('data','{}'))
    if data:
        status = data.get('status')
        errorCode = data.get('error_code')
        errorDescription = errorCode

        try:
            stateData = data.get('state','')
            if stateData:
                metadata = json.loads(b64decode(unquote(stateData).encode()).decode())
            else:
                metadata = {}
        except (TypeError, ValueError, binascii.Error):
            logger.error('Invalid metadata passed from Square app.')
            messages.error(
                request,
                format_html(
                    '<p>{}</p><ul><li><strong>CODE:</strong> {}</li><li><strong>DESCRIPTION:</strong> {}</li></ul>',
                    str(_('ERROR: Error with Square point of sale transaction attempt.')),
                    str(_('Invalid metadata passed from Square app.')),
                )
            )
            return HttpResponseRedirect(reverse('showRegSummary'))

        # This is the normal transaction identifier, which will be stored in the
        # database as a SquarePaymentRecord
        serverTransId = data.get('transaction_id')

        # This is the only identifier passed for non-card transactions.
        clientTransId = data.get('client_transaction_id')
    else:
        # Android transactions use this GET response syntax
        errorCode = request.GET.get('com.squareup.pos.ERROR_CODE')
        errorDescription = request.GET.get('com.squareup.pos.ERROR_DESCRIPTION')
        status = 'ok' if not errorCode else 'error'

        # This is the normal transaction identifier, which will be stored in the
        # database as a SquarePaymentRecord
        serverTransId = request.GET.get('com.squareup.pos.SERVER_TRANSACTION_ID')

        # This is the only identifier passed for non-card transactions.
        clientTransId = request.GET.get('com.squareup.pos.CLIENT_TRANSACTION_ID')

        # Load the metadata, which includes the registration or invoice ids
        try:
            stateData = request.GET.get('com.squareup.pos.REQUEST_METADATA','')
            if stateData:
                metadata = json.loads(b64decode(unquote(stateData).encode()).decode())
            else:
                metadata = {}

        except (TypeError, ValueError, binascii.Error):
            logger.error('Invalid metadata passed from Square app.')
            messages.error(
                request,
                format_html(
                    '<p>{}</p><ul><li><strong>CODE:</strong> {}</li><li><strong>DESCRIPTION:</strong> {}</li></ul>',
                    str(_('ERROR: Error with Square point of sale transaction attempt.')),
                    str(_('Invalid metadata passed from Square app.')),
                )
            )
            return HttpResponseRedirect(reverse('showRegSummary'))

    # Other things that can be passed in the metadata
    sourceUrl = metadata.get('sourceUrl',reverse('showRegSummary'))
    successUrl = metadata.get('successUrl',reverse('registration'))
    submissionUserId = metadata.get('userId', getattr(getattr(request,'user',None),'id',None))
    transactionType = metadata.get('transaction_type')
    taxable = metadata.get('taxable', False)
    addSessionInfo = metadata.get('addSessionInfo',False)
    customerEmail = metadata.get('customerEmail')

    if errorCode or status != 'ok':
        # Return the user to their original page with the error message displayed.
        logger.error('Error with Square point of sale transaction attempt.  CODE: %s; DESCRIPTION: %s' % (errorCode, errorDescription))
        messages.error(
            request,
            format_html(
                '<p>{}</p><ul><li><strong>CODE:</strong> {}</li><li><strong>DESCRIPTION:</strong> {}</li></ul>',
                str(_('ERROR: Error with Square point of sale transaction attempt.')), errorCode, errorDescription
            )
        )
        return HttpResponseRedirect(sourceUrl)

    api_instance = TransactionsApi()
    api_instance.api_client.configuration.access_token = getattr(settings,'SQUARE_ACCESS_TOKEN','')
    location_id = getattr(settings,'SQUARE_LOCATION_ID','')

    if serverTransId:
        try:
            api_response = api_instance.retrieve_transaction(transaction_id=serverTransId,location_id=location_id)
        except ApiException:
            logger.error('Unable to find Square transaction by server ID.')
            messages.error(request,_('ERROR: Unable to find Square transaction by server ID.'))
            return HttpResponseRedirect(sourceUrl)
        if api_response.errors:
            logger.error('Unable to find Square transaction by server ID: %s' % api_response.errors)
            messages.error(request,str(_('ERROR: Unable to find Square transaction by server ID:')) + api_response.errors)
            return HttpResponseRedirect(sourceUrl)
        transaction = api_response.transaction
    elif clientTransId:
        # Try to find the transaction in the 50 most recent transactions
        try:
            api_response = api_instance.list_transactions(location_id=location_id)
        except ApiException:
            logger.error('Unable to find Square transaction by client ID.')
            messages.error(request,_('ERROR: Unable to find Square transaction by client ID.'))
            return HttpResponseRedirect(sourceUrl)
        if api_response.errors:
            logger.error('Unable to find Square transaction by client ID: %s' % api_response.errors)
            messages.error(request,str(_('ERROR: Unable to find Square transaction by client ID:')) + api_response.errors)
            return HttpResponseRedirect(sourceUrl)
        transactions_list = [x for x in api_response.transactions if x.client_id == clientTransId]
        if len(transactions_list) == 1:
            transaction = transactions_list[0]
        else:
            logger.error('Returned client transaction ID not found.')
            messages.error(request,_('ERROR: Returned client transaction ID not found.'))
            return HttpResponseRedirect(sourceUrl)
    else:
        logger.error('An unknown error has occurred with Square point of sale transaction attempt.')
        messages.error(request,_('ERROR: An unknown error has occurred with Square point of sale transaction attempt.'))
        return HttpResponseRedirect(sourceUrl)

    # Get total information from the transaction for handling invoice.
    this_total = sum([x.amount_money.amount / 100 for x in transaction.tenders or []]) - \
        sum([x.amount_money.amount / 100 for x in transaction.refunds or []])

    # Parse if a specific submission user is indicated
    submissionUser = None
    if submissionUserId:
        try:
            submissionUser = User.objects.get(id=int(submissionUserId))
        except (ValueError, ObjectDoesNotExist):
            logger.warning('Invalid user passed, submissionUser will not be recorded.')

    if 'registration' in metadata.keys():
        try:
            tr_id = int(metadata.get('registration'))
            tr = TemporaryRegistration.objects.get(id=tr_id)
        except (ValueError, TypeError, ObjectDoesNotExist):
            logger.error('Invalid registration ID passed: %s' % metadata.get('registration'))
            messages.error(
                request,
                str(_('ERROR: Invalid registration ID passed')) + ': %s' % metadata.get('registration')
            )
            return HttpResponseRedirect(sourceUrl)

        tr.expirationDate = timezone.now() + timedelta(minutes=getConstant('registration__sessionExpiryMinutes'))
        tr.save()
        this_invoice = Invoice.get_or_create_from_registration(tr, submissionUser=submissionUser)
        this_description = _('Registration Payment: #%s' % tr_id)

    elif 'invoice' in metadata.keys():
        try:
            this_invoice = Invoice.objects.get(id=int(metadata.get('invoice')))
            this_description = _('Invoice Payment: %s' % this_invoice.id)

        except (ValueError, TypeError, ObjectDoesNotExist):
            logger.error('Invalid invoice ID passed: %s' % metadata.get('invoice'))
            messages.error(
                request,
                str(_('ERROR: Invalid invoice ID passed')) + ': %s' % metadata.get('invoice')
            )
            return HttpResponseRedirect(sourceUrl)
    else:
        # Gift certificates automatically get a nicer invoice description
        if transactionType == 'Gift Certificate':
            this_description = _('Gift Certificate Purchase')
        else:
            this_description = transactionType
        this_invoice = Invoice.create_from_item(
            this_total,
            this_description,
            submissionUser=submissionUser,
            calculate_taxes=(taxable is not False),
            transactionType=transactionType,
        )

    paymentRecord, created = SquarePaymentRecord.objects.get_or_create(
        transactionId=transaction.id,
        locationId=transaction.location_id,
        defaults={'invoice': this_invoice,}
    )
    if created:
        # We process the payment now, and enqueue the job to retrieve the
        # transaction again once fees have been calculated by Square
        this_invoice.processPayment(
            amount=this_total,
            fees=0,
            paidOnline=True,
            methodName='Square Point of Sale',
            methodTxn=transaction.id,
            notify=customerEmail,
        )
    updateSquareFees.schedule(args=(paymentRecord,), delay=60)

    if addSessionInfo:
        paymentSession = request.session.get(INVOICE_VALIDATION_STR, {})

        paymentSession.update({
            'invoiceID': str(this_invoice.id),
            'amount': this_total,
            'successUrl': successUrl,
        })
        request.session[INVOICE_VALIDATION_STR] = paymentSession

    return HttpResponseRedirect(successUrl)
1147248
public function processAction()
    {
        try {
            /** @var \OxidEsales\PayPalModule\Core\Request $request */
            $request = oxNew(\OxidEsales\PayPalModule\Core\Request::class);
            $action = $request->getRequestParameter('action');

            $order = $this->getEditObject();

            /** @var \OxidEsales\PayPalModule\Model\Action\OrderActionFactory $actionFactory */
            $actionFactory = oxNew(\OxidEsales\PayPalModule\Model\Action\OrderActionFactory::class, $request, $order);
            $action = $actionFactory->createAction($action);

            $action->process();
        } catch (\OxidEsales\Eshop\Core\Exception\StandardException $exception) {
            $this->_aViewData["error"] = $exception->getMessage();
        }
    }
607994
def process_lipisha_payment(request):
    """"""
    log.debug(request.POST)
    schema = LipishaInitiateSchema
    api_type = request.POST.get('api_type')
    if api_type == TYPE_ACKNOWLEDGE:
        schema = LipishaAcknowledgeSchema
    form = Form(request, schema())
    transaction_status_code = STATUS_SUCCESS
    transaction_status = 'Processed'
    transaction_status_description = 'Processed'
    if form.validate():
        if api_type == TYPE_INITIATE:
            # Process new payment
            pass
        elif api_type == TYPE_ACKNOWLEDGE:
            if form.data.get('transaction_status_code') == STATUS_SUCCESS:
                # Process successful accknowledgement
                pass
            else:
                log.error('Invalid payment acknowledgement')
                log.error(request.POST)
    else:
        log.error("Error while processing payment")
        for error in form.all_errors():
            log.error(error)
        transaction_status_code = STATUS_INITIATE_FAILURE
        transaction_status = 'Error'
        transaction_status_description = 'Error while processing'
    if api_type == TYPE_INITIATE:
        data = request.POST
        return dict(
            api_key=LIPISHA_API_KEY,
            api_signature=LIPISHA_API_SIGNATURE,
            api_version=data.get('api_version'),
            api_type=TYPE_RECEIPT,
            transaction_reference=data.get('transaction_reference'),
            transaction_status_code=transaction_status_code,
            transaction_status=transaction_status,
            transaction_status_description=transaction_status_description,
        )
    return {}
773931
protected function processResponse()
    {
        if ($this->response->isSuccessful()) {
            $this->updateOrderStatus();
            $this->addTransaction();
            $this->redirectSuccess();
        } else if ($this->response->isRedirect()) {
            $this->response->redirect();
        } else {
            $this->controller->redirect('', $this->response->getMessage(), 'warning', true);
        }
    }
81726
public void processResponse(ResponseEvent response) {
    ClientTransaction trans = response.getClientTransaction();
    if (trans == null) {
      return;
    }

    SipTransaction sip_trans = null;

    synchronized (respTransactions) {
      sip_trans = (SipTransaction) respTransactions.get(trans);
    }

    if (sip_trans == null) {
      return;
    }

    if (response.getResponse().getStatusCode() > 199) {
      synchronized (respTransactions) {
        respTransactions.remove(trans);
      }
    }

    // check for listener handling
    MessageListener listener = sip_trans.getClientListener();
    if (listener != null) {
      listener.processEvent(response);
      return;
    }

    // if no listener, use the default blocking mechanism
    synchronized (sip_trans.getBlock()) {
      sip_trans.getEvents().addLast(response);
      sip_trans.getBlock().notifyEvent();
    }
  }
1177547
def init(self, request, paypal_request, paypal_response):
        """"""
        if request is not None:
            from paypal.pro.helpers import strip_ip_port
            self.ipaddress = strip_ip_port(request.META.get('REMOTE_ADDR', ''))
            if (hasattr(request, "user") and request.user.is_authenticated):
                self.user = request.user
        else:
            self.ipaddress = ''

        # No storing credit card info.
        query_data = dict((k, v) for k, v in paypal_request.items() if k not in self.RESTRICTED_FIELDS)
        self.query = urlencode(query_data)
        self.response = urlencode(paypal_response)

        # Was there a flag on the play?
        ack = paypal_response.get('ack', False)
        if ack != "Success":
            if ack == "SuccessWithWarning":
                warn_untested()
                self.flag_info = paypal_response.get('l_longmessage0', '')
            else:
                self.set_flag(paypal_response.get('l_longmessage0', ''), paypal_response.get('l_errorcode', ''))
1030120
def process_request(self, request_object):
        """"""

        identifier = request_object.identifier

        # Look for the object by its ID and return it
        resource = request_object.entity_cls.get(identifier)
        return ResponseSuccess(Status.SUCCESS, resource)
1222580
def process_response(self, request, response):
        
        if not self.should_cache(request, response):
            # We don't need to update the cache, just return
            return response 

        response = self.patch_headers(response)
        self.set_cache(request, response)

        return response
1128425
def __ProcessResponse(self, response):
        """"""
        if response.status_code not in self._ACCEPTABLE_STATUSES:
            # We distinguish errors that mean we made a mistake in setting
            # up the transfer versus something we should attempt again.
            if response.status_code in (http_client.FORBIDDEN,
                                        http_client.NOT_FOUND):
                raise exceptions.HttpError.FromResponse(response)
            else:
                raise exceptions.TransferRetryError(response.content)
        if response.status_code in (http_client.OK,
                                    http_client.PARTIAL_CONTENT):
            try:
                self.stream.write(six.ensure_binary(response.content))
            except TypeError:
                self.stream.write(six.ensure_text(response.content))
            self.__progress += response.length
            if response.info and 'content-encoding' in response.info:
                # TODO(craigcitro): Handle the case where this changes over a
                # download.
                self.__encoding = response.info['content-encoding']
        elif response.status_code == http_client.NO_CONTENT:
            # It's important to write something to the stream for the case
            # of a 0-byte download to a file, as otherwise python won't
            # create the file.
            self.stream.write('')
        return response
1106722
def process_request(self, request, response):
        """"""
        self.logger.info('Requested: {0} {1} {2}'.format(request.method, request.relative_uri, request.content_type))
286331
protected function finishPurchase()
    {
        if ($this->response->isSuccessful()) {
            $this->updateOrderStatus();
            $this->addTransaction();
            $this->redirectSuccess();
        } else if ($this->response->isRedirect()) {
            $this->response->redirect();
        } else {
            $this->redirectError();
        }
    }
718804
protected function _processResponse()
    {
        $this->_factory
            ->getNewCancelProcessResponse($this->_response, $this->_order)
            ->process();
        return $this;
    }
570252
def process_response(response)
      response = create_hash response
      if response['status'].nil?
        raise Hoiio::ServerError
      elsif STATUS_SUCCESS != response['status']
        raise Hoiio::ResponseError.new response['status'], response['status']
      end
      response
    end
826755
def process_response(self, request, response):
        
        if self._is_enabled():
            log_prefix = self._log_prefix(u"After", request)
            new_memory_data = self._memory_data(log_prefix)

            log_prefix = self._log_prefix(u"Diff", request)
            cached_memory_data_response = self._cache.get_cached_response(self.memory_data_key)
            old_memory_data = cached_memory_data_response.get_value_or_default(None)
            self._log_diff_memory_data(log_prefix, new_memory_data, old_memory_data)
        return response