---
title: "Reward 与 Interstitial 代码示例"
description: "AdsGram Reward 与 Interstitial 广告格式在 React、Unity 和原生 JavaScript 中的代码示例，包含 Hook 与按钮组件。"
outline: [2,3]
---
# 代码示例
* 奖励格式，这意味着当用户观看广告至结束时，你应该给予用户奖励，广告应该在点击元素后出现。\
  有关显示广告要求的更多[信息](./reward-examples#广告展示要求)。
* 插页格式，这意味着用户可以在结束前跳过广告，广告应该在应用程序流程的自然暂停期间出现。\
  有关显示广告要求的更多[信息](./interstitial-examples#插屏广告展示要求)。

::: info 信息
以下是奖励格式的代码示例。这些示例也适用于插页格式。唯一的区别在于，AdController.show()承诺会为已观看至结束的广告以及已关闭的广告解析。请参阅[Interstitial 简单代码示例](./interstitial-examples#简单代码示例)。
:::

## React
### 插入脚本
将此[脚本](./reward-interstitial-integration#插入脚本)插入到你的HTML的`<head>`标签内

### 创建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(() => {
          // 用户观看广告至结束或在插页格式中关闭它
          onReward();
        })
        .catch((result) => {
          // 用户在播放广告时遇到错误
          onError?.(result);
        });
    } else {
      onError?.({
        error: true,
        done: false,
        state: 'load',
        description: 'Adsgram脚本未加载',
      });
    }
  }, [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(() => {
          // 用户观看广告至结束或在插页格式中关闭它
          onReward?.();
        })
        .catch((result: ShowPromiseResult) => {
          // 用户在播放广告时遇到错误
          onError?.(result);
        });
    } else {
      onError?.({
        error: true,
        done: false,
        state: 'load',
        description: 'Adsgram script not loaded',
      });
    }
  }, [onError, onReward]);
}
```
:::
::: tip 提示
测试集成时，请在 `init` 中传入 `debug: true`，此时将展示测试广告而非真实广告。发布到生产环境前，请删除该参数或将其设为 `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));
  }, []);

  /**
   * 插入你的block-id
   */
  const showAd = useAdsgram({ blockId: "your-block-id", onReward, onError });

  return (
    <button onClick={showAd}>显示广告</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('奖励');
  }, []);
  const onError = useCallback((result: ShowPromiseResult) => {
    alert(JSON.stringify(result, null, 4));
  }, []);

  /**
   * 插入你的block-id
   */
  const showAd = useAdsgram({ blockId: "your-block-id", onReward, onError });

  return (
    <button onClick={showAd}>显示广告</button>
  )
}
```
:::

## Unity
我们没有适用于Unity的插件。

创建`.jslib`文件，请参阅 Unity 手册中的[设置 JavaScript 插件](https://docs.unity3d.com/Manual/web-interacting-browser-js.html)。

从 Unity 调用 JavaScript 函数，请参阅[从 Unity C# 脚本调用 JavaScript 函数](https://docs.unity3d.com/Manual/web-interacting-browser-js-to-unity.html)。\
从 JavaScript 调用 Unity 函数，请参阅[从 JavaScript 调用 Unity C# 脚本函数](https://docs.unity3d.com/Manual/web-interacting-browser-unity-to-js.html)。

## Vanilla js
inline 代码和按钮来显示广告
```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) => {
                    // 用户观看完整广告或在插屏模式下关闭广告
                    // 在奖励广告模式下执行奖励逻辑
                    alert('Reward');
                }).catch((result) => {
                    // 用户播放广告时发生错误
                    // 可选择不执行任何操作
                    alert(JSON.stringify(result, null, 4));
                })
            })
        </script>
    </body>
</html>
```
