rewarded-video.md 15.8 KB
Newer Older
Q
qiang 已提交
1 2
**激励视频广告**

DCloud_Heavensoft's avatar
DCloud_Heavensoft 已提交
3
# 此文档已过期,新文档: [https://uniapp.dcloud.net.cn/component/ad-rewarded-video.html](https://uniapp.dcloud.net.cn/component/ad-rewarded-video.html)
4

DCloud_Heavensoft's avatar
DCloud_Heavensoft 已提交
5
===========以下为过期文档=========
Q
qiang 已提交
6

d-u-a's avatar
d-u-a 已提交
7
[激励视频广告介绍](https://uniapp.dcloud.net.cn/component/ad-rewarded-video.html)
Q
qiang 已提交
8 9 10 11


**平台差异说明**

study夏羽's avatar
study夏羽 已提交
12 13 14
|App|H5|微信小程序|支付宝小程序|百度小程序|字节跳动小程序|飞书小程序|QQ小程序|快手小程序|京东小程序|
|:-:|:-:|:-:|:-:|:-:|:-:|:-:|:-:|:-:|:-:|
|√(2.5.11+)|x|√|x|x|√(1.57.0+)|x|√(0.1.26+)|√|x|
Q
qiang 已提交
15 16 17 18


**开通配置广告**

d-u-a's avatar
d-u-a 已提交
19
[开通广告步骤详情](https://uniapp.dcloud.net.cn/uni-ad.html#start)
Q
qiang 已提交
20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48


激励视频广告组件是原生组件,层级最高,会覆盖在普通前端组件上。


### 语法

`uni.createRewardedVideoAd(options)`

### 参数说明
options 为 object 类型,属性如下:

|属性名		|类型		|必填	|描述			|最低支持版本	|
|:-:|:-:|:-:|:-:|:-:|
|adpid	  |string	|	是|广告位 id |App 2.5.11+|
|adUnitId	|string	|	是|广告位 id |微信小程序2.6.0+, QQ0.1.26+, 字节跳动1.57.0+|


### 返回值

返回值为 RewarededVideoAd 类型,属性如下:

|属性名|类型|描述|最低支持版本|
|:-:|:-:|:-:|:-:|
|show|Function|广告创建后默认是隐藏的,可以通过该方法显示广告|App 2.5.11+, 微信小程序2.6.0+, QQ0.1.26+,字节跳动1.57.0+|
|onLoad|Function|绑定广告 load 事件的监听器|App 2.5.11+, 微信小程序2.6.0+, QQ0.1.26+,字节跳动1.57.0+|
|offLoad|Function|解除绑定 load 事件的监听器|QQ0.1.26+,字节跳动1.57.0+|
|load|Function|当广告素材加载出现错误时,可以通过 load 方法手动加载|App 2.5.11+, 微信小程序2.6.0+, QQ0.1.26+,字节跳动1.57.0+|
|onError|Function|绑定 error 事件的监听器	|App 2.5.11+, 微信小程序2.6.0+, QQ0.1.26+,字节跳动1.57.0+|
d-u-a's avatar
d-u-a 已提交
49
|onAdClicked|Function|绑定广告可点击屏幕区域事件的监听器  |App 2.5.11+|
Q
qiang 已提交
50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134
|offError|Function|解除绑定 error 事件的监听器|QQ0.1.26+,字节跳动1.57.0+|
|onClose|Function|绑定 close 事件的监听器|App 2.5.11+, 微信小程序2.6.0+, QQ0.1.26+,字节跳动1.57.0+|
|offClose|Function|解除绑定 close 事件的监听器|QQ0.1.26+,字节跳动1.57.0+|


### 广告创建

开发者可以调用 `uni.createRewardedVideoAd` 创建激励视频广告组件。

激励视频广告组件默认是隐藏的,因此可以提前创建,以提前初始化组件。开发者可以在页面的 `onReady` 事件回调中创建广告实例,并在该页面的生命周期内重复调用该广告实例。

```html
<script>
    export default {
        data() {
            return {
                title: 'createRewardedVideoAd'
            }
        },
        onReady() {
          this._isLoaded = false
          rewardedVideoAd = this._rewardedVideoAd = uni.createRewardedVideoAd({ adpid: '1507000689' }) // 仅用于HBuilder基座调试 adpid: '1507000689'
          rewardedVideoAd.onLoad(() => {
            this._isLoaded = true
            console.log('onLoad event')
            // 当激励视频被关闭时,默认预载下一条数据,加载完成时仍然触发 `onLoad` 事件
          })
          rewardedVideoAd.onError((err) => {
            console.log('onError event', err)
          })
          rewardedVideoAd.onClose((res) => {
            console.log('onClose event', res)
          })
        },
        methods: {
          show() {
            if (this._isLoaded) {
              this._rewardedVideoAd.show()
            }
          }
        }
    }
</script>
```


### 推荐接入示例@ad-js

`ad.js` 是对 `uni.createRewardedVideoAd` 的封装,一个页面缓存多页面生效,避免每个页面都预载而不展示的问题,可以传入不同广告位,内部处理了Loading状态、快速点击、数据过期、失败重试1次逻辑

```html
<template>
  <view>
    <button type="primary" class="btn" @click="showRewardedVideoAd">显示激励视频广告</button>
    <button type="primary" class="btn" @click="showFullScreenVideoAd">显示全屏视频广告</button>
  </view>
</template>

<script>
  import AD from "../ad.js"

  export default {
    data() {
      return {
        title: '视频广告'
      }
    },
    onReady() {
      // 可选预载广告数据

      // AD.load({
      //   adpid: 1507000689,
      //   adType: "RewardedVideo"
      // });

      // AD.load({
      //   adpid: 1507000611,
      //   adType: "FullScreenVideo"
      // });
    },
    methods: {
      showRewardedVideoAd() {
        // 调用后会显示 loading 界面
        AD.show({
          adpid: 1507000689, // HBuilder 基座测试广告位
135 136 137 138 139 140
          adType: "RewardedVideo",
          urlCallback: {// 服务器回调透传参数
            userId: 'testuser',
            extra: 'testdata'
          }
          //singleton: false // 设置此参数后,每次调用 show 方法将重新创建广告实例,预载将失效,如果广告回调每次要透传用户信息需要设置 false
Q
qiang 已提交
141 142 143 144 145 146 147 148 149
        }, (res) => {
          // 用户点击了【关闭广告】按钮
          if (res && res.isEnded) {
            // 正常播放结束
            console.log("onClose " + res.isEnded);
          } else {
            // 播放中途退出
            console.log("onClose " + res.isEnded);
          }
d-u-a's avatar
d-u-a 已提交
150 151

          // 在此处理服务器回调逻辑
Q
qiang 已提交
152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240
        }, (err) => {
          // 广告加载错误
          console.log(err)
        })
      },
      showFullScreenVideoAd() {
        // 调用后会显示 loading 界面
        AD.show({
          adpid: 1507000611, // HBuilder 基座测试广告位
          adType: "FullScreenVideo"
        }, (res) => {
          // 用户点击了【关闭广告】按钮
          if (res && res.isEnded) {
            // 正常播放结束
            console.log("onClose " + res.isEnded);
          } else {
            // 播放中途退出
            console.log("onClose " + res.isEnded);
          }
        }, (err) => {
          // 广告加载错误
          console.log(err)
        })
      }
    }
  }
</script>

```

```js
// ad.js
const ADType = {
  RewardedVideo: "RewardedVideo",
  FullScreenVideo: "FullScreenVideo"
}

class AdHelper {

  constructor() {
    this._ads = {}
  }

  load(options, onload, onerror) {
    let ops = this._fixOldOptions(options)
    let {
      adpid
    } = ops

    if (!adpid || this.isBusy(adpid)) {
      return
    }

    this.get(ops).load(onload, onerror)
  }

  show(options, onsuccess, onfail) {
    let ops = this._fixOldOptions(options)
    let {
      adpid
    } = ops

    if (!adpid) {
      return
    }

    uni.showLoading({
      mask: true
    })

    var ad = this.get(ops)

    ad.load(() => {
      uni.hideLoading()
      ad.show((e) => {
        onsuccess && onsuccess(e)
      })
    }, (err) => {
      uni.hideLoading()
      onfail && onfail(err)
    })
  }

  isBusy(adpid) {
    return (this._ads[adpid] && this._ads[adpid].isLoading)
  }

  get(options) {
    const {
d-u-a's avatar
d-u-a 已提交
241 242
      adpid,
      singleton = true
Q
qiang 已提交
243
    } = options
d-u-a's avatar
d-u-a 已提交
244 245 246 247 248 249 250
    if (singleton === false) {
      if (this._ads[adpid]) {
        this._ads[adpid].destroy()
        delete this._ads[adpid]
      }
    }
    delete options.singleton
Q
qiang 已提交
251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502
    if (!this._ads[adpid]) {
      this._ads[adpid] = this._createAdInstance(options)
    }

    return this._ads[adpid]
  }

  _createAdInstance(options) {
    const adType = options.adType || ADType.RewardedVideo
    delete options.adType

    let ad = null;
    if (adType === ADType.RewardedVideo) {
      ad = new RewardedVideo(options)
    } else if (adType === ADType.FullScreenVideo) {
      ad = new FullScreenVideo(options)
    }

    return ad
  }

  _fixOldOptions(options) {
    return (typeof options === "string") ? {
      adpid: options
    } : options
  }
}

const EXPIRED_TIME = 1000 * 60 * 30
const ProviderType = {
  CSJ: 'csj',
  GDT: 'gdt'
}

const RETRY_COUNT = 1

class AdBase {
  constructor(adInstance, options = {}) {
    this._isLoad = false
    this._isLoading = false
    this._lastLoadTime = 0
    this._lastError = null
    this._retryCount = 0

    this._loadCallback = null
    this._closeCallback = null
    this._errorCallback = null

    const ad = this._ad = adInstance
    ad.onLoad((e) => {
      this._isLoading = false
      this._isLoad = true
      this._lastLoadTime = Date.now()

      this.onLoad()
    })
    ad.onClose((e) => {
      this._isLoad = false
      this.onClose(e)
    })
    ad.onVerify && ad.onVerify((e) => {
      // e.isValid
    })
    ad.onError(({
      code,
      message
    }) => {
      this._isLoading = false
      const data = {
        code: code,
        errMsg: message
      }

      if (code === -5008) {
        this._loadAd()
        return
      }

      if (this._retryCount < RETRY_COUNT) {
        this._retryCount += 1
        this._loadAd()
        return
      }

      this._lastError = data
      this.onError(data)
    })
  }

  get isExpired() {
    return (this._lastLoadTime !== 0 && (Math.abs(Date.now() - this._lastLoadTime) > EXPIRED_TIME))
  }

  get isLoading() {
    return this._isLoading
  }

  getProvider() {
    return this._ad.getProvider()
  }

  load(onload, onerror) {
    this._loadCallback = onload
    this._errorCallback = onerror

    if (this._isLoading) {
      return
    }

    if (this._isLoad) {
      this.onLoad()
      return
    }

    this._retryCount = 0

    this._loadAd()
  }

  show(onclose) {
    this._closeCallback = onclose

    if (this._isLoading || !this._isLoad) {
      return
    }

    if (this._lastError !== null) {
      this.onError(this._lastError)
      return
    }

    const provider = this.getProvider()
    if (provider === ProviderType.CSJ && this.isExpired) {
      this._loadAd()
      return
    }

    this._ad.show()
  }

  onLoad(e) {
    if (this._loadCallback != null) {
      this._loadCallback()
    }
  }

  onClose(e) {
    if (this._closeCallback != null) {
      this._closeCallback({
        isEnded: e.isEnded
      })
    }
  }

  onError(e) {
    if (this._errorCallback != null) {
      this._errorCallback(e)
    }
  }

  destroy() {
    this._ad.destroy()
  }

  _loadAd() {
    this._isLoad = false
    this._isLoading = true
    this._lastError = null
    this._ad.load()
  }
}

class RewardedVideo extends AdBase {
  constructor(options = {}) {
    super(plus.ad.createRewardedVideoAd(options), options)
  }
}

class FullScreenVideo extends AdBase {
  constructor(options = {}) {
    super(plus.ad.createFullScreenVideoAd(options), options)
  }
}

export default new AdHelper()

```


### 显示/隐藏
激励视频广告组件默认是隐藏的,在用户主动触发广告后,开发者需要调用 RewardedVideoAd.show() 进行显示。

```js
rewardedVideoAd.show()
```

只有在用户点击激励视频广告组件上的 关闭广告 按钮时,广告才会关闭。开发者不可控制激励视频广告组件的隐藏。

### 广告拉取成功与失败

激励视频广告组件是自动拉取广告并进行更新的。在组件创建后会拉取一次广告,用户点击 关闭广告 后会去拉取下一条广告。

如果拉取成功,通过 `RewardedVideoAd.onLoad()` 注册的回调函数会执行,`RewardedVideoAd.show()` 返回的 Promise 也会是一个 resolved Promise。两者的回调函数中都没有参数传递。

```js
rewardedVideoAd.onLoad(() => {
  console.log('激励视频 广告加载成功')
})

rewardedVideoAd.show()
.then(() => console.log('激励视频 广告显示'))
```

如果拉取失败,通过 `RewardedVideoAd.onError()` 注册的回调函数会执行,回调函数的参数是一个包含错误信息的对象。常见异常错误参考文档

```js
rewardedVideoAd.onError(err => {
  console.log(err)
})
```

`RewardedVideoAd.show()` 返回的 Promise 也会是一个 rejected Promise。

```js
rewardedVideoAd.show()
.catch(err => console.log(err))
```

### 拉取失败,重新拉取

如果组件的某次自动拉取失败,那么之后调用的 show() 将会被 reject。此时可以调用 `RewardedVideoAd.load()` 手动重新拉取广告。

```js
rewardedVideoAd.show()
.catch(() => {
    rewardedVideoAd.load()
    .then(() => rewardedVideoAd.show())
    .catch(err => {
      console.log('激励视频 广告显示失败')
    })
})
```

如果组件的自动拉取是成功的,那么调用 `load()` 方法会直接返回一个 resolved Promise,而不会去拉取广告。

```js
rewardedVideoAd.load()
.then(() => rewardedVideoAd.show())
```

### 监听用户关闭广告

D
DCloud_LXH 已提交
503
![](https://web-assets.dcloud.net.cn/unidoc/zh/rewarded-video-close.png)
Q
qiang 已提交
504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533

只有在用户点击激励视频广告组件上的 关闭广告 按钮时,广告才会关闭。这个事件可以通过 `RewardedVideoAd.onClose()` 监听。

`RewardedVideoAd.onClose()` 的回调函数会传入一个参数 res,res.isEnded 描述广告被关闭时的状态。


|属性|类型|说明|
|:-:|:-:|:-:|
|isEnded|boolean|视频是否是在用户完整观看的情况下被关闭的,true 表示用户是在视频播放完以后关闭的视频,false 表示用户在视频播放过程中关闭了视频


开发者需要根据 res.isEnded 判断是否视频是否播放结束,如果成功播放完毕则应该向用户发放奖励。

```js
rewardedVideoAd.onClose(res => {
    // 用户点击了【关闭广告】按钮
    if (res && res.isEnded) {
      // 正常播放结束
	  // 这里应该联网给予用户激励。且这段代码应该做安全保护,详见下文中的“安全注意”
    } else {
      // 播放中途退出
    }
})
```


### 服务器回调@callback

App平台 3.1.15+ 支持穿山甲/优量汇/快手

d-u-a's avatar
d-u-a 已提交
534
激励视频广告可以支持广告服务器到业务服务器的回调,用于业务系统判断是否提供奖励给观看广告的用户。配置服务器回调后,当用户成功看完广告时,广告服务器会访问配置的云函数,通知用户完成观看激励视频。
Q
qiang 已提交
535 536 537

相对来讲服务器回调将更加安全,可以依赖广告平台的反作弊机制来避免用户模拟观看广告完成的事件。

study夏羽's avatar
study夏羽 已提交
538

D
DCloud_LXH 已提交
539
![激励视频回调](https://web-assets.dcloud.net.cn/unidoc/zh/uniAdCallback.png)
study夏羽's avatar
study夏羽 已提交
540 541


Q
qiang 已提交
542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557
如何使用
1. 申请激励视频广告位时开启服务器回调
2. 创建激励视频广告时传入回调参数


urlCallback示例

```js
rewardedVideoAd = uni.createRewardedVideoAd({
  adpid: '',
  urlCallback: {
    userId: 'testuser',
    extra: 'testdata'
  }
});

d-u-a's avatar
d-u-a 已提交
558
rewardedVideoAd.onClose(e => {
Q
qiang 已提交
559 560 561
})
```

562
### 服务器回调
Q
qiang 已提交
563

564
[服务器回调详细说明](https://uniapp.dcloud.net.cn/component/ad-rewarded-video.html#callback)
Q
qiang 已提交
565

d-u-a's avatar
d-u-a 已提交
566

Q
qiang 已提交
567 568
#### 安全注意

569
[详细说明](https://uniapp.dcloud.net.cn/component/ad-rewarded-video.html#%E5%AE%89%E5%85%A8%E6%B3%A8%E6%84%8F)
Q
qiang 已提交
570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587

#### 获取广告商名称

> HBuilderX 2.6.8+

#### 语法

`RewardedVideoAd.getProvider()`

#### 说明

返回值 为 string 类型

|值|描述|
|:-:|:-:|
|csj|穿山甲|
|gdt|腾讯优量汇(前称广点通)|
|ks|快手|
588
|sigmob|Sigmob|
Q
qiang 已提交
589 590 591 592 593 594 595 596 597 598


```js
var rewardedVideoAd = uni.createRewardedVideoAd(Options);
var provider = rewardedVideoAd.getProvider();
```


### manifest 配置@manifest

Q
qiang 已提交
599 600 601 602
注: `Sigmob`属于小型广告联盟,收益偏低。如有条件,还需开通优量汇,快手等广告渠道以便提高收益。

`Sigmob`暂不支持打包界面的勾选,如集成需进行如下的配置变动:

Q
qiang 已提交
603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639
`Sigmob`打包需要将`HBuilderX`升级到`3.2.0`以上版本。

打开 `manifest.json` 文件,点击 “源码视图”,`uni-app``app-plus->distribute->sdkConfigs` 下添加如下内容,`5+ app``plus->distribute->plugins` 下添加如下内容:

```json
{
	"app-plus": {
		"distribute": {
			"sdkConfigs": {
				"ad" : {
				  "sigmob" : {}
				}
			}
		}
	}
}
```

**注意:如果已经存在ad节点,只需要在后面追加即可,如下**

```json
{
	"app-plus": {
		"distribute": {
			"sdkConfigs": {
				"ad" : {
				  "gdt" : {},
				  "csj" : {},
				  "ks" : {},
				  "ks-content" : {},
				  "sigmob" : {}
				}
			}
		}
	}
}
```