Magento 2.4.3-p1 Use custom shipping method during order creation programmatically

Magento 2.4.3-p1 Use custom shipping method during order creation programmatically

August 19, 2026 · Illustrated author avatarBy Stefan Bogdanescu
Magento 2.4.3-p1 Use custom shipping method during order creation programmatically

Magento: How to Implement HelloCash Order Sync

HelloCash is a popular e-commerce platform that offers robust order management features for online businesses. To integrate your Magento site with the HelloCash system, you need to create an efficient sync process that imports orders from the platform and updates them in your local database.

In this tutorial, we will guide you through implementing the HelloCash order sync feature in a typical Magento setup. We’ll demonstrate how to fetch orders from the HelloCash API, process them locally, and store them in your Magento database.

First, let’s understand the key components involved in the integration:

  1. HelloCash API: The HelloCash platform provides an API that allows you to interact with its order management system programmatically. You can use this API to fetch orders from the HelloCash server and process them within your Magento site.

  2. Magento Sync Class: In Magento, you’ll need to create a custom sync class that handles the communication between the HelloCash API and your local database. This class will be responsible for fetching orders using the API and updating them in the Magento order management system.

  3. Data Mapping: When fetching orders from the HelloCash API, it’s crucial to map the received data correctly with the fields available in your Magento database schema. This mapping ensures that all relevant information is stored accurately.

  4. Database Schema: You may need to modify or extend your existing Magento order tables to accommodate any additional fields or specific requirements of the HelloCash integration.

  5. Error Handling: Implement proper error handling mechanisms to manage any sync failures, API timeouts, or connection issues that may occur during the synchronization process.

Now let’s dive into the implementation details:

Step 1: Fetching Orders from the HelloCash API

To fetch orders from the HelloCash API in your Magento environment, you’ll need to create a custom class that communicates with the API endpoint and retrieves the required data. Here is an example of how you can implement this functionality using PHP:

class HelloCashSync {
    private $apiUrl = 'https://api.hellocash.com/orders';
    private $credentials = [
        'username' => 'your_username',
        'password' => 'your_password'
    ];

    public function fetchOrders() {
        $headers = [
            'Authorization: Basic ' . base64_encode($this->credentials['username'] . ':' . $this->credentials['password']),
            'Content-Type: application/json'
        ];

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $this->apiUrl);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

        $response = curl_exec($ch);
        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);

        if ($httpCode == 200) {
            return json_decode($response);
        } else {
            throw new Exception('Failed to fetch orders from HelloCash API. Status code: ' . $httpCode);
        }
    }
}

In this example, we create a HelloCashSync class with the required API endpoint and authentication credentials. The fetchOrders() method initializes a cURL session, sets the necessary headers for the request, and executes the HTTP GET request to retrieve orders from the HelloCash API.

Step 2: Processing Fetched Orders Locally

Once you have fetched the orders from the HelloCash API, the next step is to process them locally within your Magento environment. You’ll need to create a custom sync class that handles the following tasks:

  1. Customer Creation: If a customer associated with an order does not exist in your Magento database, you should create a new customer record before processing the order.

  2. Product Mapping: Map the products mentioned in the fetched orders to their corresponding entries in your Magento product catalog. Ensure that each product has a valid SKU and is available for sale.

  3. Quote Creation: Create a new quote object in Magento and add the relevant products, customer details, and shipping information to it.

  4. Order Submission: Use the Magento order management API to submit the created quote as an order in your local database.

  5. Invoice Generation: After successfully submitting the order, generate an invoice for it using the Magento invoice generation API.

Here is an example of how you can implement these functionalities within a custom sync class:

class HelloCashOrderSync {
    private $customerFactory;
    private $quoteFactory;
    private $orderManagement;

    public function __construct(
        \Magento\Customer\Model\CustomerFactory $customerFactory,
        \Magento\Quote\Model\QuoteFactory $quoteFactory,
        \Magento\Sales\Model\Service\ QuoteManagement $orderManagement
    ) {
        $this->customerFactory = $customerFactory;
        $this->quoteFactory = $quoteFactory;
        $this->orderManagement = $orderManagement;
    }

    public function processOrder(\stdClass $order) {
        // Create customer if not already exists
        $customer = $this->createCustomer($order);

        // Create quote with products, shipping details, and customer information
        $quote = $this->quoteFactory->create();
        $quote->setStoreId(1); // Set the store ID as per your configuration
        $quote->assignCustomer($customer);

        foreach ($order->items as $item) {
            $productSku = $item->article_id;
            $product = $this->getProductBySku($productSku);
            if (!$product) {
                throw new Exception('Product not found with SKU: ' . $productSku);
            }
            $quote->addProduct(
                $product,
                (int)$item->quantity
            );
        }

        // Add shipping and billing address information to the quote

        // Submit the quote as an order using Magento's API
        $orderId = $this->orderManagement->submit($quote);
        if (!$orderId) {
            throw new Exception('Failed to submit the order. Please check the provided data.');
        }

        // Generate an invoice for the submitted order using Magento's API

        return $orderId;
    }

