phpmagento

Create an Invoice after order is placed


I've create my custom payment module, it works on payment gateway, everything is working fine but I would like to set the order as paid when the return url give back a succes code. So far I've understand that I have to create an invoice for the order to be able to ave it set as paid into Magento panel.

So first of all please tell me if I'm wron until here.

Then I'm trying to create invoice on success.phtml with some codes like:

$invoice = Mage::getModel('sales/service_order', $order->prepareInvoice());


        $invoice->setRequestedCaptureCase(Mage_Sales_Model_Order_Invoice::CAPTURE_OFFLINE);
        $invoice->register();

        $invoice->getOrder()->setCustomerNoteNotify(true);          
        $invoice->getOrder()->setIsInProcess(true);
        $order->addStatusHistoryComment('Automatically INVOICED by Rico.', false);

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

        $transactionSave->save();

But it gives me back always a magento error, so probably is not a good idea.

Any help will be appreciated

EDIT

From this http://blog.chapagain.com.np/magento-quick-way-to-create-order-invoice-programmatically/

I've used

$invoiceId = Mage::getModel('sales/order_invoice_api')
                        ->create($_order->getIncrementId(), array());

instead the code above and it seems that the order is paid. But I'm not sure, if is enough.


Solution

  • I suggest you when customer is returning to your site from payment gateway and then it must goes to a magento controller and it an action you need to add your code at there

      $order=Mage::getModel('sales/order')->load($orderID);
    if($order->canInvoice() and $order->getIncrementId())
    {
      $items = array();
      foreach ($order->getAllItems() as $item) {
        $items[$item->getId()] = $item->getQtyOrdered();
      }
    $invoiceId=Mage::getModel('sales/order_invoice_api')->create($order->getIncrementId(),$items,null,false,true);
    Mage::getModel('sales/order_invoice_api')->capture($invoiceId)};
    }