@param string  $number
@param Invoice $invoice

@return bool
186707
public static function validate($number, $invoice = null)
    {
        $regexp = sprintf('/^%s(\d{%d})$/', self::$codePrefix, self::$codeLength);

        return preg_match($regexp, $number);
    }
1236594
public function coverInvoice($client, $invoiceId = null)
    {
        return $this->api->coverInvoice($this->getClientId($client), $invoiceId);
    }
279291
public function listPaymentsForInvoice(string $invoiceId, array $headers = [])
    {
        $url = $this->url('invoices/%s/payments', $invoiceId);

        return $this->get($url, [], $headers);
    }
552101
def book_with_number(number)
      response = request(
        :book_with_number,
        "currentInvoiceHandle" => handle.to_hash,
        "number" => number
      )

      # Find the created Invoice
      session.invoices.find(response[:number])
    end
662766
public function setPaidProcessing($iInvoiceId): bool
    {
        $oNow    = Factory::factory('DateTime');
        $bResult = $this->update(
            $iInvoiceId,
            [
                'state' => self::STATE_PAID_PROCESSING,
                'paid'  => $oNow->format('Y-m-d H:i:s'),
            ]
        );

        if ($bResult) {
            $this->triggerEvent(
                Events::INVOICE_PAID_PROCESSING,
                [$this->getInvoiceForEvent($iInvoiceId)]
            );
        }

        return $bResult;
    }
1125234
public function sendAdvertPurchaseNotification(Invoice $invoice)
    {
        $templateName = 'PaymentBundle:Email:advert.notification.admin.html.twig';

        if($invoice->getTransaction()->getActor() instanceof Actor){
            $email = $invoice->getTransaction()->getActor()->getEmail();
        }elseif($invoice->getTransaction()->getOptic() instanceof Optic){
            $email = $invoice->getTransaction()->getOptic()->getEmail();
        }
        $context = array(
            'order_number'    => $invoice->getTransaction()->getTransactionKey(),
            'invoice_date'      => $invoice->getCreated(),
            'user_email'        => $email,
            'order_details_url' => $this->router->generate('payment_checkout_showinvoice', array('number' => $invoice->getInvoiceNumber()), UrlGeneratorInterface::ABSOLUTE_URL),
        );

        $this->sendMessage($templateName, $context, $this->twigGlobal->getParameter('admin_email'), $this->twigGlobal->getParameter('admin_email'));
    }
910467
public function setInvoice(\Core\Entity\Invoice $invoice = null) {
        $this->invoice = $invoice;

        return $this;
    }
1016506
public function settle(Invoice $invoiceA, Invoice $invoiceB, $sendEmail = false)
    {
        return $this->connector->settle($invoiceA, $invoiceB, $sendEmail);
    }
151728
public function hasDiscount()
    {
        return $this->invoice->subtotal > 0 &&
            $this->invoice->subtotal != $this->invoice->total &&
            ! is_null($this->invoice->discount);
    }
590801
private static function updatePaymentStatus($invoice)
    {
        if (! $invoice->payment || $invoice->getStatus() === 'payed') {
            return $invoice;
        }
        $receipt = $invoice->get_payment();
        Bank_Service::update($receipt);
        if ($invoice->get_payment()->isPayed()){
            $invoice->setStatus('payed');
            $invoice->update();
        }
        return $invoice;
    }
676825
public function save(ServiceInterface $service, Invoice $invoice = null)
    {
        if (!$this->validate()) {
            throw new NotValidException('Unable to validate invoice history');
        }

        if ($invoice === null) {
            throw new Exception('$invoice must be instance of Invoice');
        }

        $newInvoice = $service->saveHistory($this, $invoice);
        $invoice->setData($newInvoice->toArray(), false);
        return $this->reload(
            end($invoice->history)
        );
    }