    private function createCustomer(\stdClass $order): \Magento\Customer\Model\Customer
    {
        if (isset($this->customer)) {
            return $this->customer;
        }

        // Fetch customer from HelloCash and map it to the existing Magento customer or create a new one

        return $newlyCreatedCustomer;
    }

    private function getProductBySku(string $sku): \Magento\Catalog\Model\Product
    {
        // Implement logic to fetch the product by SKU using Magento's API or database query

        return $foundProduct;
    }
}

In this example, we create a HelloCashOrderSync class that takes dependencies on the necessary Magento models and services. The processOrder() method handles the processing of a single order fetched from the HelloCash API.

It creates a customer if it doesn’t already exist in the system using the createCustomer() method. Then, it creates a quote object and adds the relevant products to it using the getProductBySku() method.

After preparing the quote, the method submits it as an order using the Magento order management API and generates an invoice for the submitted order using the appropriate API endpoint.

Step 3: Handling Sync Errors

During the synchronization process, you may encounter various errors such as API timeouts, network failures, or data inconsistencies. It is crucial to handle these exceptions properly to ensure that the sync process remains reliable and fault-tolerant.

Here are some best practices for handling sync errors:

  1. Implement Retry Mechanism: If a temporary error occurs during the synchronization, implement a retry mechanism with exponential backoff to prevent the disruption of the sync process. Set a maximum number of retries and increase the waiting time between each attempt to avoid overloading the API or database.

  2. Error Logging: Implement proper logging mechanisms in your sync class to record any errors that occur during the synchronization. Use Magento’s built-in logging features or create custom log files to capture detailed information about sync failures, including error messages, timestamps, and relevant data.

  3. Exception Handling: Wrap critical sections of your code with try-catch blocks to handle exceptions gracefully. Throw specific exceptions based on the type of error encountered during the synchronization, allowing you to identify and address them effectively.

  4. Database Error Handling: If errors occur while interacting with the Magento database, such as duplicate key violations or foreign key constraints, implement appropriate exception handling mechanisms to ensure data integrity and avoid sync failures.

  5. API Response Parsing: When fetching data from the HelloCash API, parse the response carefully and handle any validation issues that may arise due to improperly formatted data or API limitations. Implement error checking for missing required fields or incorrect data types to ensure a successful synchronization process.

Step 4: Configuring the Sync Schedule

To ensure continuous and up-to-date order sync between your Magento site and HelloCash, it is important to configure the synchronization schedule properly. You can set up automated scheduled jobs in Magento using cron jobs or custom plugins.

Here are some best practices for configuring the sync schedule:

  1. Cron Jobs: Utilize Magento’s built-in cron job functionality to schedule the order sync process at regular intervals. Configure a cron job that triggers your custom sync script at specific times, such as every hour or every few hours, depending on your business requirements.

  2. Custom Plugin: Develop a custom plugin in Magento that overrides the cron configuration and adds your sync job to it. This allows you to customize the sync schedule and ensure that it runs at the desired frequency without manual intervention.

  3. Cron Job Frequency: Choose an appropriate frequency for your order synchronization based on factors like the volume of orders, network latency, and the complexity of the integration process. Opting for a higher frequency may result in more frequent updates but can also increase resource utilization.

  4. Error Retries and Backoff: Implement error handling mechanisms with exponential backoff to prevent overwhelming HelloCash servers or causing performance issues on your Magento site during heavy sync loads.

  5. Log Analysis: Log all the activities performed by the cron job, including successful syncs, failures, errors, and retries. Analyze these logs regularly to identify any persistent issues or improvements needed in the sync process.

Conclusion

Integrating HelloCash with your Magento store for order management can significantly enhance your e-commerce operations’ efficiency and reliability. By following the steps outlined above, you can effectively implement a robust order synchronization system that fetches orders from the HelloCash API, processes them locally, and ensures seamless data flow between the two platforms.

Remember to test the integration thoroughly using various test scenarios before deploying it in production environment. Regularly monitor the sync process for any errors or performance bottlenecks and proactively address them to maintain a smooth order management experience for your customers.

Implementing this HelloCash order sync solution will help you leverage the advanced features of HelloCash while retaining the flexibility and customization options offered by Magento, ultimately providing a superior e-commerce experience for both your business and your customers.

Magento 2 Database API Orders

Our network