Retrieving Orders and Customers by Product ID in Magento 1.9
As an experienced developer taking on your first Magento project, let’s tackle this task step-by-step using the right tools and best practices. We’ll create a standalone PHP script that reads all orders from your Magento store, filters those containing product ID 297, and exports the customer and order information to a CSV file.
Setting Up Your Development Environment
Before diving into coding, ensure you have the necessary setup:
- Download and install XAMPP or another local server environment that supports PHP and MySQL.
- Install Magento 1.9 using the official guide: <https://developer.adobe.com/commerce/ magento-open-source/install-generic/setup/ step-step.html>
- Set up a database for your Magento instance.
Accessing Magento’s API via SOAP
Magento provides a SOAP-based web service interface (called WebAPI) that allows you to interact with the system programmatically. To retrieve order data, we’ll use the sales_order resource.
First, enable the WebAPI in your Magento configuration:
bin/magento module:enable Magento_Webapi
bin/magento setup:upgrade
Next, create a new user with API access and note down the consumer key and shared secret.
Writing the PHP Script
Create a get_orders.php file in your project root and include the necessary namespaces:
<?php
require_once 'app/bootstrap.php';
use Magento\Framework\App\Bootstrap;
use Magento\Framework\ObjectManagerFactory;
Initialize the Magento application object:
$bootstrap = Bootstrap::create(BP, $_SERVER);
$objectManager = $bootstrap->getObjectManager();
Create a function to fetch orders by product ID using Magento’s SOAP API client:
function getOrdersByProductId($product_id) {
global $objectManager;
// Create the SoapClient object
$soapClient = new \SoapClient('http://<your-magento-url>/index.php/api/v2_soapservice/?wsdl');
// Set the credentials for the API user
$sessionId = $soapClient->login('<api_user>', '<api_key>');
// Call the sales_order.list method to retrieve all orders
$orders = $soapClient->salesOrderList($sessionId);
$filteredOrders = [];
foreach ($orders['result']['items'] as $order) {
if (array_search($product_id, $order['products'])) {
$customerId = $order['customer_id'];
$filteredOrders[] = [
'order_id' => $order['entity_id'],
'customer_id' => $customerId,
'created_at' => $order['created_at'],
'grand_total' => $order['grand_total'],
];
}
}
return $filteredOrders;
}
Replace <api_user>, <api_key>, and <your-magento-url> with your actual Magento API user, key, and base URL.
Exporting Data to CSV
Write a function to export the filtered orders as a CSV file:
function exportToCsv($data, $fileName) {
// Open the output file for writing
$f = fopen($fileName, 'w');
if ($f !== FALSE) {
foreach ($data as $row) {
fputcsv($f, $row);
}
fclose($f);
} else {
echo "Unable to open the CSV file!";
}
}
Running the Script
Finally, call these functions in your get_orders.php script:
$productId = 297;
$filteredOrders = getOrdersByProductId($productId);
exportToCsv($filteredOrders, 'order_data.csv');
Run the script using PHP on your local server. It will create a order_data.csv file containing the required customer and order information.
Remember to handle any exceptions that might occur during API calls or file operations. You can expand this script further by adding headers to the CSV file or processing additional order-related data as needed.
For more advanced Magento development tasks, consider exploring the Laravel Company blog for in-depth tutorials and best practices.