0

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

1

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));
?>
1

You're going to need to do both

$quote->setBaseCurrencyCode($currencyCode);
$quote->setQuoteCurrencyCode($currencyCode);

You may want to checkout this magerun command that creates orders: https://github.com/kalenjordan/magerun-addons/blob/master/src/KJ/Magento/Command/Order/Create/Dummy.php#L178

See if it sets the currency properly from within your dev environment, and if it does, you should be able to follow that same recipe.

Disclaimer: There are still some things hard-coded in that command that should be cleaned up, but should be enough there for the currency to get set right.

0

You can emulate a certain store while processing the order. This will temporarely run Magento on a different store level using Euro. This Inchoo article will help give you the code to do so.

About sending emails. 'Confirmation' should only have 1 C, you've spelled it with two.

  • My stores aren't linked to the currencies (like my production environment) - so I can't really do this. Is there no other way of setting the currency on the order? – Latheesan Sep 14 '13 at 17:55
  • I dumped the $quote object to see what was in there and saw this: [global_currency_code] => GBP [base_currency_code] => GBP [store_currency_code] => GBP [quote_currency_code] => GBP [store_to_base_rate] => 1 [store_to_quote_rate] => 1 [base_to_global_rate] => 1 [base_to_quote_rate] => 1 So, I tried to set these value manually like so: $quote->setQuoteCurrencyCode($orderData->CurrencyCode; $quote->setStoreToQuoteRate($orderData->ExchangeRate); $quote->setBaseToQuoteRate($orderData->ExchangeRate); It doesn't work. It reverts back to GBP during quote save. – Latheesan Sep 14 '13 at 19:08
0

I had the same issue today. The solution for me was to use the following code:

$currency = Mage::getModel('directory/currency')->load('USD');
$quote->setForcedCurrency($currency);

This code will be use in the function \Mage_Sales_Model_Quote::_beforeSave and you currency will be used as intended.

The above code will use the USD currency for your order when you base currency is not USD.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.