---
title: "أمثلة كود لصيغتي Reward وInterstitial"
description: "أمثلة كود AdsGram لصيغتي Reward وInterstitial في React وUnity وجافاسكريبت الخالصة، تشمل الخطافات ومكونات الأزرار."
outline: [2,3]
---
# أمثلة على الكود

- صيغة **Rewarded**، والتي تعني أنه يجب عليك منح المستخدم مكافأة عندما يشاهد الإعلان حتى النهاية ويجب أن يكون الإعلان متوقعاً مثل بعد النقر على عنصر.\
مزيد من المعلومات حول [متطلبات عرض الإعلان](./reward-examples#متطلبات-عرض-الإعلان).
- صيغة **Interstitial**، والتي تعني أنه يمكن للمستخدم تخطي إعلان قبل النهاية ويجب أن يكون الإعلان متوقعاً أثناء التوقفات الطبيعية في تدفق التطبيق\
مزيد من المعلومات حول [متطلبات عرض الإعلان](./interstitial-examples#متطلبات-عرض-الإعلان).

::: info معلومات
أدناه أمثلة على الكود لصيغة Rewarded. هذه الأمثلة تنطبق أيضاً على صيغة Interstitial. الفرق الوحيد هو أن وعد AdController.show() يتم حله للإعلانات التي تمت مشاهدتها حتى النهاية وتلك التي تم إغلاقها. اطلع على [مثال كود بسيط لصيغة Interstitial](./interstitial-examples#مثال-بسيط-على-الكود).
:::

## React
### إدراج السكريبت
أدرج هذا [السكريبت](./reward-interstitial-integration#إدراج-السكريبت) داخل وسم `<head>` في HTML الخاص بك.

### إنشاء useAdsgram hook
أنشئ ملفاً داخل مشروعك مع custom hook `useAdsgram`.\
مزيد من المعلومات حول custom hooks في [وثائق React](https://react.dev/learn/reusing-logic-with-custom-hooks).

::: code-group
```javascript [useAdsgram.js]
import { useCallback, useEffect, useRef } from 'react';

export function useAdsgram({ blockId, onReward, onError }) {
  const AdControllerRef = useRef(undefined);

  useEffect(() => {
    AdControllerRef.current = window.Adsgram?.init({ blockId });
  }, [blockId]);

  return useCallback(async () => {
    if (AdControllerRef.current) {
      return AdControllerRef.current
        .show()
        .then(() => {
          // شاهد المستخدم الإعلان حتى النهاية أو أغلقه في صيغة interstitial
          onReward();
        })
        .catch((result) => {
          // حصل المستخدم على خطأ أثناء تشغيل الإعلان
          onError?.(result);
        });
    } else {
      onError?.({
        error: true,
        done: false,
        state: 'load',
        description: 'Adsgram script not loaded',
      });
    }
  }, [onError, onReward]);
}
```

```typescript [useAdsgram.ts]
import { useCallback, useEffect, useRef } from 'react';
/**
 * تحقق من قسم Typescript
 * واستخدم المسار الخاص بك لأنواع adsgram
 */
import type { AdController, ShowPromiseResult } from 'path-to-adsgram-types';

export interface useAdsgramParams {
  blockId: string;
  onReward?: () => void;
  onError?: (result: ShowPromiseResult) => void;
}

export function useAdsgram({ blockId, onReward, onError }: useAdsgramParams): () => Promise<void> {
  const AdControllerRef = useRef<AdController | undefined>(undefined);

  useEffect(() => {
    AdControllerRef.current = window.Adsgram?.init({ blockId });
  }, [blockId]);

  return useCallback(async () => {
    if (AdControllerRef.current) {
      return AdControllerRef.current
        .show()
        .then(() => {
          // شاهد المستخدم الإعلان حتى النهاية أو أغلقه في صيغة interstitial
          onReward?.();
        })
        .catch((result: ShowPromiseResult) => {
          // حصل المستخدم على خطأ أثناء تشغيل الإعلان
          onError?.(result);
        });
    } else {
      onError?.({
        error: true,
        done: false,
        state: 'load',
        description: 'Adsgram script not loaded',
      });
    }
  }, [onError, onReward]);
}
```
:::
::: tip نصيحة
لاختبار التكامل، مرّر `debug: true` إلى `init` — ستحصل على إعلان تجريبي بدلاً من إعلان حقيقي. احذفه أو اضبطه على `false` قبل النشر في بيئة الإنتاج. راجع [معاملات init](./api-reference#init).
:::
### مثال على الاستخدام
مثال على مكون زر بسيط، عند النقر على الزر سيتم عرض الإعلان.
::: code-group
```jsx [showAdButton.jsx]
import { useCallback, ReactElement } from 'react'
import { useAdsgram } from "./hooks/useAdsgram.ts";


export function ShowAdButton() {
  const onReward = useCallback(() => {
    alert('Reward');
  }, []);
  const onError = useCallback((result) => {
    alert(JSON.stringify(result, null, 4));
  }, []);

  /**
   * أدخل your-block-id
   */
  const showAd = useAdsgram({ blockId: "your-block-id", onReward, onError });

  return (
    <button onClick={showAd}>Show Ad</button>
  )
}
```
```tsx [showAdButton.tsx]
import { useCallback, ReactElement } from 'react'
import { useAdsgram } from "./hooks/useAdsgram.ts";
import { ShowPromiseResult } from "./types/adsgram";


export function ShowAdButton(): ReactElement {
  const onReward = useCallback(() => {
    alert('Reward');
  }, []);
  const onError = useCallback((result: ShowPromiseResult) => {
    alert(JSON.stringify(result, null, 4));
  }, []);

  /**
   * أدخل your-block-id
   */
  const showAd = useAdsgram({ blockId: "your-block-id", onReward, onError });

  return (
    <button onClick={showAd}>Show Ad</button>
  )
}
```
:::

## Unity
لا نملك plugin لـ unity.

أنشئ ملف `.jslib`، راجع [إعداد إضافة JavaScript](https://docs.unity3d.com/Manual/web-interacting-browser-js.html) في دليل Unity.

لاستدعاء دوال JS من Unity، راجع [استدعاء دوال JavaScript من سكربتات Unity C#](https://docs.unity3d.com/Manual/web-interacting-browser-js-to-unity.html).\
لاستدعاء دوال Unity من JS، راجع [استدعاء دوال سكربتات Unity C# من JavaScript](https://docs.unity3d.com/Manual/web-interacting-browser-unity-to-js.html).

## Vanilla js
مثال مع سكريبت مدمج وزر لعرض الإعلان.
```html
<!doctype html>
<html lang="en">
    <head>
        <meta charset="UTF-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <title>Test app</title>
        <script src="https://telegram.org/js/telegram-web-app.js"></script>
        <script src="https://sad.adsgram.ai/js/sad.min.js"></script>
    </head>
    <body>
        <button id="ad">Show ad</button>
        <script>
            // أدخل block id الخاص بك
            const AdController = window.Adsgram.init({ blockId: "your-block-id" });
            const button = document.getElementById('ad');
            button.addEventListener('click', () => {
                AdController.show().then((result) => {
                    // شاهد المستخدم الإعلان حتى النهاية أو أغلقه في صيغة interstitial
                    // الكود الخاص بك لمكافأة المستخدم في صيغة rewarded
                    alert('Reward');
                }).catch((result) => {
                    // حصل المستخدم على خطأ أثناء تشغيل الإعلان
                    // لا تفعل شيئاً أو افعل ما تريد
                    alert(JSON.stringify(result, null, 4));
                })
            })
        </script>
    </body>
</html>
```
