Magento – Magento – set currency when creating order programmatically

currencymagento-1.7orders

I have a dev magento with multi-currency enabled (GBP, EUR , USD). I am trying to create a sales order against my dev magento in Euro – however the order keeps creating in GBP (my base currency).

Any idea what I am doing wrong? Here's my code so far:

<?php

// Init Magento In Admin Store Context
require_once '/home/www-data/public_html/app/Mage.php';
$app = Mage::app()->setCurrentStore(Mage_Core_Model_App::ADMIN_STORE_ID);

// Function To Generate Magento Sales Order
function CreateOrder($orderData = array())
{
    // Validate Order Data
    if (!sizeof($orderData)) {
        exit('Invalid Order Data');
    }
    $orderData = (object)$orderData;
    if (!sizeof($orderData->BasketData)) {
        exit('Sales Order Basket Cannot Be Empty');
    }

    // Anticipate Error
    try
    {
        // Start New Sales Order Quote
        $quote = Mage::getModel('sales/quote')
                 ->setStoreId($orderData->StoreId);

        // Set Sales Order Quote Currency
        $quote->setCurrency($orderData->Currency);

        // Load Sales Order Customer
        $customer = Mage::getModel('customer/customer')
                    ->setWebsiteId($orderData->CustomerWebsiteId)
                    ->load($orderData->CustomerId);

        // Assign Customer To Sales Order Quote
        $quote->assignCustomer($customer);

        // Configure Notification
        $quote->setSendCconfirmation($orderData->SendConfirmation ? '1' : '0');

        // Add Products To Sales Order Quote
        foreach ($orderData->BasketData as $orderLine)
        {
            // Add Product To Sales Order Quote
            $quote->addProduct(
                Mage::getModel('catalog/product')->load($orderLine['ProductId']),
                new Varien_Object(array(
                    'price' => floatval($orderLine['Price']),
                    'qty'   => intval($orderLine['Qty'])
                ))
            );
        }

        // Set Sales Order Billing Address
        $billingAddress = $quote->getBillingAddress()->addData(array(
            'firstname'  => $orderData->BillingAddress['Firstname'],
            'lastname'   => $orderData->BillingAddress['Lastname'],
            'company'    => $orderData->BillingAddress['Company'],
            'street'     => array($orderData->BillingAddress['AddressLine1'], $orderData->BillingAddress['AddressLine2']),
            'region_id'  => 0,
            'region'     => $orderData->BillingAddress['Region'],
            'city'       => $orderData->BillingAddress['City'],
            'postcode'   => $orderData->BillingAddress['Postcode'],
            'country_id' => getCountryId($orderData->BillingAddress['Country']),
            'telephone'  => $orderData->BillingAddress['Telephone']
        ));

        // Set Sales Order Shipping Address
        $shippingAddress = $quote->getShippingAddress()->addData(array(
            'firstname'  => $orderData->ShippingAddress['Firstname'],
            'lastname'   => $orderData->ShippingAddress['Lastname'],
            'company'    => $orderData->ShippingAddress['Company'],
            'street'     => array($orderData->ShippingAddress['AddressLine1'], $orderData->ShippingAddress['AddressLine2']),
            'region_id'  => 0,
            'region'     => $orderData->ShippingAddress['Region'],
            'city'       => $orderData->ShippingAddress['City'],
            'postcode'   => $orderData->ShippingAddress['Postcode'],
            'country_id' => getCountryId($orderData->ShippingAddress['Country']),
            'telephone'  => $orderData->ShippingAddress['Telephone']
        ));

        // Collect Rates and Set Shipping & Payment Method
        $shippingAddress->setCollectShippingRates(true)
                        ->collectShippingRates()
                        ->setShippingMethod($orderData->ShippingMethod)
                        ->setPaymentMethod($orderData->PaymentMethod);

        // Set Sales Order Payment
        $quote->getPayment()->importData(array('method' => $orderData->PaymentMethod));

        // Collect Totals & Save Quote
        $quote->collectTotals()->save();

        // Create Order From Quote
        $service = Mage::getModel('sales/service_quote', $quote);
        $service->submitAll();
        $increment_id = $service->getOrder()->getIncrementId();

        // Resource Clean-Up
        $quote = $customer = $service = null;

        // Finished
        return $increment_id;
    }
    catch (Exception $e)
    {
        // Error
        exit($e->getMessage());
    }
}

