Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8318865
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 8, 20262026-06-08T22:07:35+00:00 2026-06-08T22:07:35+00:00

Hy, i’m trying to create a refund programmatically : //get order magento $orderMagento =

  • 0

Hy,

i’m trying to create a refund programmatically :

//get order magento

$orderMagento = Mage::getModel('sales/order')->loadByIncrementId($realOrderIncrementId );
if($orderMagento->getStatus() == Mage_Sales_Model_Order::STATE_CANCELED){
//création de l'avoir
$convertOrder = new Mage_Sales_Model_Convert_Order ();
$creditMemo = $convertOrder->toCreditmemo ( $orderMagento );

$items = $orderMagento->getAllItems ();
$totalQty = 0;

foreach ( $items as $item ) {
  $_eachCreditMemoItem = $convertOrder->itemToCreditmemoItem ( $item );
  $_eachCreditMemoItem->setQty ($item->getQtyInvoiced());
  $_eachCreditMemoItem->register ();
  $creditMemo->addItem ( $_eachCreditMemoItem );
  $totalQty += $item->getQtyInvoiced ();
} 

$creditMemo->refund();
$creditMemo->setTotalQty ( $totalQty );
$orderCreditMemoStatusCode = Mage_Sales_Model_Order::STATE_CLOSED;
$orderCreditMemoStatusComment = '[OK]Remboursement des article : ';
$saveTransaction = Mage::getModel('core/resource_transaction')->addObject ($creditMemo )->addObject ( $orderMagento )->save ();
$orderMagento->addStatusToHistory ( $orderCreditMemoStatusCode, $orderCreditMemoStatusComment, false );
$orderMagento->save ();
}

This code create a credit memo but all amount are null (BaseGrandTotal = 0.00€, etc…)

So where is the problem ?

