Wie programmiere ich Bestellungen in Magento?

Manchmal müssen wir programmgesteuert Bestellungen in Magento erstellen. Angenommen, Sie erstellen ein Magento-Plugin für Ihr Geschäft, um es mit dem Marktplatz wie Walmart oder Etsy zu verbinden.

Schritte zum Erstellen von Aufträgen:

  • Wir definieren Kundendaten wie Vorname, Nachname, E-Mail.
  • Definieren Sie die Versand- und Rechnungsadresse des Kunden.
  • Versand- und Zahlungsart des Kunden festlegen.
  • Definieren Sie das Produkt und die Menge, die in unserem Magento Store bestellt werden muss.
  • Erstellen Sie einen Kunden, wenn der Kunde in unserem Magento-Shop nicht existiert. Es ist ein optionaler Schritt.
  • Produkt zum Angebot des Kunden hinzufügen.
  • Fügen Sie dem Angebot des Kunden die Versand- und Rechnungsadresse hinzu.
  • Angebot des Kunden erstellen und speichern.
  • Die Bestellung wird in Ihrem Magento-Shop erstellt.

Benutzen

         $ _store = Mage :: app () -> getStore (); $ _website = Mage :: app () -> getWebsite (); $ _firstName = John '; $ _lastName = 'doe; $ _email = 'demo@demo.com'; / * * Benutzerdefinierte Rechnungsadresse * / $ billingAddress = array ('customer_address_id' => '', 'prefix' => '', 'firstname' => $ _firstName, 'middlename' => '', 'lastname' => $ _lastName, 'suffix' => '', 'company' => '', 'street' => array ('0' => 'Sektor 63', // Erforderlich '1' => 'Noida, UP') , 'city' => 'Noida', 'country_id' => 'IN', // Ländercode 'region' => 'UP', 'region_id' => '', 'postcode' => '201301', ' Telefon '=>' 888-888-8888 ',' Fax '=>' ',' save_in_address_book '=> 1); / * * Benutzerdefinierte Versandadresse * / $ shippingAddress = array ('customer_address_id' => '', 'prefix' => '', 'firstname' => $ _firstName, 'middlename' => '', 'lastname' => $ _lastName, 'suffix' => '', 'company' => '', 'street' => array ('0' => 'Sektor 63', // Erforderlich '1' => 'Noida, UP') , 'city' => 'Noida', 'country_id' => 'IN', // Ländercode 'region' => 'UP', 'region_id' => '', 'postcode' => '201301', ' Telefon '=>' 888-888-8888 ',' Fax '=>' ',' save_in_address_book '=> 1); / ** * Geben Sie die Versandart ein, die Sie verwenden möchten. Einige der anderen Versandarten * sind tablerate_tablerate, freeshipping_freeshipping usw. * Hier verwenden wir flatrate_flatrate * / $ _shippingMethod = 'flatrate_flatrate'; / ** * Geben Sie die Zahlungsmethode ein, die Sie verwenden möchten. Einige der Zahlungsmethoden der Bestellung * sind checkmo, free, banktransfer, ccsave, purchaseorder usw. * / $ _paymentMethod = 'cashondelivery'; / ** * Geben Sie eine Reihe von Produkten und deren Menge an. * $ array = array (product_id => qty) * / $ productIds = array (905 => 1); $ quote = Mage :: getModel ('sales / quote') -> setStoreId ($ _ store-> getId ()); $ quote-> setCurrency (Mage :: app () -> getStore () -> getBaseCurrencyCode ()); $ customer = Mage :: getModel ('customer / customer') -> setWebsiteId ($ _ website-> getId ()) -> loadByEmail ($ _ email); / ** * Vorbereitung des Kunden auf das Angebot * Wenn der Kunde nicht registriert ist, legen wir einen neuen Kunden an. Dies ist ein optionaler Prozess. * / if (! $ customer-> getId ()) {$ customer = Mage :: getModel ('customer / customer'); $ customer-> setWebsiteId ($ _ website-> getId ()) -> setStore ($ _ store) -> setFirstname ($ _ firstName) -> setLastname ($ _ lastName) -> setEmail ($ _ email); / ** * Neuen Kunden anlegen * Wenn Sie keinen neuen Kunden anlegen möchten, überspringen Sie try-catch. * / try {// Passwort für Kunden generieren. Sie können dafür auch ein // benutzerdefiniertes Kennwort verwenden. $_store = Mage::app()->getStore();
         $_website = Mage::app()->getWebsite();
         $_firstName = John';
         $_lastName = 'doe;
         $_email = 'demo@demo.com';
        /*
         * Custom billing address
         */
        $billingAddress = array(
            'customer_address_id' => '',
                         'prefix' => '',
            'firstname' => $_firstName,
            'middlename' => '',
             'lastname' => $_lastName,
            'suffix' => '',
            'company' => '',
            'street' => array(
                 '0' => 'Sector 63', // Required
                '1' => 'Noida, UP' 
            ),
             'city' => 'Noida',
            'country_id' => 'IN', // Country code
            'region' => 'UP', 
            'region_id' => '',
            'postcode' => '201301',
            'telephone' => '888-888-8888',
            'fax' => '',
            'save_in_address_book' => 1
        );
 
        /*
         * Custom shipping address
         */
        $shippingAddress = array(
            'customer_address_id' => '',
            'prefix' => '',
            'firstname' => $_firstName,
            'middlename' => '',
            'lastname' => $_lastName,
            'suffix' => '',
            'company' => '',
            'street' => array(
                '0' => 'Sector 63', // Required
                '1' => 'Noida, UP' 
            ),
            'city' => 'Noida',
            'country_id' => 'IN', // Country code
            'region' => 'UP',
            'region_id' => '',
            'postcode' => '201301',
            'telephone' => '888-888-8888',
            'fax' => '',
            'save_in_address_book' => 1
        );
 
        /**
         * Enter the shipping method you want to use. Some of the other shipping
         * methods are tablerate_tablerate, freeshipping_freeshipping etc.
         * Here we are using flatrate_flatrate
         */
        $_shippingMethod = 'flatrate_flatrate';
 
        /**
         * Enter the payment method you want to use. Some of the order payment  
   	*methods are checkmo, free, banktransfer, ccsave, purchaseorder etc.
         */
        $_paymentMethod = 'cashondelivery';
 
        /**
         * Provide array of product and their qty.
         * $array = array(product_id => qty)
         */
        $productIds = array(905 => 1);
        $quote = Mage::getModel('sales/quote')
                ->setStoreId($_store->getId());
 
        $quote->setCurrency(Mage::app()->getStore()->getBaseCurrencyCode());
 
        $customer = Mage::getModel('customer/customer')
                ->setWebsiteId($_website->getId())
                ->loadByEmail($_email);
 
        /**
         * Preparing customer for the quote 
         * if the customer is not registered then we will create a new customer. This is  	*an optional process.
         */
        if (!$customer->getId()) {
            $customer = Mage::getModel('customer/customer');
 
            $customer->setWebsiteId($_website->getId())
                    ->setStore($_store)
                    ->setFirstname($_firstName)
                    ->setLastname($_lastName)
                    ->setEmail($_email);
 
            /**
             * Creating new customer
             * Skip try-catch if you don't want to create a new customer.
             */
            try {
                // Generating password for customer. You can also use any custom  // password for it.
                $password = $customer->generatePassword();
                $customer->setPassword($password);
                $customer->setForceConfirmed(true);
                $customer->save();
 
                $customer->setConfirmation(null);
                $customer->save();
                $customerId = $customer->getId();
                $customAddress = Mage::getModel('customer/address');
                $customAddress->setData($billingAddress)
                        ->setCustomerId($customerId)
                        ->setIsDefaultBilling('1')
                        ->setIsDefaultShipping('1')
                        ->setSaveInAddressBook('1');
                $customAddress->save();
 
            } catch (Mage_Core_Exception $e) {
                Mage::getSingleton('customer/session')->addException($e, $this- >__('Error in creating customer'));
                Mage::logException($e);
            } catch (Exception $e) {
                Mage::getSingleton('customer/session')->addException($e, $this- >__('Error in creating customer'));
                Mage::logException($e);
            }
        }
 
        // Assign customer to quote
        $quote->assignCustomer($customer);
 
        // Add products to quote
        foreach ($productIds as $productId => $qty) {
            $product = Mage::getModel('catalog/product')->load($productId);
            $quote->addProduct($product, $qty);
        }
 
        // Add billing address to quote
        $_billingAddressData = $quote->getBillingAddress()- >addData($billingAddress);
 
        // Add shipping address to quote
        $_shippingAddressData = $quote->getShippingAddress()- >addData($shippingAddress);
 
        /**
         * If the customer is a registered customer then you can fetch their billing or  *shipping address as below
         * 
         * $_customerBillingAddress = $customer->getPrimaryBillingAddress();
         * $_customerShippingAddress = $customer->getPrimaryShippingAddress();
         * 
         * $_billingAddressData = $quote->getBillingAddress()- >addData($_customerBillingAddress);
         * $_shippingAddressData = $quote->getShippingAddress()- >addData($_customerShippingAddress);
         */
 
        // Collect shipping rates on quote shipping address data
        $_shippingAddressData->setCollectShippingRates(true)
                ->collectShippingRates();
 
        // Set shipping and payment method on quote shipping address data
        $_shippingAddressData->setShippingMethod($_shippingMethod)
                ->setPaymentMethod($_paymentMethod);
 
        // Set payment method for the quote
        $quote->getPayment()->importData(array('method' => $_paymentMethod));
 
        try {
            $quote->collectTotals();
            $quote->save();
 
            // Preparing Order From Quote
            $service = Mage::getModel('sales/service_quote', $quote);
            $service->submitAll();
            
            // $incrementId is the increment id of the order created.
            $incrementId = $service->getOrder()->getRealOrderId();
 
            Mage::getSingleton('checkout/session')
                    ->setLastQuoteId($quote->getId())
                    ->setLastSuccessQuoteId($quote->getId())
                    ->clearHelperData();
 
           /*
           * $response is the Array of the response with the status of the order  creation.
           */
            $response['success'] = true;
            $response['error'] = false;
        $response['messages'] = 'Order number '.$incrementId.' created  successfully.';
        } catch (Mage_Core_Exception $e) {
            $response['success'] = false;
            $response['error'] = true;
            $response['messages'] = $e->getMessage();
            Mage::logException($e);
        } catch (Exception $e) {
            $response['success'] = false;
            $response['error'] = true;
            $response['messages'] = $this->__('Error in processing order. Please try  again later.');
 
            Mage::logException($e);
        }
        
        Mage::app()->getResponse()->setBody(Mage::helper('core')- >jsonEncode($response)); $ incrementId = $ service-> getOrder () -> getRealOrderId (); Mage :: getSingleton ('checkout / session') -> setLastQuoteId ($ quote-> getId ()) -> setLastSuccessQuoteId ($ quote-> getId ()) -> clearHelperData (); / * * $ response ist das Array der Antwort mit dem Status der Auftragserstellung. * / $ response ['success'] = true; $ response ['error'] = false; $ response ['messages'] = 'Bestellnummer'. $ incrementId. ' erfolgreich erstellt. '; } catch (Mage_Core_Exception $ e) {$ response ['success'] = false; $ response ['error'] = true; $ response ['messages'] = $ e-> getMessage (); Mage :: logException ($ e); } catch (Ausnahme $ e) {$ response ['success'] = false; $ response ['error'] = true; $ response ['messages'] = $ this -> __ ('Fehler beim Verarbeiten der Reihenfolge. Bitte versuchen Sie es später noch einmal. '); Mage :: logException ($ e); } Mage :: app () -> getResponse () -> setBody (Mage :: helper ('core') -> jsonEncode ($ response));

Bitte gehen Sie den oben genannten Code durch


Prashant Kumar

Prashant Kumar

Prashant is a passionate Magento developer. He loves exploring e-commerce and reading books.

Leave a Reply

Your email address will not be published. Required fields are marked *