// HELPER FUNCTION
function getCountryId($countryName) {
    $countryId = '';
    $countryCollection = Mage::getModel('directory/country')->getCollection();
    foreach ($countryCollection as $country) {
        if ($countryName == $country->getName()) {
            $countryId = $country->getCountryId();
            break;
        }
    }
    $countryCollection = null;
    return $countryId;
}

// TEST Order Create Function
echo CreateOrder(array(
    'Currency'          => 'EUR', // Euro
    'StoreId'           => 3,     // Trade Store View
    'CustomerWebsiteId' => 2,     // Trade Website
    'CustomerId'        => 5,     // Latheesan K.
    'SendConfirmation'  => false,
    'BasketData'        => array
    (
        array('ProductId' => 3, 'Price' => 13.00, 'Qty' => 1), // VCF001
        array('ProductId' => 6, 'Price' =>  1.00, 'Qty' => 1), // VCF002
        array('ProductId' => 8, 'Price' => 14.99, 'Qty' => 1), // VCF003
    ),
    'BillingAddress'    => array
    (
        'Firstname'     => 'Latheesan',
        'Lastname'      => 'Kanes',
        'Company'       => 'Intelli B.I. Ltd',
        'AddressLine1'  => 'Unit 1, Eastman Road',
        'AddressLine2'  => 'Acton',
        'Region'        => '',
        'City'          => 'London',
        'Postcode'      => 'W3 7QS',
        'Country'       => 'United Kingdom',
        'Telephone'     => '0208 428 2832',
    ),
    'ShippingAddress'   => array
    (
        'Firstname'     => 'Latheesan',
        'Lastname'      => 'Kanes',
        'Company'       => 'Intelli B.I. Ltd',
        'AddressLine1'  => 'Unit 1, Eastman Road',
        'AddressLine2'  => 'Acton',
        'Region'        => '',
        'City'          => 'London',
        'Postcode'      => 'W3 7QS',
        'Country'       => 'United Kingdom',
        'Telephone'     => '0208 428 2832',
    ),
    'ShippingMethod'    => 'flatrate_flatrate',
    'PaymentMethod'     => 'checkmo'
));

?>

Also, this line isn't turning on email notification on order create:

// Configure Notification
$quote->setSendCconfirmation($orderData->SendConfirmation ? '1' : '0');

How do you enable email notification?

Regards

Best Answer

I believe you need to make your switch happen way sooner then you are, right after $app is checked for. Also, try converting the prices, and also testing that you have what you expect. Here are some things to get you rolling.

Convert Price from Current Currency to Base Currency and vice-versa

<?php
$baseCurrencyCode = Mage::app()->getStore()->getBaseCurrencyCode();
$currentCurrencyCode = Mage::app()->getStore()->getCurrentCurrencyCode();
$price = 100;

// convert price from current currency to base currency
$priceOne = Mage::helper('directory')->currencyConvert($price, $currentCurrencyCode, $baseCurrencyCode); 

// convert price from base currency to current currency
$priceTwo = Mage::helper('directory')->currencyConvert($price, $baseCurrencyCode, $currentCurrencyCode);
?>

Changing price from any one currency to another

<?php
$from = 'USD';
$to = 'NPR';
$price = 10;

$newPrice = Mage::helper('directory')->currencyConvert($price, $from, $to);
?>

Get Currency Rates

<?php
/**
 * Get the base currency
 */
$baseCurrencyCode = Mage::app()->getBaseCurrencyCode();

/**
 * Get all allowed currencies
 * returns array of allowed currency codes
 */
$allowedCurrencies = Mage::getModel('directory/currency')->getConfigAllowCurrencies();

/**
 * Get the currency rates
 * returns array with key as currency code and value as currency rate
 */
$currencyRates = Mage::getModel('directory/currency')->getCurrencyRates($baseCurrencyCode, array_values($allowedCurrencies));

$allowedCurrencies = Mage::getModel('directory/currency')->getConfigAllowCurrencies();

/**
 * Get currency rates for Nepalese Currency
 */
$currencyRates = Mage::getModel('directory/currency')->getCurrencyRates('NPR', array_values($allowedCurrencies));
?>