> ## 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.

# تسليم رموز البطاقات

> تسليم رموز بطاقات الإنترنت وتفاصيل المعاملات بأمان إلى العملاء

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

  بعد تنفيذ طلبات شحن الإنترنت، احصل على رموز البطاقات وأرقام المعاملات من API وسلّمها للعملاء بأمان. رموز البطاقات ذات قيمة ويجب التعامل معها بعناية.

  <Warning>
    **أمر بالغ الأهمية:** رموز البطاقات بيانات حساسة. شفّرها دائماً عند التخزين والإرسال.
  </Warning>

  ## بنية بيانات البطاقة

  الطلبات المنفَّذة تحتوي على ثلاثة حقول رئيسية:

  ```json theme={null}
  {
    "status": "FULFILLED",
    "card_code": "123456789012",
    "num_trans": "AT-2025-12345",
    "date_traitement": "2025-11-01T12:00:45.000Z"
  }
  ```

  * **card\_code :** رمز الشحن القابل للإدخال (المعرّف الرئيسي)
  * **num\_trans :** رقم معاملة اتصالات الجزائر (دليل الشراء)
  * **date\_traitement :** طابع التوقيت للمعالجة

  يجب تسليم الحقول الثلاثة للعميل.

  ## مرجع API

  <Card title="GET /v3/internet/check-id/{id}" icon="magnifying-glass" href="/ar/api-reference/internet/check-by-id">
    استرجاع تفاصيل البطاقة المنفَّذة
  </Card>

  ## التخزين الآمن

  شفّر رموز البطاقات دائماً قبل تخزينها:

  <CodeGroup>
    ```javascript Node.js theme={null}
    const crypto = require('crypto');

    const ENCRYPTION_KEY = process.env.ENCRYPTION_KEY; // Must be 32 bytes
    const ALGORITHM = 'aes-256-gcm';

    function encryptCardCode(code) {
      const iv = crypto.randomBytes(16);
      const cipher = crypto.createCipheriv(
        ALGORITHM,
        Buffer.from(ENCRYPTION_KEY, 'hex'),
        iv
      );

      let encrypted = cipher.update(code, 'utf8', 'hex');
      encrypted += cipher.final('hex');

      const authTag = cipher.getAuthTag();

      return {
        iv: iv.toString('hex'),
        encryptedData: encrypted,
        authTag: authTag.toString('hex')
      };
    }

    function decryptCardCode(iv, encryptedData, authTag) {
      const decipher = crypto.createDecipheriv(
        ALGORITHM,
        Buffer.from(ENCRYPTION_KEY, 'hex'),
        Buffer.from(iv, 'hex')
      );

      decipher.setAuthTag(Buffer.from(authTag, 'hex'));

      let decrypted = decipher.update(encryptedData, 'hex', 'utf8');
      decrypted += decipher.final('utf8');

      return decrypted;
    }

    // Store encrypted card
    async function storeCardSecurely(topupId, cardData) {
      const encrypted = encryptCardCode(cardData.card_code);

      await db.internetOrders.updateOne(
        { topupId },
        {
          $set: {
            status: 'FULFILLED',
            encryptedCard: encrypted,
            numTrans: cardData.num_trans,
            dateTraitement: cardData.date_traitement,
            fulfilledAt: new Date()
          }
        }
      );
    }
    ```

    ```python Python theme={null}
    from cryptography.hazmat.primitives.ciphers.aead import AESGCM
    import os
    import base64

    ENCRYPTION_KEY = bytes.fromhex(os.getenv('ENCRYPTION_KEY'))

    def encrypt_card_code(code):
        aesgcm = AESGCM(ENCRYPTION_KEY)
        nonce = os.urandom(12)
        encrypted = aesgcm.encrypt(nonce, code.encode('utf-8'), None)

        return {
            'nonce': base64.b64encode(nonce).decode('utf-8'),
            'encryptedData': base64.b64encode(encrypted).decode('utf-8')
        }

    def decrypt_card_code(nonce_b64, encrypted_data_b64):
        aesgcm = AESGCM(ENCRYPTION_KEY)
        nonce = base64.b64decode(nonce_b64)
        encrypted = base64.b64decode(encrypted_data_b64)
        decrypted = aesgcm.decrypt(nonce, encrypted, None)
        return decrypted.decode('utf-8')

    def store_card_securely(topup_id, card_data):
        encrypted = encrypt_card_code(card_data['card_code'])

        db.internet_orders.update_one(
            {'topupId': topup_id},
            {
                '$set': {
                    'status': 'FULFILLED',
                    'encryptedCard': encrypted,
                    'numTrans': card_data['num_trans'],
                    'dateTraitement': card_data['date_traitement'],
                    'fulfilledAt': datetime.now()
                }
            }
        )
    ```

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

    define('ENCRYPTION_KEY', getenv('ENCRYPTION_KEY'));
    define('CIPHER_ALGO', 'aes-256-gcm');

    function encryptCardCode($code) {
        $key = hex2bin(ENCRYPTION_KEY);
        $iv = random_bytes(16);
        $tag = '';

        $encrypted = openssl_encrypt(
            $code, CIPHER_ALGO, $key, OPENSSL_RAW_DATA, $iv, $tag, '', 16
        );

        return [
            'iv' => bin2hex($iv),
            'encryptedData' => bin2hex($encrypted),
            'authTag' => bin2hex($tag)
        ];
    }

    function decryptCardCode($ivHex, $encryptedHex, $authTagHex) {
        $key = hex2bin(ENCRYPTION_KEY);
        $decrypted = openssl_decrypt(
            hex2bin($encryptedHex), CIPHER_ALGO, $key, OPENSSL_RAW_DATA,
            hex2bin($ivHex), hex2bin($authTagHex)
        );

        if ($decrypted === false) {
            throw new Exception('Decryption failed');
        }
        return $decrypted;
    }
    ?>
    ```
  </CodeGroup>

  ## طرق التسليم

  ### 1. التسليم عبر البريد الإلكتروني

  ```javascript theme={null}
  async function deliverCardViaEmail(userId, topupId, cardData) {
    const user = await db.users.findOne({ _id: userId });

    await sendEmail({
      to: user.email,
      subject: 'Your Internet Card is Ready',
      html: `
        <h2>Your internet recharge card</h2>
        <p>Service: ${cardData.type}</p>
        <p>Number: ${cardData.number}</p>
        <p>Value: ${cardData.topup_amount} DA</p>
        
        <h3>Card Details:</h3>
        <p><strong>Card Code:</strong> ${cardData.card_code}</p>
        <p><strong>Transaction Number:</strong> ${cardData.num_trans}</p>
        <p><strong>Date:</strong> ${new Date(cardData.date_traitement).toLocaleString()}</p>
        
        <h3>How to Use:</h3>
        <p>1. Dial *600# from your ${cardData.type} line</p>
        <p>2. Select "Recharge"</p>
        <p>3. Enter the card code: ${cardData.card_code}</p>
      `
    });
  }
  ```

  ### 2. العرض داخل التطبيق

  ```javascript theme={null}
  app.get('/api/internet-orders/:topupId/card', authenticateUser, async (req, res) => {
    const { topupId } = req.params;
    const userId = req.user.id;

    // Verify ownership
    const order = await db.internetOrders.findOne({ topupId, userId });

    if (!order) return res.status(404).json({ error: 'Order not found' });
    if (order.status !== 'FULFILLED') {
      return res.status(400).json({ error: 'Order not fulfilled yet' });
    }

    const cardCode = decryptCardCode(
      order.encryptedCard.iv,
      order.encryptedCard.encryptedData,
      order.encryptedCard.authTag
    );

    res.json({
      topupId: order.topupId,
      type: order.type,
      cardCode,
      transactionNumber: order.numTrans,
      processedDate: order.dateTraitement,
      instructions: getCardUsageInstructions(order.type)
    });
  });

  function getCardUsageInstructions(type) {
    if (type === 'ADSL') {
      return [
        'Dial *600# from your ADSL line',
        'Select "Recharge"',
        'Enter the card code',
        'Confirm to add credit to your account'
      ];
    } else { // 4G
      return [
        'Dial *600# from your 4G device',
        'Select "Recharge"',
        'Enter the card code',
        'Your data will be activated immediately'
      ];
    }
  }
  ```

  ### 3. التسليم عبر SMS

  ```javascript theme={null}
  async function deliverCardViaSMS(phoneNumber, cardData) {
    const message = `Your ${cardData.type} card: ${cardData.card_code}\nTrans: ${cardData.num_trans}\nTo use: Dial *600#`;

    await sendSMS({ to: phoneNumber, message });
  }
  ```

  ## سير التسليم الكامل

  <CodeGroup>
    ```javascript Node.js theme={null}
    async function completeOrderDelivery(topupId, userId) {
      // 1. Get order details
      const order = await checkTopupStatus(topupId);

      if (order.status !== 'FULFILLED') {
        throw new Error('Order not ready for delivery');
      }

      // 2. Store encrypted card
      await storeCardSecurely(topupId, order);

      // 3. Deliver to customer
      await deliverCardViaEmail(userId, topupId, order);

      // 4. Log delivery (without sensitive data)
      await logCardDelivery(topupId, userId, 'email');

      console.log(`✅ Order ${topupId} delivery complete`);
    }
    ```

    ```python Python theme={null}
    async def complete_order_delivery(topup_id, user_id):
        # 1. Get order details
        order = check_topup_status(topup_id)

        if order['status'] != 'FULFILLED':
            raise ValueError('Order not ready for delivery')

        # 2. Store encrypted card
        store_card_securely(topup_id, order)

        # 3. Deliver to customer
        await deliver_card_via_email(user_id, topup_id, order)

        # 4. Log delivery (without sensitive data)
        await log_card_delivery(topup_id, user_id, 'email')

        print(f"✅ Order {topup_id} delivery complete")
    ```

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

    function completeOrderDelivery($topupId, $userId) {
        // 1. Get order details
        $order = checkTopupStatus($topupId);

        if ($order['status'] !== 'FULFILLED') {
            throw new Exception('Order not ready for delivery');
        }

        // 2. Store encrypted card
        storeCardSecurely($topupId, $order);

        // 3. Deliver to customer
        deliverCardViaEmail($userId, $topupId, $order);

        // 4. Log delivery (without sensitive data)
        logCardDelivery($topupId, $userId, 'email');

        error_log("✅ Order {$topupId} delivery complete");
    }
    ?>
    ```
  </CodeGroup>

  ## تسجيل التدقيق

  سجّل أحداث التسليم دون كشف بيانات البطاقة:

  ```javascript theme={null}
  async function logCardDelivery(topupId, userId, method) {
    await db.auditLogs.insertOne({
      event: 'CARD_DELIVERED',
      topupId,
      userId,
      method, // 'email', 'sms', 'in-app'
      timestamp: new Date(),
      ipAddress: req.ip,
      userAgent: req.headers['user-agent']
    });
    
    // ❌ NEVER log actual card codes
    // console.log('Card code:', card.card_code); // DON'T DO THIS
  }
  ```

  ## تعليمات الاستخدام حسب النوع

  قدّم تعليمات واضحة لكل نوع خدمة:

  ```javascript theme={null}
  function getCardUsageInstructions(type) {
    const instructions = {
      ADSL: {
        title: 'How to use your ADSL card',
        steps: [
          'Pick up your landline phone',
          'Dial *600#',
          'Select "Recharge" or "Flexy"',
          'Enter your card code: ${cardCode}',
          'Press # to confirm',
          'Your credit will be added immediately'
        ],
        support: 'For help, call 3003 from your ADSL line'
      },
      '4G': {
        title: 'How to use your 4G card',
        steps: [
          'Ensure your 4G SIM is active',
          'Dial *600# from your device',
          'Select "Recharge Internet"',
          'Enter your card code: ${cardCode}',
          'Press # to confirm',
          'Your data will be activated within minutes'
        ],
        support: 'For help, call 3003 from your mobile'
      }
    };
    
    return instructions[type];
  }
  ```

  ## قائمة التحقق الأمنية

  <Steps>
    <Step title="توليد مفتاح تشفير">
      أنشئ مفتاح تشفير آمن بطول 32 بايت وخزّنه في متغيرات البيئة
    </Step>

    <Step title="التشفير قبل التخزين">
      شفّر دائماً `card_code` قبل الإدراج في قاعدة البيانات
    </Step>

    <Step title="التحقق من الملكية">
      تأكد أن معرّف المستخدم يتطابق مع الطلب قبل عرض البطاقة
    </Step>

    <Step title="استخدام HTTPS">
      تأكد من أن جميع طرق التسليم تستخدم نقلاً مشفراً
    </Step>

    <Step title="تسجيل التدقيق">
      سجّل أحداث التسليم دون تضمين الرموز الفعلية
    </Step>

    <Step title="تعليمات واضحة">
      قدّم تعليمات استخدام خطوة بخطوة لكل نوع خدمة
    </Step>
  </Steps>

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

  <CardGroup cols={2}>
    <Card title="التشفير في حالة السكون" icon="lock">
      شفّر دائماً رموز البطاقة قبل تخزينها في قاعدة البيانات
    </Card>

    <Card title="HTTPS فقط" icon="shield-halved">
      لا ترسل بطاقات عبر اتصالات غير مشفرة
    </Card>

    <Card title="التحقق من الملكية" icon="user-lock">
      تحقق أن المستخدم يملك الطلب قبل عرض البطاقة
    </Card>

    <Card title="لا سجلات نصية" icon="file-slash">
      لا تسجّل رموز البطاقة كنص عادي في أي مكان
    </Card>

    <Card title="تضمين التعليمات" icon="book">
      قدّم دائماً تعليمات استخدام واضحة
    </Card>

    <Card title="سجل التدقيق" icon="clipboard-list">
      سجّل أحداث التسليم دون بيانات حساسة
    </Card>
  </CardGroup>

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

  ```javascript theme={null}
  async function deliverCardSafely(topupId, userId) {
    try {
      await completeOrderDelivery(topupId, userId);
      return { success: true };
    } catch (error) {
      console.error('Delivery failed:', error);
      
      if (error.message.includes('not ready')) {
        return {
          success: false,
          error: 'ORDER_NOT_READY',
          message: 'Order is still processing. Please wait.'
        };
      }
      
      if (error.message.includes('not found')) {
        return {
          success: false,
          error: 'ORDER_NOT_FOUND',
          message: 'Order not found or you do not have access to it.'
        };
      }
      
      return {
        success: false,
        error: 'DELIVERY_FAILED',
        message: 'Failed to deliver card. Please contact support.'
      };
    }
  }
  ```

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

  <CardGroup cols={3}>
    <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="shield" href="/ar/security-best-practices">
      إرشادات الأمان العامة
    </Card>

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

    <Card title="تحميل المنتجات" icon="list" href="/ar/internet-topup-guides/1-loading-products">
      جلب البطاقات المتاحة
    </Card>

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