PHPackages                             ekatra/product-sdk - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Utility &amp; Helpers](/categories/utility)
4. /
5. ekatra/product-sdk

ActiveLibrary[Utility &amp; Helpers](/categories/utility)

ekatra/product-sdk
==================

Ekatra Product SDK for PHP - Transform your product data into Ekatra Co-Deciding format

2.1.8(4mo ago)033MITPHPPHP &gt;=7.2CI passing

Since Sep 10Pushed 4mo agoCompare

[ Source](https://github.com/Ekatra-Global-Corp/ekatra-php-sdk)[ Packagist](https://packagist.org/packages/ekatra/product-sdk)[ RSS](/packages/ekatra-product-sdk/feed)WikiDiscussions main Synced 1mo ago

READMEChangelog (10)Dependencies (6)Versions (26)Used By (0)

Ekatra Product SDK for PHP
==========================

[](#ekatra-product-sdk-for-php)

A powerful PHP SDK for transforming your product data into the standardized Ekatra format. This SDK allows you to easily convert your existing product data structures into the Ekatra product format, making it simple to integrate with Ekatra's ecosystem.

Features
--------

[](#features)

- 🚀 **Smart Auto-Transformation** - Automatically converts simple data to complex Ekatra structure
- 🧠 **Intelligent Detection** - Detects data complexity and applies appropriate transformation
- 🔄 **Robust Field Mapping** - Maps 50+ field variations across different naming conventions
- ✅ **Educational Validation** - Clear error messages with actionable suggestions
- 🛠️ **Manual Setup Guide** - Step-by-step instructions for complex requirements
- 🎯 **Laravel Integration** - Full Laravel support with facades, commands, and service providers
- 🧪 **Customer Testing Tools** - Easy verification tools for customers
- 📚 **Comprehensive Documentation** - Complete guides, examples, and troubleshooting

Installation
------------

[](#installation)

### Via Composer

[](#via-composer)

```
composer require ekatra/product-sdk
```

### Laravel Integration

[](#laravel-integration)

The SDK automatically registers with Laravel. If you're using Laravel 5.5+, the service provider will be auto-discovered.

For older Laravel versions, add the service provider to `config/app.php`:

```
'providers' => [
    // ...
    Ekatra\Product\Laravel\ServiceProvider::class,
],
```

Quick Start
-----------

[](#quick-start)

### 🚀 Smart Flexible Transformation (v2.0.0 - RECOMMENDED)

[](#-smart-flexible-transformation-v200---recommended)

#### For Laravel Users (Option B - Recommended)

[](#for-laravel-users-option-b---recommended)

```
use Ekatra\Product\EkatraSDK;

class ProductController extends Controller
{
    public function getProduct($id)
    {
        $myProduct = Product::findOrFail($id);

        // One line transformation!
        $result = EkatraSDK::smartTransformProductFlexible($myProduct->toArray());

        if ($result['status'] === 'success') {
            // Apply your business rules (Option B)
            $limitedQuantityIds = [20051, 20052, 20053];
            if (in_array($result['data']['productId'], $limitedQuantityIds)) {
                $result['additionalInfo']['maxQuantity'] = 1;
            }

            return response()->json($result);
        }

        return response()->json(['status' => 'error'], 400);
    }
}
```

#### For Direct Usage

[](#for-direct-usage)

```
use Ekatra\Product\EkatraSDK;

// Your simple product data (any format)
$customerData = [
    'product_id' => 20051,
    'title' => 'Multicolor Gemstone Orb Earrings',
    'description' => 'Beautiful earrings with gemstones',
    'currency' => 'USD',
    'existing_url' => 'https://mystore.com/earrings',
    'product_keywords' => 'earrings,studs',
    'variant_name' => 'earrings',
    'variant_quantity' => 15,
    'variant_mrp' => 2257,
    'variant_selling_price' => 2118,
    'max_quantity' => 1,  // ✨ NEW: Set quantity limit for ready-to-ship products
    'image_urls' => 'url1,url2,url3'
];

// One line transformation with new v2.0.0 structure!
$result = EkatraSDK::smartTransformProductFlexible($customerData);

if ($result['status'] === 'success') {
    // Get your perfectly formatted Ekatra product
    $ekatraProduct = $result['data'];
    $maxQuantity = $result['metadata']['maxQuantity'];
    echo "✅ Auto-transformed successfully!";
    echo $maxQuantity ? "Max quantity: $maxQuantity" : "No quantity limit";
} else {
    // Get clear error guidance
    foreach ($result['metadata']['validation']['errors'] as $error) {
        echo "❌ $error";
    }
}
```

### 🔄 Product Sync Methods (NEW in v2.1.4)

[](#-product-sync-methods-new-in-v214)

For bulk product syncing to Ekatra APIs, use these methods to transform minimal product data into the standardized Ekatra format.

#### `syncProductData()` - Single Product (Returns Data Only)

[](#syncproductdata---single-product-returns-data-only)

Transforms a single product and returns just the product data array. Throws exception on validation failure.

**Required fields (flexible field names supported):**

- **productId**: `productId`, `product_id`, `id`, `item_id`, `sku`, `productCode`, etc.
- **title**: `title`, `name`, `product_name`, `product_title`, `productName`, etc.
- **currency**: `currency`, `currency_code`, `currencyCode`, `curr`, etc.
- **imageUrl**: `imageUrl`, `image_url`, `image_urls`, `images`, `thumbnail`, `photo`, `thumbnailUrl`, etc.

```
use Ekatra\Product\EkatraSDK;
use Ekatra\Product\Exceptions\EkatraValidationException;

try {
    // Accepts flexible field names
    $productData = [
        'product_id' => '20269',
        'title' => 'Geometric Rose Gold Diamond Stud Earrings',
        'currency' => 'INR',
        'image_urls' => 'https://example.com/image1.jpg,https://example.com/image2.jpg'
    ];

    // Returns just the product data (no wrapper)
    $transformedProduct = EkatraSDK::syncProductData($productData);

    // $transformedProduct contains complete Ekatra structure with defaults:
    // - productId, title, currency
    // - searchKeywords: ""
    // - specifications: []
    // - offers: [{productOfferDetails: [{}]}]
    // - variants: [{_id, color: "unknown", variations: [...], weight: 1, ...}]
    // - sizes: [{_id, name: "freestyle"}]

} catch (EkatraValidationException $e) {
    echo "Validation failed: " . $e->getMessage();
    print_r($e->getErrors());
}
```

#### `syncProductsBatch()` - Multiple Products (Batch Processing)

[](#syncproductsbatch---multiple-products-batch-processing)

Transforms multiple products and returns successful transformations and failures separately. Perfect for bulk operations.

```
use Ekatra\Product\EkatraSDK;

// Array of products (each with flexible field names)
$products = [
    [
        'product_id' => '20269',
        'title' => 'Product 1',
        'currency' => 'INR',
        'image_urls' => 'https://example.com/img1.jpg'
    ],
    [
        'productId' => '20270',
        'name' => 'Product 2',
        'currency_code' => 'USD',
        'images' => ['https://example.com/img2.jpg']
    ],
    [
        'title' => 'Invalid Product'  // Missing required fields
    ]
];

// Transform all products
$result = EkatraSDK::syncProductsBatch($products);

// Successful transformations
$successfulProducts = $result['successful'];
// Array of transformed product data

// Failed transformations (with original input for retry)
$failedProducts = $result['failed'];
// [
//   [
//     'index' => 2,
//     'input' => ['title' => 'Invalid Product', ...],
//     'error' => 'Product ID is required',
//     'validation' => ['errors' => [...], 'code' => 422]
//   ]
// ]

// Summary
$summary = $result['summary'];
// ['total' => 3, 'successful' => 2, 'failed' => 1]
```

#### Building Event Structure for API Sync

[](#building-event-structure-for-api-sync)

Use the batch method to transform products and build event structures for syncing to Ekatra APIs:

```
use Ekatra\Product\EkatraSDK;

// Step 1: Get raw products from your system
$rawProducts = [
    ['product_id' => '20269', 'title' => 'Product 1', 'currency' => 'INR', 'image_urls' => '...'],
    ['product_id' => '20270', 'title' => 'Product 2', 'currency' => 'INR', 'image_urls' => '...'],
    // ... more products
];

// Step 2: Transform all products
$result = EkatraSDK::syncProductsBatch($rawProducts);

// Step 3: Build event structure with successful products
$event = [
    'eventType' => 'PRODUCT_CREATE',
    'eventId' => 'evt_' . time(),
    'timestamp' => date('c'), // ISO 8601 format
    'products' => $result['successful']  // Only successful transformations
];

// Step 4: Send to Ekatra API
// sendToEkatraAPI($event);

// Step 5: Handle failures (log, notify, retry, etc.)
if (!empty($result['failed'])) {
    foreach ($result['failed'] as $failure) {
        // Log with original input for debugging/retry
        error_log("Product at index {$failure['index']} failed: {$failure['error']}");
        error_log("Original input: " . json_encode($failure['input']));

        // Optionally: Fix and retry
        // $fixed = fixProductData($failure['input']);
        // $retryResult = EkatraSDK::syncProductData($fixed);
    }
}

// Step 6: Report summary
echo "Processed: {$result['summary']['total']}\n";
echo "Successful: {$result['summary']['successful']}\n";
echo "Failed: {$result['summary']['failed']}\n";
```

#### `syncProduct()` - Single Product (With Response Wrapper)

[](#syncproduct---single-product-with-response-wrapper)

Returns the full ResponseBuilder format (status, data, metadata, message). Use this when you need validation details and error handling.

```
use Ekatra\Product\EkatraSDK;

$productData = [
    'productId' => '20269',
    'title' => 'Product Name',
    'currency' => 'INR',
    'imageUrl' => 'https://example.com/image.jpg'
];

$result = EkatraSDK::syncProduct($productData);

if ($result['status'] === 'success') {
    $product = $result['data'];
    $metadata = $result['metadata'];
    // Full response with validation details
} else {
    // Error response with validation details
    $errors = $result['metadata']['validation']['errors'];
}
```

#### Supported Input Formats

[](#supported-input-formats)

All sync methods accept flexible field names and handle various input formats:

**Field Name Variations:**

- **Product ID**: `productId`, `product_id`, `id`, `item_id`, `sku`, `productCode`, `product_code`, etc.
- **Title**: `title`, `name`, `product_name`, `product_title`, `productName`, `item_name`, etc.
- **Currency**: `currency`, `currency_code`, `currencyCode`, `curr`, `curr_code`, etc.
- **Image URL**: `imageUrl`, `image_url`, `image_urls`, `images`, `thumbnail`, `photo`, `thumbnailUrl`, `thumbnail_url`, etc.

**Nested Structures:**

```
// Handles nested structures automatically
$data = [
    'product_details' => [
        'product_id' => '123',
        'title' => 'Product',
        'currency' => 'USD',
        'image_url' => 'https://...'
    ]
];

// Also handles: 'product', 'data', 'result' keys
```

**Image Formats:**

```
// Single URL string
'imageUrl' => 'https://example.com/image.jpg'

// Comma-separated URLs (uses first)
'image_urls' => 'url1,url2,url3'

// Array of URLs (uses first)
'images' => ['url1', 'url2', 'url3']

// Array of objects
'images' => [
    ['url' => 'https://...'],
    ['src' => 'https://...']
]
```

### ⚠️ Legacy Method (DEPRECATED - Will be removed in v3.0.0)

[](#️-legacy-method-deprecated---will-be-removed-in-v300)

```
// ❌ DEPRECATED: Use smartTransformProductFlexible() instead
$result = EkatraSDK::smartTransformProduct($customerData);
```

### Manual Setup (For Complex Requirements)

[](#manual-setup-for-complex-requirements)

```
use Ekatra\Product\EkatraSDK;

// Create product manually
$product = EkatraSDK::product();
$product->setBasicInfo("PROD001", "My Product", "Description", "USD");
$product->setUrl("https://mystore.com/product");
$product->setKeywords(["jewelry", "ring"]);

// Create variant with variations
$variant = EkatraSDK::variant();
$variant->setBasicInfo("Gold Ring", 10, 1000, 800);
$variant->setColor("gold");

// Add variation
$variant->addVariation([
    'sizeId' => 'size-s',
    'mrp' => 1000,
    'sellingPrice' => 800,
    'availability' => true,
    'quantity' => 10,
    'size' => 'Small',
    'variantId' => 'var-001'
]);

// Add media
$variant->addMedia([
    'mediaType' => 'IMAGE',
    'playUrl' => 'https://example.com/image.jpg',
    'mimeType' => 'image/jpeg',
    'playerTypeEnum' => 'IMAGE'
]);

$product->addVariant($variant);
$product->addSize("size-s", "Small");

// Transform to Ekatra format
$result = $product->toEkatraFormatWithValidation();
```

### Basic Usage (Legacy)

[](#basic-usage-legacy)

```
use Ekatra\Product\EkatraSDK;

// Transform your product data
$customerData = [
    'id' => 'PROD001',
    'name' => 'Silver Ring',
    'description' => 'Beautiful silver ring',
    'url' => 'https://mystore.com/products/ring001',
    'keywords' => 'rings,silver,jewelry',
    'variants' => [
        [
            'name' => 'Silver Ring - Size 6',
            'price' => 850,
            'originalPrice' => 1000,
            'stock' => 25,
            'color' => 'Silver',
            'size' => '6',
            'images' => ['img1.jpg', 'img2.jpg']
        ]
    ]
];

$result = EkatraSDK::transformProduct($customerData);

if ($result['status'] === 'success') {
    echo "Transformation successful!";
    $ekatraFormat = $result['data'];
} else {
    echo "Transformation failed: " . $result['error'];
}
```

### Laravel Usage

[](#laravel-usage)

#### 🚀 Recommended: smartTransformProductFlexible (v2.0.0)

[](#-recommended-smarttransformproductflexible-v200)

```
use Ekatra\Product\EkatraSDK;

class ProductController extends Controller
{
    public function getProduct($id)
    {
        $myProduct = Product::findOrFail($id);

        // Transform using the new flexible method
        $result = EkatraSDK::smartTransformProductFlexible($myProduct->toArray());

        if ($result['status'] === 'success') {
            // Option B: Override maxQuantity based on business logic
            $limitedQuantityProductIds = [20051, 20052, 20053]; // Products with quantity limits

            if (in_array($result['data']['productId'], $limitedQuantityProductIds)) {
                $result['additionalInfo']['maxQuantity'] = 1;
            }

            return response()->json($result);
        } else {
            return response()->json([
                'status' => 'error',
                'message' => 'Product transformation failed',
                'additionalInfo' => $result['additionalInfo']
            ], 400);
        }
    }
}
```

#### 🎯 Advanced Laravel Implementation

[](#-advanced-laravel-implementation)

```
class ProductController extends Controller
{
    private $limitedQuantityProducts = [
        'premium' => [20051, 20052],
        'exclusive' => [30001, 30002],
        'limited_edition' => [40001, 40002, 40003],
    ];

    public function getProduct($id)
    {
        $myProduct = Product::findOrFail($id);
        $result = EkatraSDK::smartTransformProductFlexible($myProduct->toArray());

        if ($result['status'] === 'success') {
            // Apply business rules for quantity limits
            $this->applyQuantityLimits($result);

            // Add custom API fields
            $result['apiVersion'] = '2.0.0';
            $result['transformedAt'] = now()->toISOString();

            return response()->json($result);
        }

        return $this->handleTransformationError($result);
    }

    private function applyQuantityLimits(&$result)
    {
        $productId = $result['data']['productId'];

        foreach ($this->limitedQuantityProducts as $category => $ids) {
            if (in_array($productId, $ids)) {
                $result['additionalInfo']['maxQuantity'] =
                    ($category === 'limited_edition') ? 2 : 1;
                $result['additionalInfo']['productCategory'] = $category;
                break;
            }
        }
    }

    private function handleTransformationError($result)
    {
        return response()->json([
            'status' => 'error',
            'message' => 'Product transformation failed',
            'validation' => $result['metadata']['validation'] ?? null,
            'suggestions' => $result['metadata']['suggestions'] ?? []
        ], 400);
    }
}
```

#### ⚠️ Legacy Laravel Usage (DEPRECATED)

[](#️-legacy-laravel-usage-deprecated)

```
// ❌ DEPRECATED: Use smartTransformProductFlexible() instead
class ProductController extends Controller
{
    public function getProduct($id)
    {
        $myProduct = Product::findOrFail($id);
        $ekatraProduct = EkatraSDK::productFromData($myProduct->toArray());

        return response()->json($ekatraProduct->toEkatraFormatWithValidation());
    }
}
```

🚀 Flexible API Transformation (NEW in v1.1.0)
---------------------------------------------

[](#-flexible-api-transformation-new-in-v110)

The SDK now supports **flexible field mapping** that works with any API response format! This is the **recommended approach** for maximum compatibility.

### Supported API Formats

[](#supported-api-formats)

- **Shopify**: `{id, title, variants: [...], images: [...]}`
- **WooCommerce**: `{id, name, price, regular_price, tags: [...]}`
- **Magento**: `{id, name, custom_attributes: [...]}`
- **Generic E-commerce**: `{item_id, product_name, price, images: [...]}`
- **Minimal**: `{id, name, price}` (just the basics!)

### Flexible Transformation Methods

[](#flexible-transformation-methods)

#### `smartTransformProductFlexible()` - RECOMMENDED

[](#smarttransformproductflexible---recommended)

```
use Ekatra\Product\EkatraSDK;

// Works with ANY API format!
$result = EkatraSDK::smartTransformProductFlexible($customerData);

if ($result['status'] === 'success') {
    echo "✅ Transformation successful!";
    echo json_encode($result['data'], JSON_PRETTY_PRINT);
} else {
    echo "❌ Transformation failed:";
    foreach ($result['metadata']['validation']['errors'] as $error) {
        echo "- " . $error;
    }
}
```

#### `transformProductFlexible()` - ALIAS

[](#transformproductflexible---alias)

```
// Same as smartTransformProductFlexible() but shorter
$result = EkatraSDK::transformProductFlexible($customerData);
```

### Real-World Examples

[](#real-world-examples)

#### Shopify API Format

[](#shopify-api-format)

```
$shopifyData = [
    'id' => 123456789,
    'title' => 'Classic T-Shirt',
    'body_html' => 'Comfortable cotton t-shirt',
    'price' => '29.99',
    'compare_at_price' => '39.99',
    'variants' => [
        [
            'id' => 987654321,
            'title' => 'Small / Red',
            'price' => '29.99',
            'compare_at_price' => '39.99',
            'inventory_quantity' => 10
        ]
    ],
    'images' => [
        ['src' => 'https://cdn.shopify.com/tshirt-red.jpg']
    ]
];

$result = EkatraSDK::smartTransformProductFlexible($shopifyData);
// ✅ Works perfectly!
```

#### Minimal Format

[](#minimal-format)

```
$minimalData = [
    'id' => 999,
    'name' => 'Basic Product',
    'price' => 50.00
];

$result = EkatraSDK::smartTransformProductFlexible($minimalData);
// ✅ Works perfectly! Creates default variant automatically
```

### Migration from Old Methods

[](#migration-from-old-methods)

**⚡ Old way (DEPRECATED):**

```
$result = EkatraSDK::smartTransformProduct($customerData);
if ($result['status'] === 'success') { // Old boolean format
    $data = $result['data'];
}
```

**✅ New way (RECOMMENDED):**

```
$result = EkatraSDK::smartTransformProductFlexible($customerData);
if ($result['status'] === 'success') { // New string format
    $data = $result['data'];
    $validation = $result['metadata']['validation'];
    $maxQuantity = $result['metadata']['maxQuantity'];
}
```

### 🚀 Laravel Migration Guide

[](#-laravel-migration-guide)

**From Legacy Laravel Usage:**

```
// ❌ OLD: Manual product creation
$result = EkatraSDK::smartTransformProductFlexible($myProduct->toArray());
return response()->json($result);
```

**To New Flexible Approach:**

```
// ✅ NEW: One-line transformation with business logic
$result = EkatraSDK::smartTransformProductFlexible($myProduct->toArray());

if ($result['status'] === 'success') {
            // Apply your business rules
            if ($this->hasQuantityLimit($result['data']['productId'])) {
                $result['additionalInfo']['maxQuantity'] = 1;
            }

    return response()->json($result);
}
```

**Key Changes:**

- ✅ Use `smartTransformProductFlexible()` instead of manual product creation
- ✅ Check `$result['status'] === 'success'` instead of `$result['success']`
- ✅ Access validation via `$result['metadata']['validation']`
- ✅ Override `maxQuantity` in `$result['metadata']['maxQuantity']`

🛠️ Laravel Implementation Guide (Option B)
------------------------------------------

[](#️-laravel-implementation-guide-option-b)

### 🎯 Recommended Approach for Laravel Users

[](#-recommended-approach-for-laravel-users)

The **Option B** approach gives you complete control over quantity limits and business logic:

```
use Ekatra\Product\EkatraSDK;

class ProductController extends Controller
{
    public function getProduct($id)
    {
        $myProduct = Product::findOrFail($id);

        // Step 1: Transform using SDK
        $result = EkatraSDK::smartTransformProductFlexible($myProduct->toArray());

        if ($result['status'] === 'success') {
            // Step 2: Apply your business rules
            $this->applyBusinessRules($result);

            // Step 3: Return customized response
            return response()->json($result);
        }

        return $this->handleError($result);
    }

    private function applyBusinessRules(&$result)
    {
        $productId = $result['data']['productId'];

        // Your quantity limit business logic
        if ($this->hasQuantityLimit($productId)) {
            $result['additionalInfo']['maxQuantity'] = 1;
            $result['additionalInfo']['quantityStatus'] = 'limited';
        }

        // Add custom fields for your API
        $result['additionalInfo']['apiVersion'] = '2.0.0';
        $result['additionalInfo']['processedAt'] = now()->toISOString();
    }

    private function hasQuantityLimit($productId)
    {
        $limitedQuantityIds = [20051, 20052, 20053, 20054];
        return in_array($productId, $limitedQuantityIds);
    }
}
```

### 🚀 Benefits of Option B

[](#-benefits-of-option-b)

- ✅ **Complete Control** - You decide which products have quantity limits
- ✅ **Dynamic Configuration** - Easy to update business rules
- ✅ **No Data Changes** - No need to modify your product database
- ✅ **API Flexibility** - Customize response for your frontend needs
- ✅ **Easy Testing** - Simple to test different scenarios
- ✅ **Business Logic Separation** - Keep quantity rules separate from product data

🛠️ Response Modification (Option B)
-----------------------------------

[](#️-response-modification-option-b)

You can easily customize the response for your API needs:

### Basic Response Modification

[](#basic-response-modification)

```
use Ekatra\Product\EkatraSDK;

$result = EkatraSDK::smartTransformProductFlexible($customerData);

if ($result['status'] === 'success') {
    // Modify the response as needed
    $result['message'] = "Custom success message for API";
    $result['additionalInfo']['maxQuantity'] = 1; // Override quantity limit
    $result['additionalInfo']['customField'] = "Custom value";

    return $result; // Return modified response
} else {
    return [
        'status' => 'error',
        'message' => 'Custom error message for API',
        'additionalInfo' => $result['additionalInfo']
    ];
}
```

### Advanced Response Customization

[](#advanced-response-customization)

```
function transformProductForApi($customerData, $maxQuantity = null, $customMessage = null) {
    $result = EkatraSDK::smartTransformProductFlexible($customerData);

    // Extract core data
    $data = $result['data'];
    $validation = $result['metadata']['validation'];
    $dataType = $result['additionalInfo']['dataType'];

    // Build custom response
    return [
        'status' => 'success',
        'data' => $data,
        'additionalInfo' => [
            'validation' => $validation,
            'dataType' => $dataType,
            'maxQuantity' => $maxQuantity ?? $result['additionalInfo']['maxQuantity'],
            'apiVersion' => '2.0.0',
            'transformedAt' => date('Y-m-d H:i:s'),
            'customField' => 'Your custom value'
        ],
        'message' => $customMessage ?? $result['message']
    ];
}

// Usage
$apiResponse = transformProductForApi($customerData, 1, "Product with quantity limit applied");
```

### Utility Methods

[](#utility-methods)

```
// Check if data can be auto-transformed
$canTransform = EkatraSDK::canAutoTransformFlexible($customerData);

// Get supported API formats
$formats = EkatraSDK::getSupportedApiFormats();
// Returns: ['shopify' => '...', 'WooCom' => '...', etc.]
```

API Reference
-------------

[](#api-reference)

### Smart Transformation Methods

[](#smart-transformation-methods)

#### Flexible API Transformation (RECOMMENDED for v1.1.0+)

[](#flexible-api-transformation-recommended-for-v110)

```
// NEW: Flexible transformation - works with ANY API format
$result = EkatraSDK::smartTransformProductFlexible($customerData);

// Alias for convenience
$result = EkatraSDK::transformProductFlexible($customerData);

// Check if data can be auto-transformed with flexible transformer
$canTransform = EkatraSDK::canAutoTransformFlexible($customerData);

// Get supported API formats
$formats = EkatraSDK::getSupportedApiFormats();
```

#### Legacy Methods (Still Supported)

[](#legacy-methods-still-supported)

```
// ❌ DEPRECATED: Original smart transformation (legacy)
$result = EkatraSDK::smartTransformProduct($customerData);

// ❌ DEPRECATED: Check if data can be auto-transformed with old transformer
$canTransform = EkatraSDK::canAutoTransform($customerData);

// ❌ DEPRECATED: Get educational validation
$validation = EkatraSDK::getEducationalValidation($customerData);

// ❌ DEPRECATED: Get manual setup guide
$guide = EkatraSDK::getManualSetupGuide();

// ❌ DEPRECATED: Get code examples
$examples = EkatraSDK::getCodeExamples();

// ❌ DEPRECATED: Get troubleshooting guide
$troubleshooting = EkatraSDK::getTroubleshootingGuide();
```

### Core Classes

[](#core-classes)

#### EkatraProduct

[](#ekatraproduct)

The main product class for handling complete product information.

```
use Ekatra\Product\Core\EkatraProduct;

$product = new EkatraProduct();
$product->setBasicInfo('PROD001', 'Product Title', 'Description', 'INR')
        ->setUrl('https://example.com/product')
        ->setKeywords(['keyword1', 'keyword2'])
        ->addVariant($variant);
```

#### EkatraVariant

[](#ekatravariant)

Handles individual product variants.

```
use Ekatra\Product\Core\EkatraVariant;

$variant = new EkatraVariant();
$variant->setBasicInfo('Variant Name', 10, 100, 90)
        ->setAttributes('Red', 'M')
        ->setMedia(['image1.jpg'], ['video1.mp4']);
```

### SDK Methods

[](#sdk-methods)

#### EkatraSDK::transformProduct(array $data)

[](#ekatrasdktransformproductarray-data)

Transforms customer product data to Ekatra format.

**Parameters:**

- `$data` (array) - Customer product data

**Returns:**

```
[
    'success' => true|false,
    'data' => array|null,
    'validation' => [
        'valid' => true|false,
        'errors' => array
    ],
    'error' => string|null
]
```

#### EkatraSDK::validateProduct(array $data)

[](#ekatrasdkvalidateproductarray-data)

Validates customer product data without transformation.

**Parameters:**

- `$data` (array) - Customer product data

**Returns:**

```
[
    'valid' => true|false,
    'errors' => array
]
```

Field Mapping
-------------

[](#field-mapping)

The SDK automatically maps various field names to the Ekatra format:

### Product Fields

[](#product-fields)

Ekatra FieldMapped From`productId``id`, `sku`, `product_id`, `item_id``title``name`, `title`, `product_name`, `item_name``description``desc`, `description`, `details`, `summary``existingUrl``url`, `productUrl`, `product_url`, `link``keywords``keywords`, `searchKeywords`, `tags`### Variant Fields

[](#variant-fields)

Ekatra FieldMapped From`name``name`, `title`, `variant_name`, `item_name``color``color`, `colour`, `variant_color`, `item_color``size``size`, `variant_size`, `item_size``quantity``quantity`, `stock`, `available`, `inventory``mrp``mrp`, `originalPrice`, `listPrice`, `price_original``sellingPrice``price`, `salePrice`, `current_price`, `sale_price`Testing
-------

[](#testing)

The SDK includes comprehensive testing tools for customers.

### Quick Test

[](#quick-test)

```
# Test with sample data using the customer guide
php customer_test_guide.md
```

### Customer Testing Guide

[](#customer-testing-guide)

The `customer_test_guide.md` file provides comprehensive testing instructions:

1. **Simple Data Test** - Tests auto-transformation
2. **Complex Data Test** - Tests complex structure handling
3. **Invalid Data Test** - Tests error handling
4. **Manual Setup Test** - Tests manual product creation

### Laravel Testing

[](#laravel-testing)

```
# Test mapping with Artisan command
php artisan ekatra:test-mapping

# Test with custom data file
php artisan ekatra:test-mapping --file=path/to/test-data.json

# Test with JSON string
php artisan ekatra:test-mapping --data='{"id":"PROD001","name":"Test Product"}'

# Test only variants
php artisan ekatra:test-mapping --variant

# Test with validation
php artisan ekatra:test-mapping --validate

# Show formatted output
php artisan ekatra:test-mapping --format
```

### Test Endpoints

[](#test-endpoints)

The SDK provides test endpoints for easy testing:

```
# Test product mapping
POST /ekatra/test/product
Content-Type: application/json

{
    "id": "PROD001",
    "name": "Test Product",
    "description": "Test Description",
    "variants": [...]
}

# Test variant mapping
POST /ekatra/test/variant
Content-Type: application/json

{
    "name": "Test Variant",
    "price": 100,
    "stock": 10
}

# Get sample data
GET /ekatra/test/sample
```

Configuration
-------------

[](#configuration)

Publish the configuration file:

```
php artisan vendor:publish --tag=ekatra-config
```

This creates `config/ekatra.php` with customizable settings:

```
return [
    'default_currency' => 'INR',
    'supported_currencies' => ['INR', 'USD', 'EUR', 'GBP'],
    'validation' => [
        'strict_mode' => false,
        'log_errors' => true,
    ],
    // ... more options
];
```

Error Handling
--------------

[](#error-handling)

The SDK provides flexible error handling:

### Validation Errors

[](#validation-errors)

```
$result = EkatraSDK::transformProduct($data);

if ($result['status'] !== 'success') {
    if (isset($result['validation']['errors'])) {
        foreach ($result['validation']['errors'] as $error) {
            echo "Validation Error: $error\n";
        }
    }
}
```

### Exceptions

[](#exceptions)

```
use Ekatra\Product\Exceptions\EkatraValidationException;

try {
    $product = EkatraSDK::productFromData($data);
    $ekatraFormat = $product->toEkatraFormat();
} catch (EkatraValidationException $e) {
    echo "Validation failed: " . $e->getMessage();
    $errors = $e->getErrors();
}
```

Examples
--------

[](#examples)

### Complete Product Example

[](#complete-product-example)

```
use Ekatra\Product\EkatraSDK;

$customerData = [
    'id' => 'PROD001',
    'name' => 'Premium Silver Ring',
    'description' => 'High-quality silver ring with premium finish',
    'url' => 'https://mystore.com/products/ring001',
    'keywords' => 'rings,silver,jewelry,premium',
    'currency' => 'INR',
    'specifications' => [
        ['key' => 'Material', 'value' => 'Premium Silver Alloy'],
        ['key' => 'Weight', 'value' => '250g']
    ],
    'offers' => [
        [
            'title' => 'Special Offer',
            'productOfferDetails' => [
                [
                    'title' => 'SAVE20',
                    'description' => '20% off on all silver jewelry'
                ]
            ]
        ]
    ],
    'variants' => [
        [
            'name' => 'Silver Ring - Size 6',
            'price' => 850,
            'originalPrice' => 1000,
            'stock' => 25,
            'color' => 'Silver',
            'size' => '6',
            'images' => ['img1.jpg', 'img2.jpg'],
            'videos' => ['video1.mp4']
        ]
    ]
];

$result = EkatraSDK::transformProduct($customerData);

if ($result['status'] === 'success') {
    $ekatraFormat = $result['data'];
    // Use the transformed data
} else {
    // Handle errors
    $errors = $result['validation']['errors'] ?? [];
}
```

### Laravel Controller Example

[](#laravel-controller-example)

```
class ProductController extends Controller
{
    public function getProduct($id)
    {
        try {
            $product = Product::findOrFail($id);
            $result = EkatraSDK::smartTransformProductFlexible($product->toArray());
            return response()->json($result);
        } catch (\Exception $e) {
            return response()->json([
                'status' => 'error',
                'data' => null,
                'metadata' => ['validation' => ['valid' => false, 'errors' => [$e->getMessage()]]],
                'message' => 'Product transformation failed'
            ], 500);
        }
    }
}
```

Requirements
------------

[](#requirements)

- PHP 8.1 or higher
- Composer
- Laravel 9+ (for Laravel integration)

Dependencies
------------

[](#dependencies)

- Guzzle HTTP (for future API features)
- Illuminate Support (for Laravel integration)
- Illuminate Validation (for validation features)

Contributing
------------

[](#contributing)

1. Fork the repository
2. Create a feature branch
3. Make your changes
4. Add tests
5. Submit a pull request

License
-------

[](#license)

This SDK is licensed under the MIT License. See the LICENSE file for details.

Support
-------

[](#support)

For support and questions:

- Email:

Changelog
---------

[](#changelog)

### Version 1.0.0

[](#version-100)

- Initial release
- Core product and variant classes
- Smart field mapping
- Comprehensive validation
- Laravel integration
- Testing tools
- Documentation and examples

### Version 1.0.1

[](#version-101)

- Fixed default size to 'freestyle' for consistency
- Improved sizeId linking between variations and sizes arrays
- Enhanced SmartTransformer size matching logic

### Version 1.0.2

[](#version-102)

- Fixed discount calculation for simple variant data
- Added missing discount logic to transformSimpleToComplex method
- Ensures all transformation paths calculate discounts correctly

### Version 2.0.0 - V2 API STRUCTURE &amp; QUANTITY FIXES 🚀

[](#version-200---v2-api-structure--quantity-fixes-)

#### ✨ New Features

[](#-new-features)

- **Flattened Response Structure**: Moved validation metadata into `additionalInfo` object
- **Status Field Enhancement**: Changed `success: boolean` → `status: string`
- **MaxQuantity Support**: New `maxQuantity` field in `additionalInfo` for quantity limits
- **Media Object Alignment**: Updated `mediaList` → `media`, `mediaType` → `type`, `playUrl` → `url`
- **Thumbnail Enhancement**: Added `thumbnailUrl` field within media objects
- **Quantity Bug Fix**: Fixed issue where `quantity` was showing 0 instead of actual input values

#### 🛠️ Response Structure Changes

[](#️-response-structure-changes)

- **Old Structure**: `{success: true, data: {...}, validation: {...}}`
- **New Structure**: `{status: "success", data: {...}, metadata: {validation: {...}, maxQuantity: number, sdkVersion: "2.0.5"}}`

#### 🔧 New Methods

[](#-new-methods)

- `extractMaxQuantity()` - Extracts quantity limits from input data
- Enhanced `smartTransformProductFlexible()` - Now returns v2.0.0 structure

### Version 1.0.5 - FLEXIBLE API TRANSFORMATION (PREVIOUS)

[](#version-105---flexible-api-transformation-previous)

#### ✨ New Features

[](#-new-features-1)

- **Flexible API Transformation**: New `smartTransformProductFlexible()` method that works with ANY API format
- **Multi-Platform Support**: Handles Shopify, WooCommerce, Magento, and generic e-commerce formats
- **Smart Field Mapping**: Automatically maps 50+ field variations across different naming conventions
- **Nested Data Extraction**: Handles complex nested structures like `{success: true, product_details: {...}}`
- **Default Variant Creation**: Creates sensible defaults for minimal data formats
- **Backward Compatibility**: All existing methods continue to work unchanged

#### 🔧 New Methods

[](#-new-methods-1)

- `EkatraSDK::smartTransformProductFlexible($data)` - **RECOMMENDED** for new implementations
- `EkatraSDK::transformProductFlexible($data)` - Alias for convenience
- `EkatraSDK::canAutoTransformFlexible($data)` - Check transformation capability
- `EkatraSDK::getSupportedApiFormats()` - List supported API formats

#### 🛠️ Technical Improvements

[](#️-technical-improvements)

- **PSR-4 Autoloading**: Fixed autoloader configuration for better compatibility
- **Enhanced Validation**: More flexible validation with smart defaults
- **Better Error Handling**: Clearer error messages and suggestions
- **CI/CD Pipeline**: Added GitHub Actions for automated testing

#### 📚 Documentation

[](#-documentation)

- Updated README with comprehensive examples for all supported formats
- Added migration guide for existing users
- Real-world examples for each API format

#### 🔧 Technical Improvements

[](#-technical-improvements)

- **PSR-4 Autoloading**: Fixed autoloader configuration for better compatibility
    - **Migration**: Run `composer dump-autoload` after updating
    - **Impact**: None - backward compatible, just better autoloading

###  Health Score

34

—

LowBetter than 77% of packages

Maintenance74

Regular maintenance activity

Popularity7

Limited adoption so far

Community8

Small or concentrated contributor base

Maturity40

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 98.2% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~3 days

Total

25

Last Release

149d ago

Major Versions

1.0.11 → 2.0.02025-10-03

PHP version history (4 changes)v1.0.1PHP ^8.1

1.0.3PHP ^7.4|^8.0|^8.1|^8.2|^8.3

1.0.4PHP &gt;=7.4

1.0.6PHP &gt;=7.2

### Community

Maintainers

![](https://www.gravatar.com/avatar/2885b3b538b0add05f1ac07745191947bc64230dc12ffa7dc1a6c6776bc09e7b?d=identicon)[ekatraglobalcorp](/maintainers/ekatraglobalcorp)

---

Top Contributors

[![amit-tgml](https://avatars.githubusercontent.com/u/271157394?v=4)](https://github.com/amit-tgml "amit-tgml (55 commits)")[![MBEkatra](https://avatars.githubusercontent.com/u/204723360?v=4)](https://github.com/MBEkatra "MBEkatra (1 commits)")

---

Tags

data-trecomlaravelphpsdk

###  Code Quality

TestsPHPUnit

### Embed Badge

![Health badge](/badges/ekatra-product-sdk/health.svg)

```
[![Health](https://phpackages.com/badges/ekatra-product-sdk/health.svg)](https://phpackages.com/packages/ekatra-product-sdk)
```

###  Alternatives

[aedart/athenaeum

Athenaeum is a mono repository; a collection of various PHP packages

255.2k](/packages/aedart-athenaeum)[bensampo/laravel-embed

Painless responsive embeds for videos, slideshows and more.

142146.8k](/packages/bensampo-laravel-embed)[glhd/conveyor-belt

14797.0k](/packages/glhd-conveyor-belt)[ankurk91/laravel-ses-webhooks

Handle AWS SES webhooks in Laravel php framework

2534.2k](/packages/ankurk91-laravel-ses-webhooks)[wearepixel/laravel-cart

A cart implementation for Laravel

1310.5k](/packages/wearepixel-laravel-cart)[roomies/phonable

Gather insights and verify phone numbers from multiple third-party providers.

123.5k](/packages/roomies-phonable)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