Thanks you

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-08T22:07:37+00:00Added an answer on June 8, 2026 at 10:07 pm

    First of all thank you, I started implementing creditmemo by programming using your code, and the problem I had was that the credit memom was created but without products. I’ll share my code so you can use it.

    /*
    I think your problem is with the content of the variable data, I'll give you an example:
    
    array(6) {
      ["items"] => array(2) {
        [11] => array(1) {
          ["qty"] => string(6) "2"
        }
        [13] => array(1) {
          ["qty"] => string(1) "0"
        }
      }
      ["do_offline"] => string(1) "1"
      ["comment_text"] => string(0) ""
      ["shipping_amount"] => string(1) "0"
      ["adjustment_positive"] => string(1) "0"
      ["adjustment_negative"] => string(1) "0"
      ["qtys"] => array(2) {
        [11] => int(2)
        [13] => int(0)
      }
    }
    

    */

     /**
     *
     * @param array $dif array that contains my product information with qty and product_id and item_id
     * @param type $info array("order_increment_id" => $order->getIncrementId(), "invoice_id" => $invoiceId);
     * @return type 
     */
    protected function creaDevolucio($dif, $info){
        $qtys = array();
    
        foreach ($dif as $item) {
            if (isset($item['qty'])) {
                $qtys[$item['order_item_id']] = array("qty"=> $item['qty']);
            }
            if (isset($item['back_to_stock'])) {
                $backToStock[$item['order_item_id']] = true;
            }
        }
    
        $data = array(
            "items" => $qtys,
            "do_offline" => "1",
            "comment_text" => "",
            "shipping_amount" => "0",
            "adjustment_positive" => "0",
            "adjustment_negative" => "0",
        );
        if (!empty($data['comment_text'])) {
            Mage::getSingleton('adminhtml/session')->setCommentText($data['comment_text']);
        }
    
        try {
            $creditmemo = $this->_initCreditmemo($data, $info);
            if ($creditmemo) {
                if (($creditmemo->getGrandTotal() <=0) && (!$creditmemo->getAllowZeroGrandTotal())) {
                    Mage::throwException(
                        $this->__('Credit memo\'s total must be positive.')
                    );
                }
    
                $comment = '';
                if (!empty($data['comment_text'])) {
                    $creditmemo->addComment(
                        $data['comment_text'],
                        isset($data['comment_customer_notify']),
                        isset($data['is_visible_on_front'])
                    );
                    if (isset($data['comment_customer_notify'])) {
                        $comment = $data['comment_text'];
                    }
                }
    
                if (isset($data['do_refund'])) {
                    $creditmemo->setRefundRequested(true);
                }
                if (isset($data['do_offline'])) {
                    $creditmemo->setOfflineRequested((bool)(int)$data['do_offline']);
                }
    
                $creditmemo->register();
                if (!empty($data['send_email'])) {
                    $creditmemo->setEmailSent(true);
                }
    
                $creditmemo->getOrder()->setCustomerNoteNotify(!empty($data['send_email']));
                $this->_saveCreditmemo($creditmemo);
                $creditmemo->sendEmail(!empty($data['send_email']), $comment);
                echo '<br>The credit memo has been created.';
                Mage::getSingleton('adminhtml/session')->getCommentText(true);
                return;
            } else {
                //$this->_forward('noRoute');
                //return;
            }
        } catch (Mage_Core_Exception $e) {
            $this->_getSession()->addError($e->getMessage());
            Mage::getSingleton('adminhtml/session')->setFormData($data);
        } catch (Exception $e) {
            Mage::logException($e);
            $this->_getSession()->addError($this->__('Cannot save the credit memo.'));
        }
    }
    
    /**
     *
     * @param type $data contains products info to refund
     * @param type $info array("order_increment_id" => $order->getIncrementId(), "invoice_id" => $invoiceId);
     * @param type $update
     * @return boolean 
     */
    protected function _initCreditmemo($data, $info, $update = false)
    {
        $creditmemo = false;
        $invoice=false;
        $creditmemoId = null;//$this->getRequest()->getParam('creditmemo_id');
        $orderId = $info['order_increment_id'];//$this->getRequest()->getParam('order_id');
        $invoiceId = $data['invoice_id'];
        echo "<br>abans if. OrderId: ".$orderId;
        if ($creditmemoId) {
            $creditmemo = Mage::getModel('sales/order_creditmemo')->load($creditmemoId);
        } elseif ($orderId) {
            $order  = Mage::getModel('sales/order')->loadByIncrementId($orderId);
            if ($invoiceId) {
                $invoice = Mage::getModel('sales/order_invoice')
                    ->load($invoiceId)
                    ->setOrder($order);
                echo '<br>loaded_invoice_number: '.$invoice->getId();
            }
    
             if (!$order->canCreditmemo()) {
                echo '<br>cannot create credit memo'; 
                if(!$order->isPaymentReview())
                {
                    echo '<br>cannot credit memo Payment is in review'; 
                }
                if(!$order->canUnhold())
                {
                    echo '<br>cannot credit memo Order is on hold'; 
                }
                if(abs($order->getTotalPaid()-$order->getTotalRefunded())<.0001)
                {
                    echo '<br>cannot credit memo Amount Paid is equal or less than amount refunded'; 
                }
                if($order->getActionFlag('edit') === false)
                {
                    echo '<br>cannot credit memo Action Flag of Edit not set'; 
                }
                if ($order->hasForcedCanCreditmemo()) {
                    echo '<br>cannot credit memo Can Credit Memo has been forced set'; 
                }
                return false;
            }
    
            $savedData = array();
            if (isset($data['items'])) {
                $savedData = $data['items'];
            } else {
                $savedData = array();
            }
    
            $qtys = array();
            $backToStock = array();
            foreach ($savedData as $orderItemId =>$itemData) {
                if (isset($itemData['qty'])) {
                    $qtys[$orderItemId] = $itemData['qty'];
                }
                if (isset($itemData['back_to_stock'])) {
                    $backToStock[$orderItemId] = true;
                }
            }
            $data['qtys'] = $qtys;
    
            $service = Mage::getModel('sales/service_order', $order);
            if ($invoice) {
                $creditmemo = $service->prepareInvoiceCreditmemo($invoice, $data);
            } else {
                $creditmemo = $service->prepareCreditmemo($data);
            }
    
            /**
             * Process back to stock flags
             */
            foreach ($creditmemo->getAllItems() as $creditmemoItem) {
                $orderItem = $creditmemoItem->getOrderItem();
                $parentId = $orderItem->getParentItemId();
                if (isset($backToStock[$orderItem->getId()])) {
                    $creditmemoItem->setBackToStock(true);
                } elseif ($orderItem->getParentItem() && isset($backToStock[$parentId]) && $backToStock[$parentId]) {
                    $creditmemoItem->setBackToStock(true);
                } elseif (empty($savedData)) {
                    $creditmemoItem->setBackToStock(Mage::helper('cataloginventory')->isAutoReturnEnabled());
                } else {
                    $creditmemoItem->setBackToStock(false);
                }
            }
        }
    
        return $creditmemo;
    }
    
    /**
     * Save creditmemo and related order, invoice in one transaction
     * @param Mage_Sales_Model_Order_Creditmemo $creditmemo
     */
    protected function _saveCreditmemo($creditmemo)
    {
        $transactionSave = Mage::getModel('core/resource_transaction')
            ->addObject($creditmemo)
            ->addObject($creditmemo->getOrder());
        if ($creditmemo->getInvoice()) {
            $transactionSave->addObject($creditmemo->getInvoice());
        }
        $transactionSave->save();
    
        return $this;
    }
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

Basically, what I'm trying to create is a page of div tags, each has
I'm trying to create an if statement in PHP that prevents a single post
I am trying to understand how to use SyndicationItem to display feed which is
link Im having trouble converting the html entites into html characters, (&# 8217;) i
I have a string like this: La Torre Eiffel paragonata all&#8217;Everest What PHP function
I am trying to render a haml file in a javascript response like so:
I'm parsing an RSS feed that has an &#8217; in it. SimpleXML turns this
I'm trying to decode HTML entries from here NYTimes.com and I cannot figure out
I'm trying to use string.replace('’','') to replace the dreaded weird single-quote character: ’ (aka
I am trying to loop through a bunch of documents I have to put

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.