Perform invoice return all API request
488923
public function returnAll()
    {
        $data = $this->twisto->requestJson('POST', 'invoice/' . urlencode($this->invoice_id) . '/return/all/');
        $this->deserialize($data);
    }
1343723
def api_get(self, action, data, headers=None):
        
        return self._api_request(action, data, 'GET', headers)
38560
public function getInvoiceById($id, Request $request)
    {
        try {
            $user = $request->user();
            $response = $user->meta->downloadInvoice($id, [
                'vendor'    => config("invoice.company"),
                'street'    => config("invoice.street"),
                'location'  => config("invoice.location"),
                'phone'     => config("invoice.phone"),
                'url'       => config("invoice.url"),
                'product'   => config("invoice.product"),
                'description'   => 'Subscription',
            ]);
        } catch (Exception $e) {
            $response = back()->withErrors(['Could not find this invoice, please try again.']);
        }

        return $response;
    }
1002513
def get_invoice(invoice_id_or_number, format = :xml)
      request_params = {}
      headers        = {}

      headers.merge!("Accept" => "application/pdf") if format == :pdf

      url  = "#{@xero_url}/Invoices/#{CGI.escape(invoice_id_or_number)}"

      response = http_get(@client, url, request_params, headers)

      if format == :pdf
        Tempfile.open(invoice_id_or_number) do |f|
          f.write(response)
          f
        end
      else
        parse_response(response, {:request_params => request_params}, {:request_signature => 'GET/Invoice'})
      end
    end
699891
def void
            
      resp = StdClass.new
      t = InvoiceTransaction.where(:invoice_id => self.id, :transaction_type => InvoiceTransaction::TYPE_AUTHORIZE, :success => true).first
      
      if self.financial_status == Invoice::FINANCIAL_STATUS_CAPTURED
        resp.error = "This invoice has already been captured, you will need to refund instead"
      elsif t.nil?
        resp.error = "This invoice doesn't seem to be authorized."
      else
                
        sc = self.site.store_config
        ot = Caboose::InvoiceTransaction.new(
          :invoice_id => self.id,
          :date_processed => DateTime.now.utc,
          :transaction_type => InvoiceTransaction::TYPE_VOID,
          :payment_processor => sc.pp_name,
          :amount => self.total
        )
        
        case sc.pp_name
          when 'authorize.net'            
            response = AuthorizeNet::SIM::Transaction.new(
              sc.authnet_api_login_id, 
              sc.authnet_api_transaction_key,                      
              self.total,
              :transaction_type => InvoiceTransaction::TYPE_VOID,
              :transaction_id => t.transaction_id,
              :test => sc.pp_testing
            )                    
            self.update_attributes(
              :financial_status => Invoice::FINANCIAL_STATUS_VOIDED,
              :status => Invoice::STATUS_CANCELED
            )
            self.save          
            # TODO: Add the variant quantities invoiceed back        
            resp.success = "Invoice voided successfully"
                        
            ot.success        = response.response_code && response.response_code == '1'            
            ot.transaction_id = response.transaction_id
            #ot.auth_code      = response.authorization_code
            ot.response_code  = response.response_code            
            ot.save
          
          when 'stripe'
            # TODO: Implement void invoice for strip
            
          when 'payscape'
            # TODO: Implement void invoice for payscape
            
        end
        
      end
      return resp      
    end
1040916
public static Invoice retrieve(String invoice) throws StripeException {
    return retrieve(invoice, (Map<String, Object>) null, (RequestOptions) null);
  }
122212
def get_all_invoice_payments(self, params=None):
        
        if not params:
            params = {}
        return self._iterate_through_pages(
            get_function=self.get_invoice_payments_per_page,
            resource=INVOICE_PAYMENTS,
            **{'params': params}
        )
902379
def all(self, data={}, **kwargs):
        "
        return super(Payment, self).all(data, **kwargs)
423607
def _request_api(self, **kwargs):
        
        _url = kwargs.get('url')
        _method = kwargs.get('method', 'GET')
        _status = kwargs.get('status', 200)

        counter = 0
        if _method not in ['GET', 'POST']:
            raise ValueError('Method is not GET or POST')

        while True:
            try:
                res = REQ[_method](_url, cookies=self._cookie)
                if res.status_code == _status:
                    break
                else:
                    raise BadStatusException(res.content)
            except requests.exceptions.BaseHTTPError:
                if counter < self._retries:
                    counter += 1
                    continue
                raise MaxRetryError
        self._last_result = res
        return res
1214018
def get(self, endpoint, params=None, version='1.1'):
        """"""
        return self.request(endpoint, params=params, version=version)
1075272
def generic_request(self, method, uri,
                        all_pages=False,
                        data_key=None,
                        no_data=False,
                        do_not_process=False,
                        force_urlencode_data=False,
                        data=None,
                        params=None,
                        files=None,
                        single_item=False):
        """"""
        if not uri.startswith('http'):
            uri = self.uri_for(uri)

        if force_urlencode_data is True:
            uri += '?' + urllib.urlencode(data)

        assert method in ['GET', 'POST', 'PUT', 'DELETE', 'HEAD', 'OPTIONS']

        if method == 'GET':
            response = self.session.get(uri, params=params)
        elif method == 'POST':
            response = self.session.post(uri, data=data, files=files)
        elif method == 'PUT':
            response = self.session.put(uri, data=data)
        elif method == 'DELETE':
            response = self.session.delete(uri, params=params)
        elif method == 'HEAD':
            response = self.session.head(uri, params=params)
        elif method == 'OPTIONS':
            response = self.session.options(uri, params=params)

        response.raise_for_status()

        if do_not_process is True:
            return response

        if no_data:
            return response.status_code

        if all_pages:
            return self.depaginate(response, data_key)

        if single_item:
            r = response.json()
            if data_key:
                return r[data_key]
            else:
                return r

        return response.json()
