> ## Documentation Index
> Fetch the complete documentation index at: https://docs.oneclickdz.com/llms.txt
> Use this file to discover all available pages before exploring further.

# تحميل منتجات الإنترنت

> جلب وتخزين مؤقت لبطاقات إنترنت ADSL و4G LTE المتاحة

<div dir="rtl">
  ## نظرة عامة

  يُرجع endpoint منتجات الإنترنت جميع بطاقات الإنترنت ADSL و4G LTE المتاحة مع أسعارها وقيمها. يُنصح بالتخزين المؤقت لبيانات المنتجات لتقليل استدعاءات API.

  <Info>
    خزّن بيانات المنتجات مؤقتاً لمدة **1-4 ساعات**. الأسعار والتوفر تتغير بصورة منتظمة.
  </Info>

  ## مرجع API

  <Card title="GET /v3/internet/products" icon="list" href="/ar/api-reference/internet/list-products">
    التوثيق الكامل للـ endpoint
  </Card>

  ## التحميل الأساسي للمنتجات

  <CodeGroup>
    ```javascript Node.js theme={null}
    async function loadInternetProducts(type) {
      const url = new URL('https://api.oneclickdz.com/v3/internet/products');
      if (type) url.searchParams.set('type', type);

      const response = await fetch(url.toString(), {
        headers: {
          "X-Access-Token": process.env.API_KEY,
        },
      });

      if (!response.ok) {
        throw new Error(`Failed to load products: ${response.status}`);
      }

      const result = await response.json();
      return result.data;
    }

    // Usage
    const adslProducts = await loadInternetProducts('ADSL');
    const products4G = await loadInternetProducts('4G');

    console.log(`ADSL products: ${adslProducts.length}`);
    console.log(`4G products: ${products4G.length}`);
    ```

    ```python Python theme={null}
    import requests
    import os

    def load_internet_products(product_type=None):
        params = {}
        if product_type:
            params['type'] = product_type

        response = requests.get(
            'https://api.oneclickdz.com/v3/internet/products',
            headers={'X-Access-Token': os.getenv('API_KEY')},
            params=params
        )

        response.raise_for_status()
        return response.json()['data']

    # Usage
    adsl_products = load_internet_products('ADSL')
    products_4g = load_internet_products('4G')

    print(f"ADSL products: {len(adsl_products)}")
    print(f"4G products: {len(products_4g)}")
    ```

    ```php PHP theme={null}
    <?php

    function loadInternetProducts($type = null) {
        $url = 'https://api.oneclickdz.com/v3/internet/products';
        if ($type) {
            $url .= '?type=' . urlencode($type);
        }

        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_HTTPHEADER, [
            'X-Access-Token: ' . getenv('API_KEY')
        ]);

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

        if ($httpCode !== 200) {
            throw new Exception("Failed to load products: " . $httpCode);
        }

        $result = json_decode($response, true);
        return $result['data'];
    }

    // Usage
    $adslProducts = loadInternetProducts('ADSL');
    $products4G = loadInternetProducts('4G');

    echo "ADSL products: " . count($adslProducts) . "\n";
    echo "4G products: " . count($products4G) . "\n";
    ?>
    ```

    ```bash cURL theme={null}
    # Load ADSL products
    curl "https://api.oneclickdz.com/v3/internet/products?type=ADSL" \
      -H "X-Access-Token: YOUR_API_KEY"

    # Load 4G products
    curl "https://api.oneclickdz.com/v3/internet/products?type=4G" \
      -H "X-Access-Token: YOUR_API_KEY"
    ```
  </CodeGroup>

  ## بنية الاستجابة

  ```json theme={null}
  {
    "success": true,
    "data": [
      {
        "value": 500,
        "cost": 450,
        "available": true
      },
      {
        "value": 1000,
        "cost": 900,
        "available": true
      },
      {
        "value": 500,
        "cost": 470,
        "available": false
      }
    ]
  }
  ```

  ## التخزين المؤقت للمنتجات

  <CodeGroup>
    ```javascript Node.js theme={null}
    class ProductCache {
      constructor(ttlMs = 2 * 60 * 60 * 1000) { // 2 hours
        this.cache = {};
        this.cachedAt = {};
        this.ttlMs = ttlMs;
      }

      isExpired(type) {
        if (!this.cachedAt[type]) return true;
        return Date.now() - this.cachedAt[type] > this.ttlMs;
      }

      async get(type) {
        if (this.isExpired(type)) {
          console.log(`Cache expired for ${type}, fetching fresh products...`);
          this.cache[type] = await loadInternetProducts(type);
          this.cachedAt[type] = Date.now();
        }
        return this.cache[type];
      }
    }

    const productCache = new ProductCache();

    // Usage
    const adslProducts = await productCache.get('ADSL');
    const products4G = await productCache.get('4G');
    ```

    ```python Python theme={null}
    import time

    class ProductCache:
        def __init__(self, ttl_seconds=7200):  # 2 hours
            self.cache = {}
            self.cached_at = {}
            self.ttl_seconds = ttl_seconds

        def is_expired(self, product_type):
            if product_type not in self.cached_at:
                return True
            return time.time() - self.cached_at[product_type] > self.ttl_seconds

        def get(self, product_type):
            if self.is_expired(product_type):
                print(f"Cache expired for {product_type}, fetching fresh products...")
                self.cache[product_type] = load_internet_products(product_type)
                self.cached_at[product_type] = time.time()
            return self.cache[product_type]

    product_cache = ProductCache()
    adsl_products = product_cache.get('ADSL')
    ```

    ```php PHP theme={null}
    <?php

    class ProductCache {
        private $cache = [];
        private $cachedAt = [];
        private $ttlSeconds;

        public function __construct($ttlSeconds = 7200) {
            $this->ttlSeconds = $ttlSeconds;
        }

        private function isExpired($type) {
            if (!isset($this->cachedAt[$type])) return true;
            return (time() - $this->cachedAt[$type]) > $this->ttlSeconds;
        }

        public function get($type) {
            if ($this->isExpired($type)) {
                $this->cache[$type] = loadInternetProducts($type);
                $this->cachedAt[$type] = time();
            }
            return $this->cache[$type];
        }
    }

    $productCache = new ProductCache();
    $adslProducts = $productCache->get('ADSL');
    ?>
    ```
  </CodeGroup>

  ## الحصول على المنتجات المتاحة

  <CodeGroup>
    ```javascript Node.js theme={null}
    function getAvailableProducts(products) {
      return products.filter(p => p.available);
    }

    // Usage
    const allProducts = await cache.get('ADSL');
    const available = getAvailableProducts(allProducts);

    console.log(`${available.length}/${allProducts.length} products in stock`);
    ```

    ```python Python theme={null}
    def get_available_products(products):
        return [p for p in products if p['available']]

    # Usage
    all_products = cache.get('ADSL')
    available = get_available_products(all_products)

    print(f"{len(available)}/{len(all_products)} products in stock")
    ```

    ```php PHP theme={null}
    <?php

    function getAvailableProducts($products) {
        return array_filter($products, function($p) {
            return $p['available'];
        });
    }

    // Usage
    $allProducts = $cache->get('ADSL');
    $available = array_values(getAvailableProducts($allProducts));

    echo count($available) . "/" . count($allProducts) . " products in stock\n";
    ?>
    ```
  </CodeGroup>

  ## تطبيق هامش الربح

  <CodeGroup>
    ```javascript Node.js theme={null}
    function applyMarkup(products, markupPercent = 5) {
      return products
        .filter(p => p.available)
        .map(p => ({
          value: p.value,
          wholesaleCost: p.cost,
          customerPrice: Math.ceil(p.cost * (1 + markupPercent / 100)),
          available: true,
        }));
    }

    // Usage
    const products = await cache.get('ADSL');
    const customerPrices = applyMarkup(products, 5); // 5% markup

    customerPrices.forEach(p => {
      console.log(`${p.value} DA card: ${p.customerPrice} DA`);
    });
    ```

    ```python Python theme={null}
    import math

    def apply_markup(products, markup_percent=5):
        available = [p for p in products if p['available']]
        
        return [
            {
                'value': p['value'],
                'wholesaleCost': p['cost'],
                'customerPrice': math.ceil(p['cost'] * (1 + markup_percent / 100)),
                'available': True
            }
            for p in available
        ]

    # Usage
    products = cache.get('ADSL')
    customer_prices = apply_markup(products, markup_percent=5)

    for p in customer_prices:
        print(f"{p['value']} DA card: {p['customerPrice']} DA")
    ```

    ```php PHP theme={null}
    <?php

    function applyMarkup($products, $markupPercent = 5) {
        $available = array_filter($products, function($p) {
            return $p['available'];
        });
        
        return array_map(function($p) use ($markupPercent) {
            return [
                'value' => $p['value'],
                'wholesaleCost' => $p['cost'],
                'customerPrice' => ceil($p['cost'] * (1 + $markupPercent / 100)),
                'available' => true
            ];
        }, $available);
    }

    // Usage
    $products = $cache->get('ADSL');
    $customerPrices = applyMarkup($products, 5);

    foreach ($customerPrices as $p) {
        echo "{$p['value']} DA card: {$p['customerPrice']} DA\n";
    }
    ?>
    ```
  </CodeGroup>

  ## أفضل الممارسات

  <CardGroup cols={2}>
    <Card title="التخزين المؤقت 5-10 دقائق" icon="clock">
      وازن بين التحديث وتقليل استدعاءات API
    </Card>

    <Card title="تصفية المتاح فقط" icon="filter">
      اعرض فقط المنتجات التي `available: true`
    </Card>

    <Card title="إخفاء أسعار الجملة" icon="eye-slash">
      لا تعرض قيم `cost` الخام للعملاء
    </Card>

    <Card title="معالجة الأخطاء بلطف" icon="triangle-exclamation">
      استخدم البيانات المخزنة مؤقتاً إذا كان API غير متاح مؤقتاً
    </Card>
  </CardGroup>

  ## بناء واجهة عرض المنتجات

  مثال على هيكل عرض المنتجات للعملاء:

  ```javascript theme={null}
  async function buildProductOptions(type, markupPercent = 5) {
    const products = await cache.get(type);
    
    return {
      serviceType: type,
      serviceName: type === 'ADSL' ? 'ADSL Internet' : '4G LTE Internet',
      options: products
        .filter(p => p.available)
        .map(p => ({
          value: p.value,
          label: `${p.value} DA`,
          price: Math.ceil(p.cost * (1 + markupPercent / 100)),
          inStock: true,
        }))
        .sort((a, b) => a.value - b.value)
    };
  }

  // Usage
  const adslOptions = await buildProductOptions('ADSL', 5);
  const lteOptions = await buildProductOptions('4G', 5);
  ```

  ## تحميل نوعَي الخدمة معاً

  استرجع منتجات ADSL و4G بالتوازي:

  ```javascript theme={null}
  async function loadAllInternetProducts() {
    const [adsl, lte] = await Promise.all([
      cache.get('ADSL'),
      cache.get('4G'),
    ]);
    
    return {
      adsl: applyMarkup(adsl, 5),
      lte: applyMarkup(lte, 5),
    };
  }

  // Usage
  const allProducts = await loadAllInternetProducts();
  console.log('ADSL:', allProducts.adsl.length, 'products');
  console.log('4G:', allProducts.lte.length, 'products');
  ```

  ## معالجة الأخطاء

  ```javascript theme={null}
  async function loadProductsSafely(type) {
    try {
      return await cache.get(type);
    } catch (error) {
      console.error(`Failed to load ${type} products:`, error);
      
      // Return stale cached data if available
      const cached = cache.cache.get(type);
      if (cached) {
        console.log('Using stale cached data');
        return cached.data;
      }
      
      throw new Error(`${type} products unavailable`);
    }
  }
  ```

  ## الخطوات التالية

  <CardGroup cols={3}>
    <Card title="التحقق من الأرقام" icon="check" href="/ar/internet-topup-guides/2-validation">
      التحقق من أرقام الهاتف قبل الإرسال
    </Card>

    <Card title="إرسال الشحنات" icon="satellite-dish" href="/ar/internet-topup-guides/3-sending-topups">
      تقديم طلبات الشحن
    </Card>

    <Card title="مرجع API" icon="book" href="/ar/api-reference/internet/list-products">
      التوثيق الكامل للـ endpoint
    </Card>

    <Card title="نظرة عامة" icon="book-open" href="/ar/internet-topup-guides/overview">
      العودة إلى نظرة عامة على التكامل
    </Card>

    <Card title="تتبع الحالة" icon="chart-line" href="/ar/internet-topup-guides/4-status-tracking">
      متابعة تنفيذ الطلبات
    </Card>

    <Card title="تسليم البطاقات" icon="file-code" href="/ar/internet-topup-guides/5-card-delivery">
      تسليم رموز البطاقات بأمان
    </Card>
  </CardGroup>
</div>
