docs: def processSquarePayment(request):
      '''
      This view handles the charging of approved Square Checkout payments.
  
      All Checkout payments must either be associated with a pre-existing Invoice
      or a registration, or they must have an amount and type passed in the post data
      (such as gift certificate payment requests).
      '''
      logger.info('Received request for Square Checkout payment.')
  
      nonce_id = request.POST.get('nonce')
      invoice_id = request.POST.get('invoice_id')
      tr_id = request.POST.get('reg_id')
      amount = request.POST.get('amount')
      submissionUserId = request.POST.get('user_id')
      transactionType = request.POST.get('transaction_type')
      taxable = request.POST.get('taxable', False)
      sourceUrl = request.POST.get('sourceUrl', reverse('showRegSummary'))
      addSessionInfo = request.POST.get('addSessionInfo',False)
      successUrl = request.POST.get('successUrl',reverse('registration'))
      customerEmail = request.POST.get('customerEmail')
  
      # If a specific amount to pay has been passed, then allow payment
      # of that amount.
      if amount:
          try:
              amount = float(amount)
          except ValueError:
              logger.error('Invalid amount passed')
              messages.error(
                  request,
                  format_html(
                      '<p>{}</p><ul><li>{}</li></ul>',
                      str(_('ERROR: Error with Square checkout transaction attempt.')),
                      str(_('Invalid amount passed.'))
                  )
              )
              return HttpResponseRedirect(sourceUrl)
  
      # 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.')
  
      try:
          # Invoice transactions are usually payment on an existing invoice.
          if invoice_id:
              this_invoice = Invoice.objects.get(id=invoice_id)
              this_description = _('Invoice Payment: %s' % this_invoice.id)
              if not amount:
                  amount = this_invoice.outstandingBalance
          # This is typical of payment at the time of registration
          elif tr_id:
              tr = TemporaryRegistration.objects.get(id=int(tr_id))
              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)
              if not amount:
                  amount = this_invoice.outstandingBalance
          # All other transactions require both a transaction type and an amount to be specified
          elif not transactionType or not amount:
              logger.error('Insufficient information passed to createSquarePayment view.')
              messages.error(
                  request,
                  format_html(
                      '<p>{}</p><ul><li>{}</li></ul>',
                      str(_('ERROR: Error with Square checkout transaction attempt.')),
                      str(_('Insufficient information passed to createSquarePayment view.'))
                  )
              )
              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(
                  float(amount),
                  this_description,
                  submissionUser=submissionUser,
                  calculate_taxes=(taxable is not False),
                  transactionType=transactionType,
              )
      except (ValueError, ObjectDoesNotExist) as e:
          logger.error('Invalid registration information passed to createSquarePayment view: (%s, %s, %s)' % (invoice_id, tr_id, amount))
          messages.error(
              request,
              format_html(
                  '<p>{}</p><ul><li>{}</li></ul>',
                  str(_('ERROR: Error with Square checkout transaction attempt.')),
                  str(_('Invalid registration information passed to createSquarePayment view: (%s, %s, %s)' % (invoice_id, tr_id, amount)))
              )
          )
          return HttpResponseRedirect(sourceUrl)
  
      this_currency = getConstant('general__currencyCode')
      this_total = min(this_invoice.outstandingBalance, amount)
  
      api_instance = TransactionsApi()
      api_instance.api_client.configuration.access_token = getattr(settings,'SQUARE_ACCESS_TOKEN','')
      idempotency_key = str(uuid.uuid1())
      location_id = getattr(settings,'SQUARE_LOCATION_ID','')
      amount = {'amount': int(100 * this_total), 'currency': this_currency}
      body = {'idempotency_key': idempotency_key, 'card_nonce': nonce_id, 'amount_money': amount}
  
      errors_list = []
  
      try:
          # Charge
          api_response = api_instance.charge(location_id, body)
          if api_response.errors:
              logger.error('Error in charging Square transaction: %s' % api_response.errors)
              errors_list = api_response.errors
      except ApiException as e:
          logger.error('Exception when calling TransactionApi->charge: %s\n' % e)
          errors_list = json.loads(e.body).get('errors',[])
  
      if errors_list:
          this_invoice.status = Invoice.PaymentStatus.error
          this_invoice.save()
          errors_string = ''
          for err in errors_list:
              errors_string += '<li><strong>CODE:</strong> %s, %s</li>' % (
                  err.get('code',str(_('Unknown'))), err.get('detail',str(_('Unknown')))
              )
          messages.error(
              request,
              format_html(
                  '<p>{}</p><ul>{}</ul>',
                  str(_('ERROR: Error with Square checkout transaction attempt.')),
                  mark_safe(errors_list),
              )
          )
          return HttpResponseRedirect(sourceUrl)
      else:
          logger.info('Square charge successfully created.')
  
      transaction = api_response.transaction
  
      paymentRecord = SquarePaymentRecord.objects.create(
          invoice=this_invoice,
          transactionId=transaction.id,
          locationId=transaction.location_id,
      )
  
      # 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 Checkout',
          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)