import AppPlatform from "../../FrameWork/Util/AppPlatform"; import AppConfig from "../../FrameWork/Config/AppConfig"; import Common5 from "../th/Common5"; import Common from "../../FrameWork/Util/Common"; import User from "../../FrameWork/User/User"; /** * 抖音 */ export default class TTAPI { //移到 AppConfig // public static readonly adUnitId = "" // public static readonly bannerAdUnitId = "" // public static readonly InsAdUnitId = "" // public static readonly _templateId = "" //分享素材id private static recordRes_custom: string = "" private static record_custom: any; protected static _banner_custom: any = null; public static loginCode = ""; protected static _onShow_custom: Function = null; protected static startDate:number = 0; protected static stopDate:number = 0; protected static fourGridGamePanel: any = null; public static ttLogin_custom(onSuccess: Function, onFail: Function) { if (AppPlatform.is_TT_GAME_custom()) { window["tt"].login( { force: false, success: (res) => { console.log(res) console.log("登陆成功1"); let code = res.code; if (code) { onSuccess(code); } else { console.log("用户没有登陆,采用临时code") onFail(); } }, fail: () => { console.log("登陆失败1"); onFail(); }, }) TTAPI.initRecord_custom(); } } //-------------------------激励视频--------------------------------- protected static _isRegRewardedVideoAdEvent_custom = false; protected static _onRewardedVideoAdFailed_custom: Function = null; protected static _onRewardedVideoAdClose_custom: Function = null; protected static TTAPI_ID_number = 0; protected static onRewardedVideoAdLoad_custom() { console.log('激励视频 广告加载完成') } protected static onRewardedVideoAdError_custom(err) { console.log('激励视频 广告加载失败' + err) if (TTAPI._onRewardedVideoAdFailed_custom) { TTAPI._onRewardedVideoAdFailed_custom(); } } protected static onRewardedVideoAdClose_custom(res) { if ((res && res.isEnded) || res == null) { console.log('激励视频 已完整观看') if (TTAPI._onRewardedVideoAdClose_custom) { TTAPI._onRewardedVideoAdClose_custom(true) ZYSDK.ZYSDK.reportVideo(true); } } else { console.log('激励视频 未完整观看') if (TTAPI._onRewardedVideoAdClose_custom) { TTAPI._onRewardedVideoAdClose_custom(false) ZYSDK.ZYSDK.reportVideo(false); } } } protected static regRewardedVideoAdEvent_custom(rewardedVideoAd) { rewardedVideoAd.onLoad(TTAPI.onRewardedVideoAdLoad_custom) rewardedVideoAd.onError(TTAPI.onRewardedVideoAdError_custom) rewardedVideoAd.onClose(TTAPI.onRewardedVideoAdClose_custom) TTAPI._isRegRewardedVideoAdEvent_custom = true; } public static showRewardedVideoAd_custom(onAdClose: Function, onFailed: Function) { if (AppPlatform.is_TT_GAME_custom()) { if (window["tt"].createRewardedVideoAd) { TTAPI._onRewardedVideoAdClose_custom = onAdClose; TTAPI._onRewardedVideoAdFailed_custom = onFailed; if (this.TTAPI_ID_number == AppConfig.tt_adUnitIdArr_custom.length) { this.TTAPI_ID_number = 0; } let videoid = AppConfig.tt_adUnitIdArr_custom[this.TTAPI_ID_number]; //AppConfig.tt_adUnitIdArr_custom[Math.floor(Math.random() * AppConfig.tt_adUnitIdArr_custom.length)]; this.TTAPI_ID_number++; var rewardedVideoAd = window["tt"].createRewardedVideoAd( { adUnitId: videoid, } ); if (!TTAPI._isRegRewardedVideoAdEvent_custom) { TTAPI.regRewardedVideoAdEvent_custom(rewardedVideoAd); } rewardedVideoAd.load().then(() => { var promise = rewardedVideoAd.show(); promise.then(() => console.log('激励视频 广告显示成功')); promise.catch((err) => { rewardedVideoAd.load() .then(() => rewardedVideoAd.show()) .catch(err => { if (AppPlatform.is_TT_GAME_custom()) { let errStr = "激励视频 广告显示失败" + err.errCode console.log('errStr', errStr); window["tt"].reportAnalytics('getVideoFail', { failReason: errStr, }); } if (onFailed) { if (this.TTAPI_ID_number == AppConfig.tt_adUnitIdArr_custom.length) { this.TTAPI_ID_number = 0; onFailed(); }else{ this.showRewardedVideoAd_custom(onAdClose,onFailed); } } }) }); }).catch(err => { let errStr = "激励视频 广告加载失败" + err.errCode console.log('errStr', errStr); if (AppPlatform.is_TT_GAME_custom()) { window["tt"].reportAnalytics('getVideoFail', { failReason: errStr, }); } if (onFailed) { // onFailed(); if (this.TTAPI_ID_number == AppConfig.tt_adUnitIdArr_custom.length) { this.TTAPI_ID_number = 0; onFailed(); }else{ this.showRewardedVideoAd_custom(onAdClose,onFailed); } } }) } else { window["tt"].showModal({ title: "提示", content: "当前客户端版本过低,无法使用该功能,请升级客户端或关闭后重启更新。", }); } } else { onAdClose(true); } } //-------------------录屏------------------------------------------- /** * 配置录屏 */ public static initRecord_custom() { let tt = window["tt"]; if(tt){ TTAPI.recordRes_custom = tt.getGameRecorderManager(); } TTAPI.record_custom = window["tt"].getGameRecorderManager(); if (TTAPI.record_custom != null) { TTAPI.record_custom.onStart(res => { console.log("录屏开始"); TTAPI.recordRes_custom = ""; }) TTAPI.record_custom.onStop(res => { console.log("录屏结束"); TTAPI.recordRes_custom = res.videoPath; }) } } public static getOpenID(){ let onFail = ()=>{ } let onSuccess = (response)=>{ console.log(response, '数据+++=====') if(response.msg == 'OK'){ User.setOtherplatformUserid(response.openid) } } if(this.loginCode != ""){ let url = "https://report1.ioe-times.com/api/getopenid" let headersTab = {}; //头数据 let xhr: XMLHttpRequest = new XMLHttpRequest(); xhr.timeout = 15000; //请求过程发生意外的回调 xhr.onerror = function (error) { onFail(); } //超时 xhr.ontimeout = function (error) { onFail(); } xhr.onreadystatechange = function () { let readyState = xhr.readyState; let status = xhr.status; if (readyState === 4) { let tab = { code: 1 } if (status >= 200 && status < 300) { let responseText = xhr.responseText; const response = JSON.parse(responseText); console.log(response, 'getLoginInfo data+++++') onSuccess(response); } else { let statusText = xhr.statusText; console.log("接收内容:" + statusText) onSuccess(null); } } } xhr.open("POST", url, true); if (!headersTab["Content-Type"]) { headersTab["Content-Type"] = "application/json"; } if (headersTab) { for (let key in headersTab) { xhr.setRequestHeader(key, headersTab[key]); } } let params = {GameName:"WDZTBJ",Anonymous_code:"", "Code":this.loginCode}; let sendMsg = JSON.stringify(params); xhr.send(sendMsg); } } /** * 开始录屏 */ public static startRecord_custom(durationiNPUT = 300) { if (!AppPlatform.is_TT_GAME_custom()) { return; } this.startDate = new Date().getTime(); console.log(this.startDate); TTAPI.record_custom.start({ duration:durationiNPUT }) } /** * 停止录屏 */ public static stopRecord_custom() { if (!AppPlatform.is_TT_GAME_custom()) { return; } this.stopDate = new Date().getTime(); console.log(this.stopDate); TTAPI.record_custom.stop(); } //---------------------------------------------------------------------- //---------------------分享录屏---------------------------------------- public static shareRecord_custom(callback: Function = null, Failcallback: Function = null) { if (!AppPlatform.is_TT_GAME_custom()) { return; } if ((this.stopDate - this.startDate) < 5000){ Common5.showTips_custom("录屏时间小于5秒分享失败,请稍后再试!"); return; } if (TTAPI.recordRes_custom != "") { window["tt"].shareAppMessage({ channel: "video", extra: { videoPath: TTAPI.recordRes_custom, // 可替换成录屏得到的视频地址 videoTopics: [AppConfig.GameName_custom] }, success() { if (callback != null) { callback(); } console.log("分享视频成功"); }, fail(e) { console.log("分享视频失败", e); if (Failcallback != null) { Failcallback(); } } }); } else { if (Failcallback != null) { Failcallback(); } console.log("分享视频为空"); } } //---------------------------------------------------------------------- //---------------------------------------------------------------------- //---------------------分享好友---------------------------------------- public static share_custom(complate: Function = null) { if (!AppPlatform.is_TT_GAME_custom()) { return; } window["tt"].shareAppMessage({ channel: "invite", // 拉起邀请面板分享游戏好友 title: "", desc: "", imageUrl: "", query: "", success(res) { console.log("分享成功" + JSON.stringify(res)); }, fail(e) { console.log("分享失败"); }, }); // window["tt"].shareAppMessage({ // templateId: AppConfig.tt_templateId_custom, // success() { // if (complate != null) { // complate(); // } // }, // fail() { // console.log("分享失败"); // } // }); } //------------------------------------------------------------------ //-------------------------banner------------------------------------------- public static showBanner_custom(): any { if (!AppPlatform.is_TT_GAME_custom() || AppConfig.tt_bannerAdUnitId_custom.length <= 0) { return; } if (!TTAPI._banner_custom) { const { windowWidth, windowHeight } = window["tt"].getSystemInfoSync(); var targetBannerAdWidth = 150; // 创建一个居于屏幕底部正中的广告 TTAPI._banner_custom = window["tt"].createBannerAd({ adUnitId: AppConfig.tt_bannerAdUnitId_custom, adIntervals: 30, style: { width: targetBannerAdWidth, top: windowHeight - (targetBannerAdWidth / 16) * 9, // 根据系统约定尺寸计算出广告高度 } }); // 也可以手动修改属性以调整广告尺寸 TTAPI._banner_custom.style.left = (windowWidth - targetBannerAdWidth) / 2; TTAPI._banner_custom.onResize(size => { console.log(size.width, size.height); TTAPI._banner_custom.style.top = windowHeight - size.height; TTAPI._banner_custom.style.left = (windowWidth - size.width) / 2; }); } TTAPI._banner_custom.show(); } public static hideBanner_custom() { if (null != TTAPI._banner_custom) { TTAPI._banner_custom.hide(); } } public static showMoreGamesModal_custom(onSuccess: Function, onFail: Function) { const systemInfo = window["tt"].getSystemInfoSync(); // iOS 不支持,建议先检测再使用 if (systemInfo.platform !== "ios") { // 打开互跳弹窗 window["tt"].showMoreGamesModal({ appLaunchOptions: [ { appId: AppConfig.AppID_custom, query: "foo=bar&baz=qux", extraData: {} } // {...} ], success(res) { console.log("success", res.errMsg); if (onSuccess) { onSuccess(); } }, fail(res) { console.log("fail", res.errMsg); if (onFail) { onFail(); } } }); } else { if (onFail) { onFail(); } } } // ------------------------------------- 插屏广告 ------------------------------------- public static showInterstitialAd(onAdClose: Function, onFail: Function) { if (!AppPlatform.is_TT_GAME_custom()) { return; } console.log("插屏插屏create....................") let interstitialAd: any = window["tt"].createInterstitialAd({ adUnitId: AppConfig.tt_InsAdUnitId_custom, }); interstitialAd.load().then(() => { console.log("插屏广告加载成功!"); interstitialAd.show().then(() => { console.log("插屏广告展示成功!"); }).catch((err) => { console.log("插屏广告显示失败:", JSON.stringify(err)); }); }).catch((err) => { console.log("插屏广告加载失败:", JSON.stringify(err)); }); interstitialAd.onClose(() => { console.log('插屏广告 关闭'); interstitialAd.destroy(); if (onAdClose) { onAdClose(); } }) } // ------------------------------------- 插屏广告 ------------------------------------- /** * 得到小程序启动参数的同步方法,可得到一个Object返回值,返回值具体的数据结构在下面的列表中 * scene number 启动小游戏的场景值 * query Object 启动小游戏的 query 参数 * shareTicket string shareTicket,详见获取更多转发信息 * referrerInfo object 来源信息。从另一个小程序、公众号或 App 进入小程序时返回。否则返回 {} * https://developers.weixin.qq.com/minigame/dev/api/base/app/life-cycle/wx.getLaunchOptionsSync.html * @static * @returns {LaunchOptions} * @memberof TTAPI */ public static getLaunchOptionsSync_custom() { // let result = { scene: 0, query: null, shareTicket: "", referrerInfo: null }; if (AppPlatform.is_TT_GAME_custom()) { let obj = window["tt"].getLaunchOptionsSync(); console.log("obj ", obj); console.log("场景值 " + obj.scene); let str = JSON.stringify(obj.query); console.log("Query参数 " + str); let key = obj.query["key"]; console.log("Query参数:key " + key); return obj; } let obj = { scene: 1001, query: "" } return obj; } //关注抖音号 public static followTTCount() { if (AppPlatform.is_TT_GAME_custom()) { window["tt"].openAwemeUserProfile({ success: (res) => { console.log(res); }, }); } } //添加到桌面 public static addToZM() { if (AppPlatform.is_TT_GAME_custom()) { window["tt"].addShortcut({ success: function (res) { ZYSDK.ZYSDK.reportUserAction('添加桌面-成功'); console.log("添加成功"); }, fail: function (res) { console.log("添加失败"); } }) } } //监听小游戏回到前台的事件 public static onShow(callFunc){ if (AppPlatform.is_TT_GAME_custom()) { window["tt"].onShow((res)=>{ console.log("启动参数:", res.query); console.log("来源信息:", res.refererInfo); console.log("场景值:", res.scene); console.log("启动场景字段:", res.launch_from, ", ", res.location); callFunc && callFunc(res) }) } } //检测是否有侧边栏 public static checkScene(onSuccess: Function, onFail: Function){ if (AppPlatform.is_TT_GAME_custom()) { if(window["tt"].checkScene){ window["tt"].checkScene({ scene: "sidebar", success: (res) => { console.log("check scene success: ", res.isExist); //成功回调逻辑 onSuccess && onSuccess() }, fail: (res) => { console.log("check scene fail:", res); //失败回调逻辑 onFail && onFail() } }) } } } //加入侧边栏 public static navigateToScene(onSuccess: Function, onFail: Function){ if (AppPlatform.is_TT_GAME_custom()) { window["tt"].navigateToScene({ scene: "sidebar", success: (res) => { console.log("navigate to scene success"); // 跳转成功回调逻辑 onSuccess && onSuccess() }, fail: (res) => { console.log("navigate to scene fail: ", res); // 跳转失败回调逻辑 onFail && onFail() }, }); } } public static showFourGridGamePanel(){ if (AppPlatform.is_TT_GAME_custom()){ if ( this.fourGridGamePanel) { this.fourGridGamePanel.show() .then(() => { console.error("展示游戏推荐组件成功"); }) .catch((err) => { console.error("展示游戏推荐组件失败", err); }); // setTimeout(() => { // this.fourGridGamePanel.hide(); // console.log("隐藏游戏推荐组件"); // }, 5000); } } } //创建游戏推荐组件实例。 public static createGridGamePanel(){ if (AppPlatform.is_TT_GAME_custom()) { try { // 四宫格可设置大小 设置位置无实际作用 const fourGridGamePanel = window["tt"].createGridGamePanel({ gridCount: "four", size: "large", query: { "ttd0e8a6554fda8f7902": "age=1&name=我的养家日记", "tt0a637cde955f697002": "age=2&name=我的侦探笔记", "tt32d2446faded9fb302": "age=3&name=收纳梦之岛", "ttaf9cd92130a0ced102": "age=4&name=我的修仙日记", }, }); this.fourGridGamePanel = fourGridGamePanel } catch (error) { console.error("创建游戏推荐组件失败", error); } } } public static getImRankList(){ if (AppPlatform.is_TT_GAME_custom()) {//抖音,字节跳动 if(window['tt'].getImRankList){ window['tt'].getImRankList({ relationType: "default", //好友榜,总榜 dataType: 0, //只圈选type为数字类型的数据进行排序 rankType: "month", //每月1号更新,只对当月1号到现在写入的数据进行排序 suffix: "关", //数据后缀,成绩后续默认带上 “个” rankTitle: "每月排行", //标题 success(res) { LogUtils.networkLog_custom("获取排行榜数据成功----------------------") }, fail(res) { console.log(`getImRankData fail res: ${res.errMsg}`); }, }); } }else{ Common5.showTips_custom("请登录抖音查看排行!"); } } //设置排行榜数据 public static setImRankData(value){ if (AppPlatform.is_TT_GAME_custom()) {//抖音,字节跳动 if(window['tt'].setImRankData){ window['tt'].setImRankData({ dataType: 0,//枚举类型0,1 value: value+'', priority:0, extra:"", success(res) { LogUtils.networkLog_custom("设置排行榜数据成功----------------------") }, fail(res) { console.log(`setImRankData fail res: ${res.errMsg}`); }, }); } } } public static dingyueXiaoxi(){ const tmplIds = ["MSG1634714137177312344616265861403"]; if(window['tt'] && window['tt'].requestSubscribeMessage){ console.log('有接口requestSubscribeMessage') window['tt'].requestSubscribeMessage({ tmplIds: tmplIds, complete: (res) => { console.log('订阅接口完成') }, success: (res) => { console.log(res) console.log("订阅接口完成成功1"); ZYSDK.ZYSDK.reportUserAction('订阅消息-成功'); }, fail: (res) => { window['tt'].showModal({ title: "订阅消息", content: JSON.stringify(res), }); console.log("订阅接口完成失败1"); }, }); } } }