Magento – How to Create an Order via API Call

apicartorders

I want to create an order using API in magento.

I have already create an api as following:
cart.create
cart_product.add
cart.totals

So quote is generated in magento when customer called API from android while product add to cart. Now next thing is to create an order of this quote.

Description More about query :
we place an order in magento by following way :

  1. Add product to cart
  2. Select shipping method (but here not because I am using downlodable product)
  3. Select payment method
  4. Place order

Now see how I maintain above steps between android app and magento

  1. Customer add product to cart in application (service is called to magento this time and I am adding products to cart with method “cart.create”)
  2. Customer select payment method Paypal. This time any service is not called but as we have paypal sdk,customer redirect to paypal from app to gateway.there he pay amount and come back to application.
  3. Now when he come back to application,service is called. And on this call I have to create an order.

May be this is more easy to understand my query.

Here I am confused, how to create an order in Magento after success/canceled transaction response, sent from App to Magento.

Best Answer

Not sure if I understood correctly, but you should always create the order before before redirecting to paypal. Then when paypal notifies you that the payment was made the order should change status accordingly.

This is how I would create an order:

$quote = $this->getQuote();

try {
    $quotePayment = $quote->getPayment();

    $quotePayment->setMethod('payment_method_code');
    $quote->setPayment($quotePayment);

    $onePageCheckOut = \Mage::getSingleton('checkout/type_onepage');
    $onePageCheckOut->getCheckout()->setQuoteId($quote->getId());
    $onePageCheckOut->saveOrder();

    $this->redirectUrl = $onePageCheckOut->getCheckout()->getRedirectUrl();
    $quote->setIsActive(false)->save();
} catch (\Exception $e) {
    throw new \Exception(
        $e->getMessage(),
        'some error code'
    );
}

$order = \Mage::getModel('sales/order')->load($onePageCheckOut->getLastOrderId(), 'increment_id');
$order->save();

Then you need to wait for the payment notification and update the order:

//check how to get the params in your case
$paymentId = $this->param('payment_id');
$transactionId = $this->param('transaction_id');

if($order->getStatus() === \Mage_Sales_Model_Order::STATE_CANCELED) {
    //do something if order is cancelled
}

$payment = $order->getPayment();

$amountOrdered = $payment->getAmountOrdered();
$payment->setAmountPaid($amountOrdered);
$payment->setAmountAuthorized($amountOrdered);

/** Save a comment regarding the transaction */
$order->addStatusHistoryComment(
    sprintf(
        "Transaction status: %s / Paypal id: %s",
        strtoupper($this->paymentStatus),
        $paymentId
    )
);
$payment->save();
$order->save();
Related Topic