Magento – Create invoice programmatically and capture online not working while running from cron

croninvoicemagento-1.7programmatically

I'm currently facing a weird result with my script when running it by cron.
This script is creating the invoice and capture the amount online.

if($order->canInvoice()) {

  $invoice = Mage::getModel('sales/service_order', $order)->prepareInvoice();
  $invoice->setRequestedCaptureCase(Mage_Sales_Model_Order_Invoice::CAPTURE_ONLINE);
  $invoice->register()->pay(); 

  Mage::getModel('core/resource_transaction')
      ->addObject($invoice)
      ->addObject($invoice->getOrder())
      ->save();

  $invoice->sendEmail();

}

It works fine when I call the cron by Magento backend AEOScheduler, then "RunNow".

The problem is when the cron is executed automatically by crontab.
The invoice is created successfully but the event "sales_order_invoice_pay" seems not fired. This is the event catched by my payment processor extension for capturing correctly the amount ONLINE.

Any idea/suggestion would be appreciate.
Thank you.

Best Answer

Try below code:

<?php

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->addComment('Invoice genrated automatically');
$invoice->register();

$transactionSave = Mage::getModel('core/resource_transaction')
    ->addObject($invoice)
    ->addObject($order);

$transactionSave->save();

try {
    $invoice->sendEmail(true);
} catch (Exception $e) {
    Mage::logException($e);
    Mage::getSingleton('core/session')
        ->addError($this->__('Unable to send the invoice email.'));
}