1236561
async def api_request(self, url, params):
        """"""
        request = None
        try:
            with async_timeout.timeout(DEFAULT_TIMEOUT, loop=self._event_loop):
                request = await self._api_session.get(
                    url, params=params)
            if request.status != 200:
                _LOGGER.error('Error fetching Emby data: %s', request.status)
                return None

            request_json = await request.json()
            if 'error' in request_json:
                _LOGGER.error('Error converting Emby data to json: %s: %s',
                              request_json['error']['code'],
                              request_json['error']['message'])
                return None
            return request_json
        except (aiohttp.ClientError, asyncio.TimeoutError,
                ConnectionRefusedError) as err:
            _LOGGER.error('Error fetching Emby data: %s', err)
            return None
1123399
def _api_call(self, endpoint, model=None, method=None, data=None, filters=None):
        
        if not self.token:
            raise RuntimeError("You do not have an API token!")

        if not method:
            raise ValueError("Method is required for API calls!")

        if model:
            endpoint = endpoint.format(**vars(model))
        url = '{}{}'.format(self.base_url, endpoint)
        headers = {
            'Authorization': "Bearer {}".format(self.token),
            'Content-Type': 'application/json',
            'User-Agent': self._user_agent,
        }

        if filters:
            headers['X-Filter'] = json.dumps(filters)

        body = None
        if data is not None:
            body = json.dumps(data)

        response = method(url, headers=headers, data=body)

        warning = response.headers.get('Warning', None)
        if warning:
            logger.warning('Received warning from server: {}'.format(warning))

        if 399 < response.status_code < 600:
            j = None
            error_msg = '{}: '.format(response.status_code)
            try:
                j = response.json()
                if 'errors' in j.keys():
                    for e in j['errors']:
                        error_msg += '{}; '.format(e['reason']) \
                                if 'reason' in e.keys() else ''
            except:
                pass
            raise ApiError(error_msg, status=response.status_code, json=j)

        if response.status_code != 204:
            j = response.json()
        else:
            j = None # handle no response body

        return j
777278
def create_invoices(invoices)
      b = Builder::XmlMarkup.new
      request_xml = b.Invoices {
        invoices.each do | invoice |
          invoice.to_xml(b)
        end
      }

      response_xml = http_put(@client, "#{@xero_url}/Invoices?SummarizeErrors=false", request_xml, {})

      response = parse_response(response_xml, {:request_xml => request_xml}, {:request_signature => 'PUT/invoices'})
      response.invoices.each_with_index do | response_invoice, index |
        invoices[index].invoice_id = response_invoice.invoice_id if response_invoice && response_invoice.invoice_id
      end
      response
    end
624020
public function showInvoiceAction(Request $request, $number)
    {
        
        $em = $this->container->get('doctrine')->getManager();
        /** @var Invoice $invoice */
        $invoice = $em->getRepository('EcommerceBundle:Invoice')->findOneBy(array(
            'invoiceNumber' => $number
        ));

        if (!$invoice ||
            false === $this->container->get('checkout_manager')->isCurrentUserOwner($invoice->getTransaction())) {
            throw new AccessDeniedException();
        }

        /** @var CheckoutManager $checkoutManager */
        $checkoutManager = $this->container->get('checkout_manager');

        $delivery = $invoice->getTransaction()->getDelivery();
        $totals = $checkoutManager->calculateTotals($invoice->getTransaction(), $delivery);

        return array(
                'delivery' => $delivery,
                'invoice'  => $invoice,
                'totals'   => $totals,
            );
    }
879107
public function getSearch()
    {
        if (!userHasPermission('admin:invoice:customer:manage')) {
            throw new ApiException('You are not authorised to search customers.', 401);
        }

        $oInput         = Factory::service('Input');
        $sKeywords      = $oInput->get('keywords');
        $oCustomerModel = Factory::model('Customer', 'nails/module-invoice');

        if (strlen($sKeywords) < 3) {
            throw new ApiException('Search term must be 3 characters or longer.', 400);
        }

        $oResult = $oCustomerModel->search($sKeywords);
        $aOut    = [];

        foreach ($oResult->data as $oCustomer) {
            $aOut[] = $this->formatCustomer($oCustomer);
        }

        return Factory::factory('ApiResponse', 'nails/module-api')
                      ->setData($aOut);
    }
530625
def api_run_get(run_id):
    """"""
    data = current_app.config["data"]
    run = data.get_run_dao().get(run_id)
    records_total = 1 if run is not None else 0
    if records_total == 0:
        return Response(
            render_template(
                "api/error.js",
                error_code=404,
                error_message="Run %s not found." % run_id),
            status=404,
            mimetype="application/json")
    records_filtered = records_total
    return Response(render_template("api/runs.js", runs=[run], draw=1,
                                    recordsTotal=records_total,
                                    recordsFiltered=records_filtered,
                                    full_object=True),
                    mimetype="application/json")