821399
public function invoices($includePending = false, $parameters = [])
    {
        $invoices = [];

        $parameters = array_merge(['limit' => 24], $parameters);

        $stripeInvoices = $this->asStripeCustomer()->invoices($parameters);

        // Here we will loop through the Stripe invoices and create our own custom Invoice
        // instances that have more helper methods and are generally more convenient to
        // work with than the plain Stripe objects are. Then, we'll return the array.
        if (! is_null($stripeInvoices)) {
            foreach ($stripeInvoices->data as $invoice) {
                if ($invoice->paid || $includePending) {
                    $invoices[] = new Invoice($this, $invoice);
                }
            }
        }

        return new Collection($invoices);
    }
585743
public function update(int $invoice, array $data)
    {
        $response = $this->httpPut('/3/invoices/'.$invoice, ['Invoice' => $data]);

        if (!$this->hydrator) {
            return $response;
        }

        // Use any valid status code here
        if (200 !== $response->getStatusCode()) {
            $this->handleErrors($response);
        }

        return $this->hydrator->hydrate($response, Model::class);
    }
1268691
public function send(Invoice $invoice, $method = 'email', $email = null, $message = null)
    {
        return $this->connector->send($invoice, $this->buildEnvelope($method, $email, $message));
    }
748164
protected function triggerInvoiceCreated(array &$invoice, Source $invoiceSource, Result $localResult)
    {
        JPluginHelper::importPlugin('acumulus');
        $results = JEventDispatcher::getInstance()->trigger('onAcumulusInvoiceCreated', array(&$invoice, $invoiceSource, $localResult));
        if (count(array_filter($results, function ($value) {
                return $value === false;
            })) >= 1
        ) {
            $invoice = null;
        }
    }
