---
title: "نمونه کد Reward و Interstitial"
description: "نمونه‌های کد AdsGram برای فرمت‌های Reward و Interstitial در React، Unity و جاوااسکریپت خالص، شامل هوک‌ها و کامپوننت دکمه."
outline: [2,3]
---
# نمونه‌های کد

- قالب **Rewarded**، به این معنی که باید به کاربر پاداش بدهید وقتی تبلیغ را تا انتها مشاهده کرد و تبلیغ باید مورد انتظار باشد، مثلاً پس از کلیک روی یک عنصر.\
اطلاعات بیشتر درباره [الزامات نمایش تبلیغ](./reward-examples#الزامات-نمایش-تبلیغ).
- قالب **Interstitial**، به این معنی که کاربر می‌تواند تبلیغ را قبل از انتها ببندد و تبلیغ باید در حین مکث‌های طبیعی در جریان اپلیکیشن مورد انتظار باشد.\
اطلاعات بیشتر درباره [الزامات نمایش تبلیغ](./interstitial-examples#الزامات-نمایش-تبلیغ).

::: info اطلاعات
در زیر نمونه‌های کد برای قالب Rewarded آمده است. این نمونه‌ها برای قالب Interstitial نیز معتبر هستند. تنها تفاوت این است که promise مربوط به AdController.show() هم برای تبلیغاتی که تا انتها مشاهده شده‌اند و هم برای تبلیغاتی که بسته شده‌اند، resolve می‌شود. [نمونه کد ساده Interstitial](./interstitial-examples#مثال-کد-ساده) را ببینید.
:::

## React
### درج اسکریپت
این [اسکریپت](./reward-interstitial-integration#درج-اسکریپت) را داخل تگ `<head>` HTML خود قرار دهید.

### ایجاد هوک useAdsgram
فایلی در پروژه خود با هوک سفارشی `useAdsgram` ایجاد کنید.\
اطلاعات بیشتر درباره هوک‌های سفارشی در [مستندات 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` ارسال کنید — به جای تبلیغ واقعی، تبلیغ آزمایشی دریافت می‌کنید. قبل از انتشار در production آن را حذف کنید یا روی `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));
  }, []);

  /**
   * blockId خود را وارد کنید
   */
  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));
  }, []);

  /**
   * blockId خود را وارد کنید
   */
  const showAd = useAdsgram({ blockId: "your-block-id", onReward, onError });

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

## Unity
ما پلاگینی برای unity نداریم.

فایل `.jslib` ایجاد کنید؛ [راه‌اندازی افزونه JavaScript](https://docs.unity3d.com/Manual/web-interacting-browser-js.html) را در راهنمای Unity ببینید.

برای فراخوانی توابع JS از Unity، [فراخوانی توابع JavaScript از اسکریپت‌های C# در Unity](https://docs.unity3d.com/Manual/web-interacting-browser-js-to-unity.html) را ببینید.\
برای فراخوانی توابع Unity از JS، [فراخوانی توابع اسکریپت C# در Unity از 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>
            // blockId خود را وارد کنید
            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>
```
