games/ChaoJiJieYaGuan_MaJiang2/assets/Script/Tools/Sdk/ads/douyinAdsApi.ts

745 lines
23 KiB
TypeScript
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

/**
* 抖音广告sdk
* ts 版本
* 单例
*/
import Utils from "../../Utils";
export default class douyinAdsApi {
public static _instance:douyinAdsApi = null
isvideoend: boolean;
checkVideo: boolean;
private _type: any;
public static get Instance(){
if (null == this._instance) {
this._instance = new douyinAdsApi();
}
return this._instance
}
// private _platform:string
// get platform():string {
// this._platform = 'tt'
// return this._platform
// }
// set plaform(str){
// this._platform = str
// }
videoRecordingState:any = 0;
video_recorder:any = null;
videoStartTime:any = null;
videoPath:any = null;
videoIsExist:any = 0;//视频是否存在 默认存在
recorderTime:any = 120; //视频录制时间
videoAd:any = null; //激励视频
chaPingErr:any = false; //插屏报错(触发频繁限制等)
chaPing:any = null
bannerAd:any = null; //横屏广告
videoCallBack = null //激励视频成功回调
videoFailCallBack = null //激励视频失败回调
isshowbanner = false
//抖音小游戏 广告配置
tt_info:any = {
gamename:"xx", //游戏名称
shareTitle:'#xx#xx', //分享标题
appId:'xxxx', //appid
videoId: '2g6k03247i3bbe0mgq', //激励视频
chapingId: '205kvivcof71ggv8hn', //插屏
bannerId: "3e44e0ffj4mn272vkr", //banner 横幅
getMore_videoId:'',
templateId: ['','','',''],
videoTopics:['激战麻将','欢乐麻将'], //分享录屏 设定的话题
appSecret:'',
}
/**
* 获取平台 类
*/
getPlatformClass(){
//@ts-ignore
var p_class = tt
return p_class
}
/**
* 获取分享标题
*/
getShareTitle(){
var title = ''
title = this.tt_info.shareTitle
return title
}
/**
* 获取名字
*/
getName(){
var name = ''
name = this.tt_info.gamename
return name
}
/**
* 获取appid
*/
getAppId(){
var appid = ''
appid = this.tt_info.appId
return appid
}
/**
* 获取bannerid
*/
getBannerId(){
var bannerID = ''
bannerID = this.tt_info.bannerId
return bannerID
}
/**
* 获取videoid
*/
getVideoId(){
var videoId = ''
videoId = this.tt_info.videoId
return videoId
}
/**
* 再得videoid
*/
getMoreVideoId(){
var videoId = ''
videoId = this.tt_info.getMore_videoId
return videoId
}
/**
* 获取插屏广告id
*/
getChaPingId(){
var chapingId = ''
chapingId = this.tt_info.chapingId
return chapingId
}
/**
* 游戏登录
*/
gameLogin(_force){
this.getPlatformClass().login({
force: _force,
success(res) {
console.log('login 调用成功',res);
},
fail(res) {
//console.log(`login 调用失败`);
}
});
}
/**
* 游戏分享
*/
game_share(callBack, sharetype){
if(sharetype == 0) {//常规分享
//@ts-ignore
tt.shareAppMessage({
templateId: '', // 替换成通过审核的分享ID
query: "",
success() {
//console.log("分享成功");
callBack()
},
fail(e) {
//console.log("分享失败");
}
});
}
}
/**
* 分享到好友
* @param callback
*/
shareGameToFriend(callback, note?:string){
let notestr = '你的好友邀请你一起战斗'
if(note) notestr = note
var self = this
let title = this.getName()
this.getPlatformClass().shareAppMessage({
channel: "invite", // 拉起邀请面板分享游戏好友
title: title,
desc: notestr,
imageUrl: "",
query: "",
success() {
//console.log("分享成功");
},
fail(e) {
//console.log("分享失败");
},
});
}
/**
* banner 广告显示
*/
bannerAds_Show(){
var self = this
if (self.bannerAd == null) {
let winSize = this.getPlatformClass().getSystemInfoSync();
let bannerWidth = winSize.windowWidth;
let bannerHeight = 100;
// // 广告
let bannerID = this.getBannerId()
self.bannerAd = this.getPlatformClass().createBannerAd({
adUnitId: bannerID,
style: {
left: (winSize.windowWidth - bannerWidth) / 2,
top: winSize.windowHeight - bannerHeight ,
width: bannerWidth,
height: bannerHeight,
}
})
self.bannerAd.onResize(res => {
self.bannerAd.style.left = (winSize.windowWidth - res.width) / 2;
self.bannerAd.style.top = winSize.windowHeight - res.height ;
})
self.bannerAd.onError(function (res) {
//console.log(res);
})
}
if (self.bannerAd != null) {
self.bannerAd.show();
}
}
/**
* banner 广告隐藏
*/
bannerAds_Hide(){
var self = this
if (self.bannerAd != null) {
self.bannerAd.hide();
}
}
/**
* 插屏广告显示
*/
chaPingAds_Show(){
var self = this
let sysData = this.getPlatformClass().getSystemInfoSync()
if(sysData.appName == 'devtools') return console.log('插屏开发工具不操作')
if(self.chaPingErr == true) return
self.chaPingErr = true
setTimeout(()=>{
self.chaPingErr = false
},60000)
var chapingId = this.getChaPingId()
if (this.getPlatformClass().createInterstitialAd) {
const interstitialAd = this.getPlatformClass().createInterstitialAd({
adUnitId: chapingId
});
interstitialAd
.load()
.then(() => {
interstitialAd.show();
})
.catch(err => {
console.log(err);
setTimeout(() => {
interstitialAd.load().then(()=>{interstitialAd.show})
}, 5);
});
interstitialAd.onClose(()=>{
if(interstitialAd){
interstitialAd.destroy()
}
})
}
}
/**
* 激励广告加载
*/
motivational_Video_Load(){
let sysData = this.getPlatformClass().getSystemInfoSync()
if(sysData.appName == 'devtools') return console.log('开发工具不操作')
var self = this
var videoId = this.getVideoId()
this.videoAd = this.getPlatformClass().createRewardedVideoAd({
adUnitId: videoId,
//multiton: true
})
this.videoAd.onError((res)=>{
//console.log('激励视频错误',res)
})
this.videoAd.load()
var endCallBack = function(res){
if (res.isEnded == true) {
if(self.videoCallBack != null){
//console.log('获取奖励')
self.videoCallBack()
}
if(this._type != -1){
self.showToast('已获得')
}
} else {
if (self.videoFailCallBack != null) self.videoFailCallBack()
}
self.isvideoend = true
}
self.videoAd.onClose(endCallBack); //绑定结束回调
}
/**
* 展示激励视频
* 参数1 成功回调
* 参数2 失败回调 可以省略
*/
motivational_Video_Show(success, faile, type?){
var self = this
if(this.checkVideo == true) return this.showToast('勿频繁点击')
setTimeout(()=>{
self.checkVideo = false
},1000)
this.videoCallBack = success
this.videoFailCallBack = faile
this._type = type
this.checkVideo = true
let sysData = this.getPlatformClass().getSystemInfoSync()
if(sysData.appName == 'devtools') return success(),console.log('开发工具不操作')
if(this.videoAd == null || this.videoAd == undefined){
return this.videoCallBack()
}
this.videoAd.onError((res)=>{
//console.log('广告出错监听', res)
})
// /**展示 */
this.videoAd
.show()
.then(() => {
})
.catch(err => {
self.showToast('激励视频播放失败')
//console.log('打印激励视频错误', err)
// 可以手动加载一次
self.videoAd.load().then(() => {
// 加载成功后需要再显示广告
return self.videoAd.show();
});
});
}
/**
* 再得 展示激励视频
* 参数1 成功回调
* 参数2 失败回调
*/
motivational_Other_Video_Show(success, faile, param){
let type = param[0]
let videonum = 0
if(type == 0){ //无限体力的
videonum = 2 - param[1]
console.log('打印激励视频次数', videonum)
}else if(type == 1) {//福利礼包的
videonum = 1
}else if(type == 2){ //彩虹 锤子道具礼包
videonum = 1 - param[1]
}
if(videonum <= 0){
this.motivational_Video_Show(success, faile)
return
}
console.log('打印激励视频 次数', videonum)
var videoId = this.getMoreVideoId()
const sysinfo = this.getPlatformClass().getSystemInfoSync()
const sdkversion = sysinfo.SDKVersion
let appname = sysinfo.appName
let appVersion = sysinfo.version
if (Utils.compareVersion(sdkversion, '2.70.0') >= 0
&& (appname == 'Douyin' || appname == 'douyin_lite')
&& Utils.compareVersion(appVersion, '23.4') >= 0) {
douyinAdsApi.Instance.videoAd.destroy()
.then(() => {
//这里再次创建其他adUnitId的广告实例
//@ts-ignore
douyinAdsApi.Instance.videoAd = tt.createRewardedVideoAd({
adUnitId: videoId,
multiton: true,
multitonRewardMsg: ['更多奖励', '更多奖励', '更多奖励'],
multitonRewardTimes: videonum,
progressTip: false,
});
douyinAdsApi.Instance.videoAd.load().then(() => {
console.log("手动加载成功");
douyinAdsApi.Instance.videoAd.show();
});
douyinAdsApi.Instance.videoAd.onClose(res => {
// 用户点击了【关闭广告】按钮
console.log('打印多次看视频', res.count)
if (res && res.isEnded) {
for (let index = 0; index < res.count; index++) {
console.log('打印激励视频回调',index)
success()
}
// 正常播放结束,可以下发游戏奖励
douyinAdsApi.Instance.showToast('已获得')
}
else {
// 播放中途退出,不下发游戏奖励
faile()
}
douyinAdsApi.Instance.videoAd.destroy()
douyinAdsApi.Instance.motivational_Video_Load()
})
})
.catch((err) => {
console.log("广告组件出现问题", err);
});
}else{
this.motivational_Video_Show(success, faile)
}
}
/**
* 录制视频开始
*/
recording_Video_Start(){
var self = this
let sysData = this.getPlatformClass().getSystemInfoSync()
if(sysData.appName == 'devtools') return console.log('开发工具不操作')
self.videoRecordingState = 1;
self.videoIsExist = 0;
self.video_recorder = this.getPlatformClass().getGameRecorderManager();
self.videoStartTime = Date.parse(new Date().toString()) //Date.parse(new Date());
//开始回调
self.video_recorder.onStart(res => {
//console.log('录屏开始');
//console.log(res);
});
//开始
self.video_recorder.start({
duration: self.recorderTime, //录制时长
});
//录制结束回调
self.video_recorder.onStop(res => {
self.videoRecordingState = 2;
self.videoPath = res.videoPath;
//console.log('录屏结束', self.videoPath)
// do somethine;
});
//录制错误回调
self.video_recorder.onError(res => {
//console.log("录屏error", res)
});
}
/**
* 录制视频结束
*/
recording_Video_End(){
let sysData = this.getPlatformClass().getSystemInfoSync()
if(sysData.appName == 'devtools') return console.log('开发工具不操作')
var self = this
//console.log('录屏结束');
//gameConfig.shareVideoTips = 0;
if (self.video_recorder) {
var endTime = Date.parse(new Date().toString()) //Date.parse(new Date());
if ((endTime - self.videoStartTime) / 1000 <= 5) {
self.videoIsExist = 1;
}else{
self.videoIsExist = 0;
}
self.video_recorder.stop();
}
}
/**
* 录制视频分享
* 参数1 成功回调方法
* 参数2 失败回调方法
*/
recording_Video_Share(callBack, failCallBack){
let sysData = this.getPlatformClass().getSystemInfoSync()
if(sysData.appName == 'devtools') return console.log('开发工具不操作')
var self = this
if(self.videoIsExist == 1){
self.showToast('录制时间过短')
return;
}
var result = 200;
self.videoRecordingState = 3;
this.getPlatformClass().shareAppMessage({
channel: 'video',
title: '',
imageUrl: '',
query: '',
extra: {
videoPath: self.videoPath, // 可用录屏得到的视频地址
videoTopics: self.tt_info.videoTopics,
createChallenge: true
},
success() {
self.showToast('分享视频成功')
callBack()
//self.recording_Video_Start()
},
fail(e) {
result = 201;
self.showToast('分享视频失败')
//console.log('分享失败', e)
failCallBack()
//self.recording_Video_Start()
}
})
}
//录屏是否存在
getVideoIsExist(){
return this.videoIsExist
}
/**
* 添加桌面
* @param scb
* @param fcb
*/
addShortcut(scb:Function, fcb:Function){
this.getPlatformClass().addShortcut({
success() {
this.showToast("添加桌面成功");
scb()
},
fail(err) {
this.showToast("添加桌面失败");
fcb()
},
});
}
/**
* 检测是否添加到桌面
* @returns true 不支持 或者 已添加
*/
checkShortcut(){
const version = this.getPlatformClass().getSystemInfoSync().SDKVersion
if (Utils.compareVersion(version, '2.46.0') >= 0) {
this.getPlatformClass().checkShortcut({
success(res) {
let exist = res.status.exist
//console.log("检查快捷方式", res.status);
return exist
},
fail(res) {
return true
//console.log("检查快捷方式失败", res.errMsg);
},
});
}else{
return true
}
}
/**
* 提示框
*/
showToast(str){
this.getPlatformClass().showToast({
title: str,
duration: 1000,
success(res) {
//console.log(`${res}`);
},
fail(res) {
//console.log(`showToast调用失败`);
}
});
}
//手机震动
vibrateShort(){
this.getPlatformClass().vibrateShort()
}
/**
* 设置 抖音排行榜 数字类型排行榜
* @param value 数值
*/
setImRankData_Num(value:string){
//@ts-ignore
const sysinfo = tt.getSystemInfoSync()
const sdkversion = sysinfo.SDKVersion
let appname = sysinfo.appName
let appVersion = sysinfo.version
if (Utils.compareVersion(sdkversion, '2.70.0') >= 0
&& (appname == 'Douyin' || appname == 'douyin_lite')
&& Utils.compareVersion(appVersion, '23.2.0') >= 0) {
//@ts-ignore
tt.setImRankData({
dataType: 0, //成绩为数字类型
value: "" + value, //该用户得了999999分
priority: 0, //dataType为数字类型不需要权重直接传0
extra: "extra",
success(res) {
console.log(`setImRankData success res: ${res}`);
},
fail(res) {
console.log(`setImRankData fail res: ${res.errMsg}`);
},
});
}
}
/**
* 获取数字类型原生排行榜
*/
getImRankList_Num(){
//@ts-ignore
const sysinfo = tt.getSystemInfoSync()
const sdkversion = sysinfo.SDKVersion
let appname = sysinfo.appName
let appVersion = sysinfo.version
if (Utils.compareVersion(sdkversion, '2.70.0') >= 0
&& (appname == 'Douyin' || appname == 'douyin_lite')
&& Utils.compareVersion(appVersion, '23.2.0') >= 0) {
//@ts-ignore
tt.getImRankList({
relationType: "default", //只展示好友榜
dataType: 0, //只圈选type为数字类型的数据进行排序
rankType: "day", //每月1号更新只对当月1号到现在写入的数据进行排序
suffix: "", //数据后缀,成绩后续默认带上 “分”
rankTitle: "游戏排行榜", //标题
success(res) {
console.log(`getImRankData success res: ${res}`);
},
fail(res) {
console.log(`getImRankData fail res: ${res.errMsg}`);
},
});
}else{
this.showToast('app版本不支持该功能')
}
}
/**
* 设置 抖音排行榜 枚举类型排行榜
* @param value 数值
* @param priority 权重
*/
setImRankData_Enum(value:string,priority:number){
//@ts-ignore
const sysinfo = tt.getSystemInfoSync()
const sdkversion = sysinfo.SDKVersion
let appname = sysinfo.appName
let appVersion = sysinfo.version
if (Utils.compareVersion(sdkversion, '2.70.0') >= 0
&& (appname == 'Douyin' || appname == 'douyin_lite')
&& Utils.compareVersion(appVersion, '23.2.0') >= 0) {
//@ts-ignore
tt.setImRankData({
dataType: 1, //成绩为枚举类型,因为段位不是一个数字
value: "" + value, //该用户段位为白银
priority: priority, //dataType为枚举类型需要权重该游戏排序为 青铜1、白银2、黄金3、王者4因此此处传2
extra: "extra",
success(res) {
console.log(`setImRankData success res: ${res}`);
},
fail(res) {
console.log(`setImRankData fail res: ${res.errMsg}`);
},
});
}
}
/**
* 获取枚举类型原生排行榜
*/
getImRankList_Enum(){
//@ts-ignore
const sysinfo = tt.getSystemInfoSync()
const sdkversion = sysinfo.SDKVersion
let appname = sysinfo.appName
let appVersion = sysinfo.version
if (Utils.compareVersion(sdkversion, '2.70.0') >= 0
&& (appname == 'Douyin' || appname == 'douyin_lite')
&& Utils.compareVersion(appVersion, '23.2.0') >= 0) {
//@ts-ignore
tt.getImRankList({
relationType: "default", //好友榜、总榜都展示
dataType: 1, //只圈选type为枚举类型的数据进行排序
rankType: "day", //每天凌晨0点更新只对当天0点到现在写入的数据进行排序
suffix: "", //为空或不填,一般枚举类型不需要填后缀
rankTitle: "游戏排行榜", //标题
success(res) {
console.log(`getImRankData success res: ${res}`);
},
fail(res) {
console.log(`getImRankData fail res: ${res.errMsg}`);
},
});
}else{
this.showToast('app版本不支持该功能')
}
}
/**
* 添加收藏
* @param {*} _typestring = bar customize
*/
addToMyFavorite(_type){
if(cc.sys.platform == cc.sys.BYTEDANCE_GAME){
if(_type == 'bar'){ //底部浮窗
//@ts-ignore
tt.showFavoriteGuide({
type: "bar",
content: "一键添加到我的小程序",
position: "bottom",
success(res) {
console.log("引导组件展示成功");
},
fail(res) {
console.log("引导组件展示失败");
},
});
}else if(_type == 'customize'){ //自定义
//@ts-ignore
tt.showFavoriteGuide({
type: "customize",
success(res) {
if(res.isFavorited){
douyinAdsApi.Instance.showToast('收藏成功')
}
console.log("isFavorited",res.isFavorited); //此处输出 “ifFavoritedtrue” 代表用户已收藏若为false代表用户未收藏
},
fail(res) {
console.log("自定义弹窗展示失败");
},
});
}
}
}
}