1137513
protected function pay($oInvoice)
    {
        $oAsset = Factory::service('Asset');
        $oInput = Factory::service('Input');

        $this->data['oInvoice']       = $oInvoice;
        $this->data['headerOverride'] = 'structure/header/blank';
        $this->data['footerOverride'] = 'structure/footer/blank';

        //  Only open invoice can be paid
        if ($oInvoice->state->id !== 'OPEN' && !$oInvoice->is_scheduled) {

            if ($oInvoice->state->id === 'PAID') {

                $oView = Factory::service('View');
                $this->loadStyles(NAILS_APP_PATH . 'application/modules/invoice/views/pay/paid.php');
                $oView->load('structure/header', $this->data);
                $oView->load('invoice/pay/paid', $this->data);
                $oView->load('structure/footer', $this->data);
                return;

            } else {

                show404();
            }
        }

        //  If a user ID is specified, then the user must be logged in as that user
        if (!empty($oInvoice->user->id) && $oInvoice->user->id != activeUser('id')) {
            unauthorised();
        }

        $this->data['sUrlCancel'] = $oInput->get('cancel') ?: site_url();

        // --------------------------------------------------------------------------

        //  If there are payments against this invoice which are processing, then deny payment
        if ($oInvoice->has_processing_payments) {

            $oPaymentModel = Factory::model('Payment', 'nails/module-invoice');

            $this->data['aProcessingPayments'] = [];
            foreach ($oInvoice->payments->data as $oPayment) {
                if ($oPayment->status->id === $oPaymentModel::STATUS_PROCESSING) {
                    $this->data['aProcessingPayments'][] = $oPayment;
                }
            }

            $oView = Factory::service('View');
            $this->loadStyles(NAILS_APP_PATH . 'application/modules/invoice/views/pay/hasProcessing.php');
            $oView->load('structure/header', $this->data);
            $oView->load('invoice/pay/hasProcessing', $this->data);
            $oView->load('structure/footer', $this->data);
            return;
        }

        // --------------------------------------------------------------------------

        //  Payment drivers
        $oPaymentDriverService = Factory::service('PaymentDriver', 'nails/module-invoice');
        $aDrivers              = $oPaymentDriverService->getEnabled();
        foreach ($aDrivers as $oDriver) {

            $oDriverInstance = $oPaymentDriverService->getInstance($oDriver->slug);

            if ($oDriverInstance->isAvailable($oInvoice)) {
                $this->data['aDrivers'][] = $oDriverInstance;
            }
        }

        if (empty($this->data['aDrivers'])) {
            throw new DriverException('No enabled payment drivers', 1);
        }

        // --------------------------------------------------------------------------

        if ($oInput->post()) {

            /**
             * Validation works by looking at which driver has been chosen and then
             * validating the respective fields accordingly. If the driver's fields
             * is simply CARD then we validate the cc[] field.
             */

            $oFormValidation = Factory::service('FormValidation');

            $aRules = [
                'driver'   => ['trim', 'required'],
                'cc[name]' => ['trim'],
                'cc[num]'  => ['trim'],
                'cc[exp]'  => ['trim'],
                'cc[cvc]'  => ['trim'],
            ];

            $sSelectedDriver = $oInput->post('driver');
            $oSelectedDriver = null;

            foreach ($this->data['aDrivers'] as $oDriver) {

                $sSlug   = $oDriver->getSlug();
                $aFields = $oDriver->getPaymentFields();

                if ($sSelectedDriver == $sSlug) {

                    $oSelectedDriver = $oDriver;

                    if ($aFields === $oSelectedDriver::PAYMENT_FIELDS_CARD) {

                        $aRules['cc[name]'][] = 'required';
                        $aRules['cc[num]'][]  = 'required';
                        $aRules['cc[exp]'][]  = 'required';
                        $aRules['cc[cvc]'][]  = 'required';

                    } elseif (!empty($aFields)) {
                        foreach ($aFields as $aField) {
                            $aRules[$sSlug . '[' . $aField['key'] . ']'] = [''];
                        }
                    }

                    break;
                }
            }

            foreach ($aRules as $sKey => $sRules) {
                $oFormValidation->set_rules($sKey, '', implode('|', array_unique($sRules)));
            }

            if ($oFormValidation->run()) {

                try {

                    //  Set up ChargeRequest object
                    $oChargeRequest = Factory::factory('ChargeRequest', 'nails/module-invoice');

                    //  Set the driver to use for the request
                    $oChargeRequest->setDriver($sSelectedDriver);

                    //  Describe the charge
                    $oChargeRequest->setDescription('Payment for invoice #' . $oInvoice->ref);

                    //  Set the invoice we're charging against
                    $oChargeRequest->setInvoice($oInvoice->id);

                    //  If the driver expects card data then set it, if it expects custom data then set that
                    $mPaymentFields = $oSelectedDriver->getPaymentFields();

                    if (!empty($mPaymentFields) && $mPaymentFields == $oSelectedDriver::PAYMENT_FIELDS_CARD) {

                        $sName = !empty($_POST['cc']['name']) ? $_POST['cc']['name'] : '';
                        $sNum  = !empty($_POST['cc']['num']) ? $_POST['cc']['num'] : '';
                        $sExp  = !empty($_POST['cc']['exp']) ? $_POST['cc']['exp'] : '';
                        $sCvc  = !empty($_POST['cc']['cvc']) ? $_POST['cc']['cvc'] : '';

                        $aExp   = explode('/', $sExp);
                        $aExp   = array_map('trim', $aExp);
                        $sMonth = !empty($aExp[0]) ? $aExp[0] : null;
                        $sYear  = !empty($aExp[1]) ? $aExp[1] : null;

                        $oChargeRequest->setCardName($sName);
                        $oChargeRequest->setCardNumber($sNum);
                        $oChargeRequest->setCardExpMonth($sMonth);
                        $oChargeRequest->setCardExpYear($sYear);
                        $oChargeRequest->setCardCvc($sCvc);

                    } elseif (!empty($mPaymentFields)) {
                        foreach ($mPaymentFields as $aField) {
                            if (!empty($_POST[$sSelectedDriver][$aField['key']])) {
                                $sValue = $_POST[$sSelectedDriver][$aField['key']];
                            } else {
                                $sValue = null;
                            }
                            $oChargeRequest->setCustomField($aField['key'], $sValue);
                        }
                    }

                    //  Attempt payment
                    $oChargeResponse = $oChargeRequest->execute(
                        $oInvoice->totals->raw->grand,
                        $oInvoice->currency->code
                    );

                    //  Handle response
                    if ($oChargeResponse->isProcessing() || $oChargeResponse->isComplete()) {

                        /**
                         * Payment was successful (but potentially unconfirmed). Send the user off to
                         * complete the request.
                         */

                        redirect($oChargeResponse->getSuccessUrl());

                    } elseif ($oChargeResponse->isFailed()) {

                        /**
                         * Payment failed, throw an error which will be caught and displayed to the user
                         */

                        throw new NailsException(
                            'Payment failed: ' . $oChargeResponse->getError()->user,
                            1
                        );

                    } else {

                        /**
                         * Something which we've not accounted for went wrong.
                         */

                        throw new NailsException('Payment failed.', 1);
                    }

                } catch (\Exception $e) {
                    $this->data['error'] = $e->getMessage();
                }

            } else {
                $this->data['error'] = lang('fv_there_were_errors');
            }
        }

        // --------------------------------------------------------------------------

        $oView = Factory::service('View');
        $this->loadStyles(NAILS_APP_PATH . 'application/modules/invoice/views/pay/index.php');
        $oAsset->load('../../node_modules/jquery.payment/lib/jquery.payment.min.js', 'nails/module-invoice');
        $oAsset->load('invoice.pay.min.js', 'nails/module-invoice');
        $oView->load('structure/header', $this->data);
        $oView->load('invoice/pay/index', $this->data);
        $oView->load('structure/footer', $this->data);
    }
