create invoice capture amount programmatic magento

create invoice capture amount programmatic magento, In order to capture the amount and create auto invoice programmatic from your custom payment module. Enable invoice variable first in your source model and use this code sample

In your model file.


public function invoiceandcapture(Varien_Object $payment, $amount){
        $order = $payment->getOrder(); 
        try {
                if(!$order->canInvoice())
                {
                Mage::throwException(Mage::helper('core')->__('Cannot create an invoice.'));
                }
                 
                $invoice = Mage::getModel('sales/service_order', $order)->prepareInvoice();
                 
                if (!$invoice->getTotalQty()) {
                Mage::throwException(Mage::helper('core')->__('Cannot create an invoice without products.'));
                }                   $invoice->setRequestedCaptureCase(Mage_Sales_Model_Order_Invoice::CAPTURE_ONLINE);
                $invoice->register(); 
                $transactionSave = Mage::getModel('core/resource_transaction')
                ->addObject($invoice)
                ->addObject($order);
                 
                $transactionSave->save(); 

                 foreach ($order->getInvoiceCollection() as $invoice) {
                        $invoiceIncId[] = $invoice->getIncrementId();
                 }
                 $incrementId = $invoiceIncId[0];
                 $invoive = Mage::getModel('sales/order_invoice')->loadByIncrementId($incrementId);
                 if($this->getConfigData('send_invoice_email')) {
                    $invoice->getOrder()->setCustomerNoteNotify(true);
                    $invoice->getOrder()->setIsInProcess(true);
                    $invoice->sendEmail();  
                 }
                 $invoice->capture()->save(); 
            }
            catch (Mage_Core_Exception $e) {
                  Mage::getSingleton('core/session')->setInvoicemessage($e->getMessage());
            }
    }

Of course, for customer invoice email you need to make some external settings. To check the condition. For example in system.xml file

    <send_invoice_email translate="label">
         <label>Send Invoice Email to Customer</label>
             <frontend_type>select</frontend_type>
             <source_model>adminhtml/system_config_source_yesno</source_model>
             <sort_order>9</sort_order>
             <show_in_default>1</show_in_default>
             <show_in_website>1</show_in_website>
             <show_in_store>0</show_in_store>
             <depends>
               <generate_auto_invoice>1</generate_auto_invoice>
             </depends>
     </send_invoice_email>