1226037
public function payWithStripeAction(Invoice $invoice, Request $request)
    {
        $buyer = $this->get('security.context')
            ->getToken()
            ->getUser()
            ->getCurrentProfile()
        ;

        if ($buyer !== $invoice->getCustomer()) {
            throw new NotFoundHttpException('Buyer is not Invoice Customer');
        }

        // First we need to create a payment
        $payment = new InvoicePayment(array($invoice));

        // Save the Payment, so that we get an id
        $em = $this->get('doctrine')->getEntityManager();
        $em->persist($payment);
        $em->flush();

        $this->get('payment.stripe');

        // Grap Stripe token
        $token  = $_POST['stripeToken'];

        try {
            // First create a Stripe customer
            $customer = \Stripe_Customer::create(array(
              'card'        => $token,
              'description' => '#'.$invoice->getCustomer()->getId().' '.$invoice->getCustomer()->getName(),
            ));

            $charge = \Stripe_Charge::create(array(
                'customer'    => $customer->id,
                'amount'      => floor($payment->getAmount()*100),
                'currency'    => 'usd',
                'description' => 'Invoice Payment #'.$payment->getId(),
            )); //, $invoice->getVendor()->getStripeAccessToken());

            // Create SavedCreditCard
            $creditCard = new \HarvestCloud\CoreBundle\Entity\Payment\SavedCreditCard();
            $creditCard->setPaymentServiceKey('stripe');
            $creditCard->setPaymentServiceToken($customer->id);
            $creditCard->setType($charge['card']['type']);
            $creditCard->setExpiryDateFromYearAndMonth($charge['card']['exp_year'], $charge['card']['exp_month']);
            $creditCard->setLastFourDigits($charge['card']['last4']);
            $creditCard->setNameOnCard($charge['card']['name']);

            $invoice->getCustomer()->addSavedCreditCard($creditCard);

            $em->persist($invoice->getCustomer());
            $em->flush();


            // Everything went OK, so let's post the Payment
            $payment->post();

            // Create a Customer
        } catch (\Stripe_CardError $e) {
            // @todo Send some messages back to the browser
            // for now, we'll just re-throw the exception
            throw $e;
        }

        // Save the Payment again after the post()
        $em->persist($payment);
        $em->flush();

        return $this->redirect($this->generateurl('Buyer_invoice_show', array(
            'id' => $invoice->getId(),
        )));
    }