各小游戏平台sdk,vivo,oppo,wx,qq,字节跳动

远程加载相关https://blog.csdn.net/K86338236/article/details/104385484

项目地址下载:
https://download.csdn.net/download/K86338236/89096170
在这里插入图片描述

VX


import DataManager from "../DataManager";
import Loading from "../Loading";
import Utils from "../Utils";

const { ccclass, property } = cc._decorator;
@ccclass
export default class WXSdk {

    protected static _instance: WXSdk = null;
    private _shareTime: number;
    private isShared: boolean = false;
    private isGroupShared: boolean = false;
    private _shareGroupCb: any = null;
    private _shareCb: any = null;
    private _shareFb: any = null;
    private _intersitialAd: any;
    InterstitialAdId: any;
    private _bannerAds: any = null;
    BannerIds: any = ["输入对应广告id"];
    private _rewardedVideoAd = null;
    WatchVAD: boolean = false;
    RewardedVideoAdId: any = ["输入对应广告id"];
    private _VideoAdcb = null;
    private _VideoAdfb = null;
    private _systemInfo: any;

    public static get Instance(): WXSdk {
        if (WXSdk._instance == null) {
            WXSdk._instance = new WXSdk();
        }
        return WXSdk._instance;
    }

    public data: any = null;
    public ShareTitle: string[] = [
        "据说好看的人到哪都是最高分",
        "快看,你是超不过我的!",
        "噗!我需要您的帮助",
        "@你,我已经超过了,快来和我决斗",
        "实力不允许我低调"
    ];
    public ShareImgId: string = '通过 MP 系统审核的图片编号'; // 通过 MP 系统审核的图片编号
    public ShareImgUrl: string = '通过 MP 系统审核的图片路径';

    init() {
        let sysInfo = window["wx"].getSystemInfoSync();
        this._systemInfo = sysInfo;
        this.createBannerAds();
    }
    
    init2() {
        this.createRewardedVideoAd();
    }

    showInterstitialAd() {
        if (!window["wx"]) {
            return;
        }
        if (!this._intersitialAd) {
            this.createInterstitialAd();
            return;
        }
        this._intersitialAd.show();
    }


    showRewardedVideoAd(index, cb, fb) {
        if (!window["wx"]) {
            return;
        }
        this._VideoAdcb = cb;
        this._VideoAdfb = fb;
        if (this._rewardedVideoAd) {
            this._rewardedVideoAd.show();
        }
        else {
            this.createRewardedVideoAd();
            setTimeout(() => {
                if (this._rewardedVideoAd) this._rewardedVideoAd.show();
            },1000)
        }
    }



    showBannerAd(index) {
        index = 0;
        if (!window["wx"]) {
            return;
        }
        if (!this._bannerAds) {
            return;
        }
        for (let i = 0; i < this._bannerAds.length; i++) {
            if (i != index) {
                this._bannerAds[i].hide();
            }
        }
        let node = cc.find("gamePanel");
        if (node && node.getComponent("gamePanel") && node.getComponent("gamePanel").gameState) return;
        console.log(index)
        if (this._bannerAds[index]) {
            console.log("this._bannerAds", this._bannerAds[index])
            this._bannerAds[index].show();
        }
    }

    hideBannerAd(index) {
        if (!window["wx"]) {
            return;
        }
        this.hideBannerAds();
        if (this._bannerAds && index < this._bannerAds.length && this._bannerAds[index]) {
            this._bannerAds[index].hide();
        }
    }

    //隐藏所有广告
    hideBannerAds() {
        if (!window["wx"]) {
            return;
        }
        if (!this._bannerAds) {
            return;
        }
        if (this._bannerAds && this._bannerAds.length != null) {
            if (this._bannerAds.length > 0) {
                for (var i = 0; i < this._bannerAds.length; i++) {
                    if (this._bannerAds && this._bannerAds[i]) {
                        this._bannerAds[i].hide();
                    }
                }
            }
        }
    }

    createBannerAds() {
        let winSize = this._systemInfo || window["wx"].getSystemInfoSync(); //wx.getSystemInfoSync();
        let bannerHeight = 130;
        let bannerWidth = 300;

        this._bannerAds = [];
        var length = this.BannerIds.length;
        for (let i = 0; i < length; i++) {
            //@ts-ignore
            let banner = wx.createBannerAd({
                adUnitId: this.BannerIds[i],
                adIntervals: 30,
                style: {
                    left: (winSize.windowWidth - bannerWidth) / 2,
                    top: winSize.windowHeight - bannerHeight,
                    width: bannerWidth,
                }
            });
            banner.onError(function (res) {
                console.log('banner, ', res);
            });
            this._bannerAds[i] = banner;
        }
    }

    createInterstitialAd() {
        let self = this;

        if (this._intersitialAd) {
            return;
        }

        //@ts-ignore
        this._intersitialAd = wx.createInterstitialAd({
            adUnitId: this.InterstitialAdId,
        })

        //console.log('this._intersitialAd=' + this._intersitialAd);
        this._intersitialAd.onError(function (res) {
            console.log('_intersitialAd, errMsg=' + JSON.stringify(res));
            // wx.showToast({
            //     title: 'load ad failed!',
            //     icon: 'success',
            //     duration: 2000
            // });
            setTimeout(() => {
                self.createInterstitialAd();
            }, 500);
        });
        this._intersitialAd.onClose(function (res) {
            console.log('_intersitialAd, onClose, res=' + JSON.stringify(res));
        });

        if (!this._intersitialAd) {
            setTimeout(() => {
                this.createInterstitialAd();
            }, 500);
            return;
        }
        this._intersitialAd.load();
        //this._intersitialAd.show();
    }

    shareAppMessage(i = 0, cb?, fb?) {
        console.log('shareAppMessage...');
        let self = this;
        let msg = self.ShareTitle[i];
        //@ts-ignore
        window["wx"].shareAppMessage({
            title: msg,
            imageUrlId: self.ShareImgId,
            imageUrl: self.ShareImgUrl,
            query: "id:" + DataManager.Instance.getPlayerId(),
        });
        this._shareTime = Utils.Instance.getCurTime();
        this.isShared = true;
        this._shareCb = cb;
        this._shareFb = fb;
    }

    createRewardedVideoAd(number = 0) {
        if (this._rewardedVideoAd) {
            return;
        }
        if (!window["wx"]) {
            return;
        }
        //@ts-ignore
        this._rewardedVideoAd = wx.createRewardedVideoAd({
            adUnitId: this.RewardedVideoAdId[0]
        });

        this._rewardedVideoAd.onError(function (res) {
            console.log('onError, _rewardedVideoAd, res=' + JSON.stringify(res));
        });

        this.WatchVAD = false;
        this._rewardedVideoAd.onClose((res) => {
            // 用户点击了【关闭广告】按钮
            // 小于 2.1.0 的基础库版本,res 是一个 undefined
            console.log(res)
            if (res && res.isEnded || res === undefined) {
                this.WatchVAD = true;
                if (this._VideoAdcb) this._VideoAdcb();
                DataManager.Instance.setVideoNum(1);
                this._VideoAdcb = null;
            }
            else {
                // 播放中途退出,不下发游戏奖励
                if (this._VideoAdfb) this._VideoAdfb();
                this._VideoAdfb = null;
            }
        });
        this._rewardedVideoAd.onError((err) => {
            if (this._VideoAdfb) this._VideoAdfb();
            this._VideoAdfb = null;
        });
        this._rewardedVideoAd.load();
        //this._rewardedVideoAd.show();
    }


    shareToGroupAppMessage(cb) {
        console.log('shareAppMessage...');
        let self = this;
        this._shareGroupCb = cb;
        //@ts-ignore
        window["wx"].shareAppMessage({
            title: self.ShareTitle[0],
            imageUrlId: self.ShareImgId,
            imageUrl: self.ShareImgUrl,
            query: "id:" + DataManager.Instance.getPlayerId(),
        });
        this.isGroupShared = true;
    }

    public getUserName(): string {
        if (WXSdk.Instance.data == null) {
            return "玩家";
        }
        else {
            return WXSdk.Instance.data.userInfo.nickName;
        }
    }
    public getAvatarURL(): string {
        if (WXSdk.Instance.data == null) {
            return "";
        }
        else {
            return WXSdk.Instance.data.userInfo.avatarUrl;
        }
    }
    public getLoginCode(): string {
        if (WXSdk.Instance.data == null) {
            return "";
        }
        else {
            return WXSdk.Instance.data.userInfo.avatarUrl;
        }
    }

    postDataToWX(score, now) {
        //向微信保存最高分数
        var kvDateList = new Array();
        kvDateList.push({
            key: "score",
            value: score + "",
        });
        kvDateList.push({
            key: "now",
            value: now + "",
        });
        console.log("托管游戏数据")
        console.log(kvDateList)
        //托管游戏数据
        //@ts-ignore
        wx.setUserCloudStorage({
            KVDataList: kvDateList,
            success: (res) => {
                console.log("托管游戏数据wx.setUserCloudStorage success");
                console.log(res);
            },
            fail: (res) => {
                console.log("托管游戏数据wx.setUserCloudStorage fail");
                console.log(res);
            }
        });
    }

    showShare() {
        //@ts-ignore
        wx.showShareMenu({
            withShareTicket: true,
            menus: ['shareAppMessage', 'shareTimeline']
        });
        //@ts-ignore
        wx.onShow((res) => {
            let curTime = Utils.Instance.getCurTime();
            if (this.isShared && (curTime - this._shareTime) >= 3 && (curTime - this._shareTime) < 60) {
                console.log("分享成功");
                this._shareTime = curTime;
                this.isShared = false;
                if (this._shareCb) {
                    this._shareCb();
                    this._shareCb = null;
                }
            }
            else if (this.isShared) {
                if (this._shareFb) {
                    this._shareFb();
                    this._shareFb = null;
                }
                this.isShared = false;
            }
            let shareTicket = res ? res.shareTicket : "";
            if (shareTicket && this.isGroupShared) {
                if (this._shareGroupCb) {
                    this._shareGroupCb(shareTicket);
                    this._shareGroupCb = null;
                }
                this.isGroupShared = false;
            }
        });
        //@ts-ignore
        wx.onShareAppMessage(() => {
            return {
                title: this.ShareTitle[0],
                imageUrlId: this.ShareImgId,
                imageUrl: this.ShareImgUrl,
            }
        });
    }


    public Login(cb?) {
        this.showShare();
        //@ts-ignore
        let sysInfo = wx.getSystemInfoSync();
        this._systemInfo = sysInfo;
        let width = sysInfo.screenWidth;
        let height = sysInfo.screenHeight;
        let self = this;
        console.log("请求用户信息");
        //@ts-ignore
        wx.getSetting({
            success(res) {
                console.log("res.authSetting:" + res.authSetting);
                if (res.authSetting["scope.userInfo"]) {
                    console.log("用户已授权");
                    //@ts-ignore
                    wx.getUserInfo({
                        success(res) {
                            console.log("用户授权:" + res);
                            console.log(res);
                            WXSdk.Instance.data = res;
                            //TODO: others
                            console.log("nickName:" + WXSdk.Instance.getUserName());
                            console.log("avatarUrl:" + WXSdk.Instance.getAvatarURL());
                            self.setLogin(cb, res);
                            let sysInfo = window["wx"].getSystemInfoSync();
                            self._systemInfo = sysInfo;
                        }
                    });
                }
                else {
                    console.log("用户未授权");
                    //用户未授权的话,全屏覆盖一个按钮,用户点击任意地方都会触发onTap(),弹出授权界面
                    //@ts-ignore
                    let button = wx.createUserInfoButton({
                        type: 'text',
                        text: '',//不显示文字
                        style: {
                            left: 0,
                            top: 0,
                            width: width,
                            height: height,
                            // lineHeight: 40,
                            backgroundColor: '#00000000',//设置按钮透明
                            color: '#ffffff',
                            textAlign: 'center',
                            fontSize: 16,
                            // borderRadius: 4
                        }
                    });
                    button.onTap(
                        (res) => {
                            if (res.userInfo) {
                                console.log("用户授权:" + res);
                                console.log(res);
                                WXSdk.Instance.data = res;
                                self.setLogin(cb, res);
                                //TODO:others
                                button.destroy();//此时删除按钮
                            }
                            else//说明用户点击 不允许授权的按钮
                            {
                                console.log("用户拒绝授权");
                                button.destroy();
                                self.Login(cb);
                            }
                        }
                    );
                }
            }
        });
    }

    setLogin(cb?, data = {}) {
        // let isWeChat = (cc.sys.platform === cc.sys.WECHAT_GAME);
        if (Loading.Instance.ApiType !== 1) {
            return;
        }
        let self = this;
        //@ts-ignore
        wx.login({
            success(res) {
                console.log('请求登录');
                console.log(res)
                if (res.code) {
                    console.log('微信登录成功!')
                    console.log(res)
                    //发起网络请求
                    if (cb) cb(res, data);
                } else {
                    setTimeout(() => {
                        self.setLogin(cb, data);
                    }, 500);
                    console.log('登录失败!' + res.errMsg)
                }
            },
            complete() {
                console.log('登录调用完成');
            },
            fail() {
                console.log('再次登录');
                setTimeout(() => {
                    self.setLogin(cb, data);
                }, 500);
            },
        })
    }
}

字节跳动,头条

import DataManager from "../DataManager";
import Utils from "../Utils";

const { ccclass, property } = cc._decorator;

@ccclass
export default class ZJTD_SDK {

    protected static _instance: ZJTD_SDK = null;
    private _shareTime: number;
    private isShared: boolean = false;
    private isGroupShared: boolean = false;
    private _shareGroupCb: any = null;
    private _shareCb: any = null;
    private _shareFb: any = null;
    private _intersitialAd: any;
    InterstitialAdId: any;
    private _bannerAds: any = null;
    BannerIds: any = ["b3grg0ha26r5e69gnl"];
    private _rewardedVideoAd = null;
    WatchVAD: boolean = false;
    RewardedVideoAdId: any = ["1yokp6sf82k256nm0l"];
    private _VideoAdcb = null;
    private _VideoAdfb = null;
    private _systemInfo: any;
    closeTime: number;
    AudioCloseTime: number;
    private _isAndroid: any;
    state: number = 0;
    RecorderManager: any;
    videoPath: string = "";
    private _wxUserInfo: any;

    public static get Instance(): ZJTD_SDK {
        if (ZJTD_SDK._instance == null) {
            ZJTD_SDK._instance = new ZJTD_SDK();
        }
        return ZJTD_SDK._instance;
    }

    public data: any = null;
    public ShareTitle: string[] = [
        "据说好看的人到哪都是最高分",
        "快看,你是超不过我的!",
        "噗!我需要您的帮助",
        "@你,我已经超过了,快来和我决斗",
        "实力不允许我低调"
    ];
    public ShareId: string[] = ['mgnnaie75lh886680j']; // 通过 MP 系统审核的图片编号



    init() {
        console.log('tt初始化');
        this.craetTTRecorder();
        this.createBannerAds();
        let sysInfo = window["tt"].getSystemInfoSync();
        this._systemInfo = sysInfo;
    }

    init2() {
    }

    shareAppMessage(i = 0, cb?, fb?) {
        console.log('shareAppMessage...');
        let self = this;
        this.isShared = true;
        this._shareCb = cb;
        this._shareFb = fb;
        window["tt"].shareAppMessage({
            title: "小白快冲",
            desc: this.ShareTitle[i],
            imageUrl: "",
            query: "id:" + DataManager.Instance.getPlayerId(),
            success() {
                console.log("分享成功");
                if (self._shareCb) {
                    self._shareCb();
                    self._shareCb = null;
                }
            },
            fail(e) {
                console.log("分享失败");
                if (self._shareFb) {
                    self._shareFb();
                    self._shareFb = null;
                }
            },
        });

        this.closeTime = Utils.Instance.getCurTime();
        this._shareTime = Utils.Instance.getCurTime();
    }

    showInterstitialAd() {
        if (!window["tt"]) {
            return;
        }
        if (!this._intersitialAd) {
            this.createInterstitialAd();
            return;
        }
        this._intersitialAd.show();
    }


    showRewardedVideoAd(index = 0, cb, fb) {
        var self = this;
        var id = 0;
        this.AudioCloseTime = new Date().getTime();
        //console.log("创建视频广告", index, id, this.RewardedVideoAdId, this.RewardedVideoAdId[id]);
        var videoAd = window["tt"].createRewardedVideoAd({
            adUnitId: self.RewardedVideoAdId[id]
        });
        videoAd.load();
        this._VideoAdcb = cb;
        this._VideoAdfb = fb;
        // 显示广告
        videoAd
            .show()
            .then(() => {
                console.log("广告显示成功");
                this.TTRecorderCheck(2);
            })
            .catch(err => {
                console.log("广告组件出现问题", err);
                // 可以手动加载一次
                videoAd.load().then(() => {
                    this.TTRecorderCheck(2);
                    console.log("手动加载成功");
                    // 加载成功后需要再显示广告
                    return videoAd.show();
                });
            });
        videoAd.onClose(res => {
            console.log("点击关闭视频", res);
            this.TTRecorderCheck(3);
            if (res.isEnded) {
                // 给予奖励
                this.WatchVAD = true;
                if (this._VideoAdcb) this._VideoAdcb();
                DataManager.Instance.setVideoNum(1);
                this._VideoAdcb = null;
            }
            else {
                /*
                if (require('GameMgr').Instance().ApiType === 2) {
                    let curTime = new Date().getTime();
                    console.log("看视频时间:", curTime, self.AudioCloseTime);
                    if (curTime - self.AudioCloseTime >= 10000) {
                        require('GameMgr').Instance().ShowADrewords();
                        // 正常播放结束,可以下发游戏奖励
                        require('GameMgr').Instance().setDaily(2);
                    }
                    else {*/
                if (this._VideoAdfb) this._VideoAdfb();
                this._VideoAdfb = null;
                return;
            }
        });

        if (!this._rewardedVideoAd) {
            return;
        }
    }



    showBannerAd(index) {
        index = 0;
        if (!window["tt"]) {
            return;
        }
        if (!this._bannerAds) {
            return;
        }
        for (let i = 0; i < this._bannerAds.length; i++) {
            if (i != index) {
                this._bannerAds[i].hide();
            }
        }
        console.log(index)
        if (this._bannerAds[index]) {
            console.log("this._bannerAds", this._bannerAds[index])
            this._bannerAds[index].show();
            this._bannerAds[index].onLoad(() => {
                this._bannerAds[index]
                    .show()
                    .then(() => {
                        console.log("底部广告显示成功");
                    })
                    .catch(err => {
                        console.log("底部广告组件出现问题", err);
                    });
            });
        }
    }

    //隐藏所有广告
    hideBannerAds() {
        if (!window["tt"]) {
            return;
        }
        if (!this._bannerAds) {
            return;
        }
        if (this._bannerAds && this._bannerAds.length != null) {
            if (this._bannerAds.length > 0) {
                for (var i = 0; i < this._bannerAds.length; i++) {
                    if (this._bannerAds && this._bannerAds[i]) {
                        this._bannerAds[i].hide();
                    }
                }
            }
        }
    }

    createBannerAds() {
        let winSize = this._systemInfo || window["tt"].getSystemInfoSync();; //window["tt"].getSystemInfoSync();
        let bannerHeight = 130;
        let bannerWidth = 300;
        console.log("廣告高度", (winSize.windowHeight - bannerHeight));

        this._bannerAds = [];
        var length = this.BannerIds.length;
        var self = this;
        for (let i = 0; i < length; i++) {
            var targetBannerAdWidth = 200;
            let banner = window["tt"].createBannerAd({
                adUnitId: self.BannerIds[i],
                adIntervals: 30,
                style: {
                    left: (winSize.windowWidth - bannerWidth) / 2,
                    top: winSize.windowHeight - (bannerHeight / 16) * 9 - 40,// 根据系统约定尺寸计算出广告高度
                    width: bannerWidth,
                }
            });
            //banner.style.left = (windowWidth - targetBannerAdWidth) / 2;
            banner.onError(function (res) {
                console.log('banner, ', res);
            });
            this._bannerAds[i] = banner;
        }
    }

    createInterstitialAd() {
        let self = this;

        if (this._intersitialAd) {
            return;
        }
        const isToutiaio = window["tt"].getSystemInfoSync().appName === "Toutiao";
        if (!this._isAndroid) {
            return;
        }
        // 插屏广告仅今日头条安卓客户端支持
        if (isToutiaio) {
            const interstitialAd = window["tt"].createInterstitialAd({
                adUnitId: this.InterstitialAdId
            });
            interstitialAd
                .load()
                .then(() => {
                    interstitialAd.show();
                })
                .catch(err => {
                    console.log(err);
                });
        }
    }

    craetTTRecorder() {
        this.state = 0;
        console.log('创建录屏');
        this.RecorderManager = window["tt"].getGameRecorderManager();
        if (!this.RecorderManager || !this.RecorderManager["start"]) return;
        //录屏开始
        this.RecorderManager.onStart((res) => {
            console.log('录屏开始');
            this.state = 1;
        });
        this.RecorderManager.onStop((res) => {
            let self = this;
            // if (this.RecorderManager["_duration"] && this.RecorderManager._duration >= 30) {
            //     this.RecorderManager.clipVideo({
            //         path: res.videoPath,
            //         timeRange: [10, 0],
            //         success(res1) {
            //             console.log(res1.videoPath); // 生成最后10秒的视频
            //             console.log('录屏结束');
            //             if (res1.videoPath) self.videoPath = res1.videoPath;
            //             if (self.videoPath) {
            //             }
            //             self.state = 0;
            //         },
            //         fail(e) {
            //             console.error(e);
            //             console.log(res.videoPath);
            //             console.log('录屏结束');
            //             self.state = 0;
            //         },
            //     });
            //     return;
            // }
            // else {
            this.state = 0;
            //}
            console.log(res.videoPath);
            console.log('录屏结束');
            this.videoPath = res.videoPath;
            if (this.videoPath) {
            }
        });
        this.RecorderManager.onInterruptionEnd(() => {
            this.TTRecorderCheck(2);
            console.log('录屏中断暂停');
        })
        this.RecorderManager.onInterruptionBegin(() => {
            this.TTRecorderCheck(3);
            console.log('录屏中断继续');
        })
        this.RecorderManager.onPause(() => {
            this.state = 2;
            console.log('录屏暂停');
        })
        this.RecorderManager.onResume(() => {
            this.state = 1;
            console.log('录屏继续');
        })
    }

    getVideoState() {
        return this.videoPath;
    }
    getVideoTime() {
        return this.RecorderManager._duration;
    }

    TTShareVideo(cb?) {
        if (!this.videoPath) {
            this.showToast("录制视频失败");
            if (cb) cb("faile");
            return;
        }
        window["tt"].shareAppMessage({
            channel: "video",
            title: "分享视频",
            desc: "分享精彩一刻",
            imageUrl: "",
            templateId: "", // 替换成通过审核的分享ID
            query: "",
            extra: {
                videoPath: this.videoPath, // 可替换成录屏得到的视频地址
                videoTopics: ["录屏分享", "小游戏"]
            },
            success() {
                console.log("分享视频成功");
                if (cb) cb(true);
            },
            fail(e) {
                console.log("分享视频失败", e);
                if (e.errMsg == "shareAppMessage:cancel") {
                    // "分享视频失败,录制时间过短"
                    if (cb) cb(false);
                    this.showToast("取消分享");
                }
                else {
                    if (cb) cb("faile");
                }
            }
        });
    }

    showToast(msg: string, state = "fail") {
        return;
        if (!window["tt"]) return;
        window["tt"].showToast({
            title: msg,
            duration: 2000,
            icon: state,
            success(res) {
                console.log(`${res}`);
            },
            fail(res) {
                console.log(`showToast 调用失败`);
            },
        });
    }

    TTRecorderCheck(state = 0) {
        console.log('录屏----', state, this.state);
        console.log(this.RecorderManager);
        if (!this.RecorderManager || !this.RecorderManager["start"]) return;
        if (this.state != 0 && state == 0) {
            console.log('录屏结束----');
            this.RecorderManager.stop();
        }
        else if (this.state == 0 && state == 1) {
            console.log('录屏开始---');
            this.RecorderManager.start({
                duration: 30,
            })
        }
        else if (this.state == 1 && state == 2) {
            console.log('录屏暂停---');
            this.RecorderManager.pause();
        }
        else if (this.state == 2 && state == 3) {
            console.log('录屏继续---');
            this.RecorderManager.resume()
        }
    }

    PYQshow() {
        window["tt"].hideShareMenu();
    }

    PYQhid() {
        window["tt"].hideShareMenu();
    }


    postDataToWX(score, now) {
        //向微信保存最高分数
        var kvDateList = new Array();
        kvDateList.push({
            key: "score",
            value: score + "",
        });
        kvDateList.push({
            key: "now",
            value: now + "",
        });
        console.log("托管游戏数据")
        console.log(kvDateList)
        //托管游戏数据
        //@ts-ignore
        window["tt"].setUserCloudStorage({
            KVDataList: kvDateList,
            success: (res) => {
                console.log("托管游戏数据tt.setUserCloudStorage success");
                console.log(res);
            },
            fail: (res) => {
                console.log("托管游戏数据tt.setUserCloudStorage fail");
                console.log(res);
            }
        });
    }

    setLogin(cb?) {
        if (!window["tt"]) {
            return;
        }
        let self = this;

        window["tt"].login({
            success(res) {
                console.log('字节跳动请求登录');
                console.log(res)
                if (res.code) {
                    console.log('字节跳动登录成功!')
                    console.log(res)
                    //发起网络请求
                    if (cb) cb(res);
                } else {
                    setTimeout(() => {
                        self.setLogin(cb);
                    }, 500);
                    console.log('登录失败!' + res.errMsg)
                }
            },
            complete() {
                console.log('登录调用完成');
            },
            fail(err) {
                console.log(err);
                console.log('再次登录');
                setTimeout(() => {
                    self.setLogin(cb);
                }, 500);
            }
        })
    }

    /**
     * 获取微信信息
     */
    getWeiXinInfo(cb?) {
        let self = this;

        window["tt"].showShareMenu({
        });

        window["tt"].onShareAppMessage(function (res) {
            //当监听到用户点击了分享或者拍抖音等按钮后,会执行该函数
            console.log(res.channel);
            // do something
            return {
                //执行函数后,这里是需要该函数返回的对象
                title: "小白快冲",
                // imageUrl: "https://example.com/test.png",

                desc: this.ShareTitle[0],
                query: "",
                success() {
                    console.log("分享成功");
                    if (self._shareCb) {
                        self._shareCb();
                        self._shareCb = null;
                    }
                },
                fail(e) {
                    console.log("分享失败");
                    if (self._shareFb) {
                        self._shareFb();
                        self._shareFb = null;
                    }
                }
            }; //返回的对象会传入tt.shareAppMessage进行最终分享
        });

        window["tt"].onShow((para) => {
            //console.log('onShow...' + JSON.stringify(para));
            // 用户点击了【关闭广告】按钮
            // 小于 2.1.0 的基础库版本,res 是一个 undefined
            console.log("this.WatchVAD", this.WatchVAD);
            if (this.WatchVAD) {
                // 正常播放结束,可以下发游戏奖励
            }
        });

        window["tt"].onHide(function (para) {
            //console.log('onHide...' + JSON.stringify(para));
        });
        let sysInfo = window["tt"].getSystemInfoSync();

        this._systemInfo = sysInfo;

        self.setLogin((data) => {
            this.getSetting(cb, data);
        });
    }

    getSetting(cb, data?) {
        let self = this;
        window["tt"].getSetting({
            success(res) {
                console.log("用户授权1", res);
                if (res.authSetting["scope.userInfo"]) {
                    //console.log("用户已授权");
                    window["tt"].getUserInfo({
                        success(res1) {
                            //console.log(res);
                            //self._wxUserInfo = res.userInfo;
                            //此时可进行登录操作
                            // console.log('this._wxUserInfo=' + JSON.stringify(self._wxUserInfo));
                            console.log("用户授权:", res1);
                            console.log(res1);
                            // ZJTD_SDK.Instance.data = res;

                            // let sysInfo = window["tt"].getSystemInfoSync();
                            // self._systemInfo = sysInfo;
                            //self.setLogin(cb, res.data);
                            if (cb) cb(data, res1["userInfo"]);
                        }
                    });
                } else {
                    window["tt"].openSetting();
                    window["tt"].authorize({
                        scope: "scope.userInfo",
                        success(res2) {
                            console.log("scope.userInfo", res2);
                            // self._wxUserInfo = res.userInfo;
                            //此时可进行登录操作
                            // console.log('this._wxUserInfo=' + JSON.stringify(this._wxUserInfo));
                            console.log("用户授权:", res2);
                            console.log(res2);
                            //ZJTD_SDK.Instance.data = res;

                            //let sysInfo = window["tt"].getSystemInfoSync();
                            // self._systemInfo = sysInfo;
                            //self.setLogin(cb, res.data);
                            if (cb) cb(data, res2["userInfo"]);
                        }
                    });
                }
            }
        });
    }

}

vivo

// Learn cc.Class:
//  - [Chinese] https://docs.cocos.com/creator/manual/zh/scripting/class.html
//  - [English] http://docs.cocos2d-x.org/creator/manual/en/scripting/class.html
// Learn Attribute:
//  - [Chinese] https://docs.cocos.com/creator/manual/zh/scripting/reference/attributes.html
//  - [English] http://docs.cocos2d-x.org/creator/manual/en/scripting/reference/attributes.html
// Learn life-cycle callbacks:
//  - [Chinese] https://docs.cocos.com/creator/manual/zh/scripting/life-cycle-callbacks.html
//  - [English] https://www.cocos2d-x.org/docs/creator/manual/en/scripting/life-cycle-callbacks.html


var curMod = cc.Class({
    extends: cc.Component,

    properties: {
        // foo: {
        //     // ATTRIBUTES:
        //     default: null,        // The default value will be used only when the component attaching
        //                           // to a node for the first time
        //     type: cc.SpriteFrame, // optional, default is typeof default
        //     serializable: true,   // optional, default is true
        // },
        // bar: {
        //     get () {
        //         return this._bar;
        //     },
        //     set (value) {
        //         this._bar = value;
        //     }
        // },
    },

    statics: {
        _instance: null,
        InterstitialAdId: '54b7154fcc594b4e9353170ca703ed49',
        RewardedVideoAdId: ['7e15bb05747a48c7a22477b3e86d8dbb'],
        BannerIds: ['951d8ba45a6d4b85b2395b15cbf187ef'],
        NativeAds: ["eb524542dc3f47488b229c13c7b25f07"],

        ShareTitle: '高分全凭手速快!',
        //ShareImgId: '通过 MP 系统审核的图片编号', // 通过 MP 系统审核的图片编号
        //ShareImgUrl: '通过 MP 系统审核的图片地址',

        _wxUserInfo: {},
        _systemInfo: {},

        Instance() {
            return curMod._instance;
        },
        GetInfo() {
            return curMod._wxUserInfo;
        },
    },

    onLoad() {
        console.log('vivo onload, curMod._instance=', curMod._instance);
        if (curMod._instance) {
            return;
        }
        curMod._instance = this;

        if (require('GameMgr').Instance().ApiType !== 3) {
            return;
        }
        //...
        //this.setLogin();//用户登录,获取用户信息
        this.getVivoInfo();
    },

    start() {
    },

    // update (dt) {},
    //分享
    shareAppMessage() {
        return;
        if (require('GameMgr').Instance().ApiType !== 3) {
            return;
        }
        var self = this;
        qg.share({
            success: function () {
                qg.showToast({
                    message: "分享成功"
                });
                require('GameMgr').Instance().setDaily(5);
                require('GameMgr').Instance().ShowADrewords();
                this.isShared = true;
            },
            fail: function (erromsg, errocode) {
                require('GameMgr').Instance().showTip("分享失败,请稍后再试", 0, "取消", "确定", function () {
                }, function () { return; });
                qg.showToast({
                    message: "分享失败:" + errocode + ': ' + erromsg
                });
            },
            cancel: function () {
                require('GameMgr').Instance().showTip("分享取消,获取奖励失败", 0, "取消", "确定", function () {
                }, function () { return; });
                qg.showToast({
                    message: "分享完成"
                });
            },
            complete: function () {
                qg.showToast({
                    message: "分享调用完成"
                });
            },
        });
    },
    //显示原生广告
    initNativeAd() {
        var self = this;
        var Timeout = 20000;
        var str = cc.sys.localStorage.getItem('lastNativeAdTime');//读取数据
        if (!str) {
            self.lastTime = 0;
        }
        else {
            self.lastTime = parseInt(parseInt((str)));//转为json格式id
        }
        var nowTime = new Date().getTime();
        console.log('广告间隔时间', nowTime, self.lastTime, nowTime - self.lastTime, Timeout)
        if (nowTime - self.lastTime >= Timeout) {
            self.lastTime = nowTime;
            cc.sys.localStorage.setItem('lastNativeAdTime', self.lastTime + "");
        }
        else {
            return;
        }

        const nativeAd = qg.createNativeAd({
            posId: curMod.NativeAds[0],
        });

        var self = this;
        nativeAd.onLoad(function (res) {
            var self1 = self;
            self1.res = res;
            console.log('原生广告加载完成-onload触发', JSON.stringify(res));
            require("SeverLink").Instance().Burialpoint("adsClick", { t: 1, ApiType: require('GameMgr').Instance().ApiType });
            var data = res.adList[0];
            nativeAd.reportAdShow({ adId: res.adList[0].adId.toString() });
            var fun = function () {
                console.log('点击原生广告');
                if (nativeAd) {
                    nativeAd.reportAdClick({ adId: self1.res.adList[0].adId.toString() });
                    nativeAd.offLoad();
                }
            };
            var fun2 = function () {
                console.log('关闭原生广告');
                if (nativeAd) {
                    nativeAd.offLoad();
                }
            };
            require("ADShow").OpenPanel(data.imgUrlList[0], data.icon, fun, true, data.desc, fun2);
            // 原生广告在没有被曝光或者点击的情况下,再去拉去原生广告就会返回空广告
            // 所以load完要去执行reportAdShow和reportAdClick 才能正常拉取下一条广告
            // 注意:需要先调用reportAdShow上报广告曝光,才能调用reportAdClick去上报点击!!!
        })
        nativeAd.onError(err => {
            console.log("原生广告加载异常", JSON.stringify(err));
        });
    },

    //显示插屏广告
    showInterstitialAd(i) {
        if (require('GameMgr').Instance().ApiType !== 3) {
            return;
        }
        if (i === 0) {
            this.initNativeAd();
            return;
        }
        var self = this;
        var Timeout = 10000;
        var str = cc.sys.localStorage.getItem('lastTime');//读取数据
        if (!str) {
            self.lastTime = 0;
        }
        else {
            self.lastTime = parseInt(parseInt((str)));//转为json格式id
        }
        var nowTime = new Date().getTime();
        console.log('广告间隔时间', nowTime, self.lastTime, nowTime - self.lastTime, Timeout)
        if (nowTime - self.lastTime >= Timeout) {
            self.lastTime = nowTime;
            cc.sys.localStorage.setItem('lastTime', self.lastTime + "");
        }
        else {
            return;
        }

        let interstitialAd = qg.createInterstitialAd({
            posId: curMod.InterstitialAdId
        });
        let adShow = interstitialAd.show();
        adShow && adShow.then(() => {
            console.log("插屏广告展示成功");
        }).catch((err) => {
            switch (err.code) {
                case 30003:
                    console.log("新用户1天内不能曝光Banner,请将手机时间调整为1天后,退出游戏重新进入")
                    break;
                case 30009:
                    console.log("10秒内调用广告次数超过1次,10秒后再调用")
                    // setTimeout(() => {
                    //     show()
                    // }, 10000);
                    break;
                case 30002:
                    console.log("load广告失败,重新加载广告")
                    // setTimeout(() => {
                    //     retryShow()
                    // }, 10000);  
                    break;
                default:
                    // 参考 https://minigame.vivo.com.cn/documents/#/lesson/open-ability/ad?id=广告错误码信息 对错误码做分类处理
                    console.log("插屏广告展示失败")
                    console.log(JSON.stringify(err))

                    break;
            }
        });
    },
    //显示视频广告
    showRewardedVideoAd(index) {
        if (require('GameMgr').Instance().ApiType !== 3) {
            return;
        }// showToast 上线之前一定要去掉!
        // 错误的回调,creat的是在onerror里面,load,show等的回调在自己的catch里面
        var self = this;
        this.isRewardedVideo = true;
        require('GameMgr').Instance().StopBgm();
        index = 0;
        console.log("激励广告加载", index);
        let rewardedAd;
        rewardedAd = qg.createRewardedVideoAd({
            posId: curMod.RewardedVideoAdId[index]
        });
        rewardedAd.onError(err => {
            self.isRewardedVideo = false;
            require('GameMgr').Instance().resumeBgm();
            switch (err.errCode) {
                case -3:
                    console.log("激励广告加载失败---调用太频繁", JSON.stringify(err));
                    require("TipShow").Instance().showTip("广告加载失败,观看太频繁\n请稍后再试" + err, 1, function () {
                    })
                    break;
                case -4:
                    console.log("激励广告加载失败--- 一分钟内不能重复加载", JSON.stringify(err));
                    require("TipShow").Instance().showTip("广告加载失败\n一分钟内不能重复加载\n请稍后再试" + err, 1, function () {
                    })
                    break;
                case 30008:
                    // 当前启动来源不支持激励视频广告,请选择其他激励策略
                    break;
                default:
                    // 参考 https://minigame.vivo.com.cn/documents/#/lesson/open-ability/ad?id=广告错误码信息 对错误码做分类处理
                    console.log("激励广告展示失败")
                    console.log(JSON.stringify(err))
                    require("TipShow").Instance().showTip("视频获取失败请稍后重试\n", 1, function () {
                    })
                    break;
            }
        })

        rewardedAd.onClose(res => {
            self.isRewardedVideo = false;
            if (res && res.isEnded) {
                console.log("正常播放结束,可以下发游戏奖励");
                require('GameMgr').Instance().WadBack();
            } else {
                console.log("播放中途退出,不下发游戏奖励");
                require('GameMgr').Instance().WadBack2();
            }
            require('GameMgr').Instance().resumeBgm();
        });

        // 第一次creat后广告可以在onload里面直接show
        // 后续的加载必须要load才能触发onload接着才能show出广告
        let adLoad = rewardedAd.load();//第一次调用 可能会报-3  广告能正常展示就可以忽略
        // 捕捉load失败的错误
        adLoad && adLoad.catch(err => {
            console.log("激励广告load失败" + JSON.stringify(err));
        })
        rewardedAd.onLoad(() => {
            let adshow = rewardedAd.show();
            require('GameMgr').Instance().StopBgm();
            // 捕捉show失败的错误
            adshow && adshow.catch(err => {
                console.log("激励广告展示失败" + JSON.stringify(err));
                //require("TipShow").Instance().showTip("视频获取失败请稍后重试\n" + err, 1, function () {                //})
            })
        })
    },

    //显示底部广告
    showBannerAd(index, fun) {
        if (require('GameMgr').Instance().ApiType !== 3) {
            return;
        }
        if (fun) {
            fun();
        }
        var self = this;
        var Timeout = 10000;
        var str = cc.sys.localStorage.getItem('lastBannerTime');//读取数据
        if (!str) {
            self.lastTime = 0;
        }
        else {
            self.lastTime = parseInt(parseInt((str)));//转为json格式id
        }
        var nowTime = new Date().getTime();
        console.log('Banner广告间隔时间', nowTime, self.lastTime, nowTime - self.lastTime, Timeout)
        if (nowTime - self.lastTime >= Timeout) {
            self.lastTime = nowTime;
            cc.sys.localStorage.setItem('lastBannerTime', self.lastTime + "");
        }
        else {
            return;
        }

        index = 0;
        console.log("创建banner广告", index);
        this._bannerAds = qg.createBannerAd({
            posId: curMod.BannerIds[index],
            style: {}
        });
        let adshow = this._bannerAds.show();
        // 调用then和catch之前需要对show的结果做下判空处理,防止出错(如果没有判空,在平台版本为1052以及以下的手机上将会出现错误)
        var self = this;
        adshow && adshow.then(() => {
            console.log("banner广告展示成功");
        }).catch((err) => {
            switch (err.code) {
                case 30003:
                    console.log("新用户1天内不能曝光Banner,请将手机时间调整为1天后,退出游戏重新进入")
                    break;
                case 30009:
                    console.log("10秒内调用广告次数超过1次,10秒后再调用")
                    // setTimeout(() => {
                    //     show()
                    // }, 10000);
                    break;
                case 30002:
                    console.log("加载广告失败,重新加载广告")
                    setTimeout(() => {
                        self.retryShow();
                    }, 10000);
                    break;
                default:
                    // 参考 https://minigame.vivo.com.cn/documents/#/lesson/open-ability/ad?id=广告错误码信息 对错误码做分类处理
                    console.log("banner广告展示失败")
                    console.log(JSON.stringify(err))
                    break;
            }
        });
    },
    //banner重加载
    retryShow() {
        if (require('GameMgr').Instance().ApiType !== 3) {
            return;
        }
        let bannerAdRetey = qg.createBannerAd({
            posId: curMod.BannerIds[0],
            style: {}
        })
        let adShowRetry = bannerAdRetey.show()
        adShowRetry && adShowRetry.catch((error) => {
            console.log("banner广告展示失败-重试")
            console.log(JSON.stringify(error))
        })
    },

    //隐藏所有底部广告
    hideBannerAds() {
        if (require('GameMgr').Instance().ApiType !== 3) {
            return;
        }
        if (this._bannerAds) {
            var adhide = this._bannerAds.hide();
            adhide && adhide.then(() => {
                console.log("banner广告隐藏成功");
                this._bannerAds = "";
            }).catch(err => {
                console.log("banner广告隐藏失败", JSON.stringify(err));
            });
        }
    },


    setLogin() {
        var id = require('GameMgr').Instance().ApiType;
        console.log("渠道ID:" + id);
        var self = this;
        if (require('GameMgr').Instance().ApiType === 3) {
            if (qg.getSystemInfoSync().platformVersionCode >= 1053) {
                qg.login().then((res) => {
                    console.log("登录成功", res);
                    console.log(res);
                    self.getVivoInfo();
                }, (err) => {
                    console.log('登录失败' + JSON.stringify(err));
                    //self.setLogin(); // 重新登录
                    //cc.director.loadScene('LoadScene');
                });
            }
        }
    },
    /**
     * 获取微信信息
     */
    getVivoInfo() {
        //获取登录信息
        if (qg.getSystemInfoSync().platformVersionCode >= 1053) {
            qg.getUserInfo().then((res) => {
                if (res.data) {
                    console.log('当前用户信息: ' + JSON.stringify(res.data));
                    curMod._wxUserInfo = res.data;
                    var imgurl = res.data.smallAvatar + "?aaa=aa.jpg";
                    var name = res.data.nickName;
                    require('GameMgr').Instance().SetplMsg(imgurl, name);
                }
            }, (err) => {
                console.log('获取用户信息失败' + JSON.stringify(err));
            });
        }
        qg.onHide(function () {
            require('GameMgr').Instance().StopBgm();
        });
        qg.onShow(function () {
            require("energyMgr").Instance().setTili();
            if (this.isRewardedVideo) {
                return;
            }
            require('GameMgr').Instance().resumeBgm();
        });
    },

    CheckHave(fun) {
        if (require('GameMgr').Instance().ApiType !== 3) {
            return;
        }
        qg.hasShortcutInstalled({
            success: function (res) {
                // 判断图标未存在时,创建图标
                console.log("创建图标");
                if (res == true) {
                    fun();
                }
            },
            fail: function (err) {
            },
        });
    },

    onCreatDeskIco(fun) {
        if (require('GameMgr').Instance().ApiType !== 3) {
            return;
        }
        qg.hasShortcutInstalled({
            success: function (res) {
                // 判断图标未存在时,创建图标
                if (res == false) {
                    qg.installShortcut({
                        success: function () {
                            // 执行用户创建图标奖励
                            fun();
                            console.log("执行用户创建图标奖励");
                        },
                        fail: function (err) { },
                        complete: function () { }
                    })
                }
            },
            fail: function (err) { },
            complete: function () { }
        })
    },

    printInfo(res) {
        // console.log('设备品牌:', res.brand)
        // console.log('设备型号:', res.model)
        // console.log('设备像素比:', res.pixelRatio)
        // console.log('屏幕宽度:', res.windowWidth)
        // console.log('屏幕高度:', res.windowHeight)
        // console.log('状态栏的高度:', res.statusBarHeight)
        // console.log('微信设置的语言:', res.language)
        // console.log('微信版本号:', res.version)
        // console.log('操作系统及版本:', res.system)
        // console.log('客户端平台:', res.platform)
        // console.log('用户字体大小:', res.fontSizeSetting)
        // console.log('客户端基础库版本 :', res.SDKVersion)
        // console.log('设备性能等级:', res.benchmarkLevel)
        if (res.system.indexOf('Android') != -1) {
            curMod._isAndroid = true;
        }
    },
});

oppo



// Learn cc.Class:
//  - [Chinese] https://docs.cocos.com/creator/manual/zh/scripting/class.html
//  - [English] http://docs.cocos2d-x.org/creator/manual/en/scripting/class.html
// Learn Attribute:
//  - [Chinese] https://docs.cocos.com/creator/manual/zh/scripting/reference/attributes.html
//  - [English] http://docs.cocos2d-x.org/creator/manual/en/scripting/reference/attributes.html
// Learn life-cycle callbacks:
//  - [Chinese] https://docs.cocos.com/creator/manual/zh/scripting/life-cycle-callbacks.html
//  - [English] https://www.cocos2d-x.org/docs/creator/manual/en/scripting/life-cycle-callbacks.html

//const Req = require("GameReqs");

const SDK = require("SDKUtil");

var curMod = cc.Class({
    extends: cc.Component,

    properties: {
        // foo: {
        //     // ATTRIBUTES:
        //     default: null,        // The default value will be used only when the component attaching
        //                           // to a node for the first time
        //     type: cc.SpriteFrame, // optional, default is typeof default
        //     serializable: true,   // optional, default is true
        // },
        // bar: {
        //     get () {
        //         return this._bar;
        //     },
        //     set (value) {
        //         this._bar = value;
        //     }
        // },
    },

    statics: {
        _instance: null,
        InterstitialAdId: '189798',
        RewardedVideoAdId: ['181997'],
        BannerIds: ['181996'], //, 'adunit-905904089942c58e'],
        NativeAds: ["182001", "182002", "182000", "185492"],

        ShareTitle: '1sptkc92obm2siacp3',
        ShareImgId: '5JWEBFBdTHiZ5EcslmutbA==', // 通过 MP 系统审核的图片编号
        //ShareImgUrl: 'https://mmocgame.qpic.cn/wechatgame/3gfJUsiaHCx28sibf4QvxkWEwK6UicbQricJn4M7ia9OoUIPaDXXn1tib6eSZWtpu7hOGz/0',

        _wxUserInfo: {},
        _systemInfo: {},

        Instance() {
            return curMod._instance;
        },

        GetInfo() {
            return curMod._wxUserInfo;
        },
    },

    onLoad() {
        console.log('vivo onload, curMod._instance=', curMod._instance);
        if (curMod._instance) {
            return;
        }
        curMod._instance = this;
        //...
        if (require('GameMgr').Instance().ApiType !== 4) {
            return;
        }
        //return;
        this.getOppoInfo();//用户登录,获取用户信息
    },

    start() {
    },

    // update (dt) {},
    //分享
    shareAppMessage() {
        if (require('GameMgr').Instance().ApiType !== 4) {
            return;
        }
        var self = this;
    },


    CheckHave(fun) {
        if (require('GameMgr').Instance().ApiType !== 4) {
            return;
        }
        qg.hasShortcutInstalled({
            success: function (res) {
                // 判断图标未存在时,创建图标
                console.log("创建图标");
                if (res == true) {
                    fun();
                }
            },
            fail: function (err) {
            },
        });
    },


    onCreatDeskIco(fun) {
        if (require('GameMgr').Instance().ApiType !== 4) {
            return;
        }
        qg.hasShortcutInstalled({
            success: function (res) {
                // 判断图标未存在时,创建图标
                if (res == false) {
                    qg.installShortcut({
                        success: function () {
                            // 执行用户创建图标奖励
                            fun();
                            console.log("执行用户创建图标奖励");
                        },
                        fail: function (err) { },
                        complete: function () { }
                    })
                }
            },
            fail: function (err) { },
            complete: function () { }
        })
    },

    //显示插屏广告
    showInterstitialAd() {
        if (require('GameMgr').Instance().ApiType !== 4) {
            return;
        }
        //this.showNativeAd(1);
        var self = this;
        var Timeout = 30000;
        var fun = function () {
            Timeout = 10000;
            var str = cc.sys.localStorage.getItem('lastTime');//读取数据
            if (!str) {
                self.lastTime = 0;
            }
            else {
                self.lastTime = parseInt(parseInt((str)));//转为json格式id
            }
            var nowTime = new Date().getTime();
            console.log('广告间隔时间', nowTime, self.lastTime, nowTime - self.lastTime, Timeout)
            if (nowTime - self.lastTime >= Timeout) {
                self.lastTime = nowTime;
                cc.sys.localStorage.setItem('lastTime', self.lastTime + "");
                self.showNativeAd(0);
            }
            else {
                return;
            }
        }

        var fun2 = function () {
            var str = cc.sys.localStorage.getItem('lastTime');//读取数据
            if (!str) {
                self.lastTime = 0;
            }
            else {
                self.lastTime = parseInt(parseInt(str));//转为json格式id
            }
            var nowTime = new Date().getTime();
            console.log('广告间隔时间', nowTime, self.lastTime, nowTime - self.lastTime, Timeout)
            if (nowTime - self.lastTime >= Timeout) {
                self.lastTime = nowTime;
                cc.sys.localStorage.setItem('lastTime', self.lastTime + "");
                self.showNativeAd(0);
            }
            else {
                return;
            }
        }
        require('SeverLink').Instance().SeverLink(1, fun, fun2, fun2);
        return;
        this.interstitialAd = qg.createInsertAd({
            adUnitId: curMod.InterstitialAdId
        })
        if (!this.interstitialAd) {
            return;
        }
        this.interstitialAd.load();

        this.interstitialAd.onLoad(function () {
            this.interstitialAd.show();
            console.log('插屏视频广告加载')
        });

        this.interstitialAd.onError(function (err) {
            console.log(err.errCode, err.errMsg)
            console.log("插屏视频广告加载失败", err)
        });
        /*
                interstitialVideoAd.onClose(function () {
                    console.log('插屏视频广告关闭')
                });
                interstitialVideoAd.onShow(function () {
                    console.log('插屏视频广告展示')
                });
        */
    },

    //显示插屏广告
    creatInterstitialAd() {
        if (require('GameMgr').Instance().ApiType !== 4) {
            return;
        }
        var self = this;
        console.log('显示插屏广告')
        //return;
        this.interstitialAd = qg.createInsertAd({
            adUnitId: curMod.InterstitialAdId
        })
        if (!this.interstitialAd) {
            //return;
        }
        this.interstitialAd.load();
        this.interstitialAd.onLoad(function () {
            console.log('插屏广告加载')
            self.interstitialAd.show();
        });

        this.interstitialAd.onError(function (err) {
            console.log(err.errCode, err.errMsg)
            console.log("插屏广告加载失败", err)
            console.log(JSON.parse(err));
        });
        /*
                interstitialVideoAd.onClose(function () {
                    console.log('插屏视频广告关闭')
                });
                interstitialVideoAd.onShow(function () {
                    console.log('插屏视频广告展示')
                });
        */
    },

    hideInAd() {
        if (require('GameMgr').Instance().ApiType !== 4) {
            return;
        }
        if (this.interstitialAd) {
            this.interstitialAd.destroy();
        }
    },
    //显示原生插屏广告
    showNativeAd(i, callback) {
        if (require('GameMgr').Instance().ApiType !== 4) {
            //require("ADShow").OpenPanel("", "", () => { });
            return;
        }
        if (i === 0) {
            return;
        }
        var self = this;
        console.log("显示原生插屏广告");
        var nativeAd = qg.createNativeAd({
            adUnitId: curMod.NativeAds[i],
        })
        if (!nativeAd) {
            console.log("显示原生插屏广告获取失败");
            return;
        }
        nativeAd.load();

        if (callback) {
            callback();
        }
        nativeAd.onLoad(function (res) {
            console.log('原生广告加载', JSON.stringify(res.adList));
            if (!res.adList[0]) {
                self.creatInterstitialAd();
                return;
            }
            var id = res.adList[0].adId;
            nativeAd.reportAdShow({
                adId: id,
            });
            var fun = function () {
                console.log('点击原生广告');
                nativeAd.reportAdClick({
                    adId: id,
                });
                nativeAd.offLoad();
                nativeAd.offError();
                nativeAd.destroy();
            };
            var fun2 = function () {
                console.log('关闭原生广告');
                nativeAd.offLoad();
                nativeAd.offError();
                nativeAd.destroy();
            };
            if (i === 3) {
                require("SeverLink").Instance().Burialpoint("adsClick", { t: 2, ApiType: require('GameMgr').Instance().ApiType });
                require("ADShow3").OpenPanel(res.adList[0].imgUrlList[0], res.adList[0].icon, fun, false, res.adList[0].desc, fun2);
                return;
            }
            if (res.adList[0].creativeType === 6) {
                require("SeverLink").Instance().Burialpoint("adsClick", { t: 1, ApiType: require('GameMgr').Instance().ApiType });
                require("ADShow").OpenPanel(res.adList[0].imgUrlList[0], res.adList[0].icon, fun, true, res.adList[0].desc, fun2);
            }
            else if (res.adList[0].creativeType === 3) {
                require("SeverLink").Instance().Burialpoint("adsClick", { t: 3, ApiType: require('GameMgr').Instance().ApiType });
                require("ADShow2").OpenPanel(res.adList[0].icon, res.adList[0].icon, fun, false, res.adList[0].desc, fun2);
            }
        });

        nativeAd.onError(function (err) {
            console.log(err.errCode, err.errMsg);
            console.log("原生广告加载失败", JSON.stringify(err), i);
            if (i < 3) {
                self.creatInterstitialAd();
            }
            else {
                self.showBannerAd2(0);
            }
            nativeAd.destroy();
        });
        /*
                interstitialVideoAd.onClose(function () {
                    console.log('插屏视频广告关闭')
                });
                interstitialVideoAd.onShow(function () {
                    console.log('插屏视频广告展示')
                });
        */
    },
    //显示视频广告
    showRewardedVideoAd(index) {
        if (require('GameMgr').Instance().ApiType !== 4) {
            return;
        }// showToast 上线之前一定要去掉!
        // 错误的回调,creat的是在onerror里面,load,show等的回调在自己的catch里面
        var self = this;
        this.isRewardedVideo = true;
        require('GameMgr').Instance().StopBgm();
        console.log("激励广告加载", index);
        index = 0;
        let rewardedAd;
        rewardedAd = qg.createRewardedVideoAd({
            adUnitId: curMod.RewardedVideoAdId[index]
        });

        rewardedAd.load();
        var loadcount = 0;
        rewardedAd.onLoad(function () {
            console.log('激励视频加载成功')
            rewardedAd.show();
            require("SeverLink").Instance().Burialpoint("adsClick", { t: 4, ApiType: require('GameMgr').Instance().ApiType });
        })

        rewardedAd.onClose(function (res) {
            loadcount++;
            if (loadcount > 1) {
                return;
            }
            if (res.isEnded) {
                console.log('激励视频广告完成,发放奖励')
                require('GameMgr').Instance().WadBack();
            } else {
                console.log('激励视频广告取消关闭,不发放奖励')
                require('GameMgr').Instance().WadBack2();
            }
            require('GameMgr').Instance().resumeBgm();
            self.isRewardedVideo = false;
        })
        rewardedAd.onError(function (err) {
            console.log(err, "视频获取失败请稍后重试");
            console.log(JSON.parse(err));
            //require("TipShow").Instance().showTip("视频获取失败请稍后重试\n", 1, function () {
            //})
            rewardedAd.show();
        })
    },

    //显示底部广告
    showBannerAd(index, callback) {
        if (require('GameMgr').Instance().ApiType !== 4) {
            return;
        }
        this.showNativeAd(3, callback);
        return;
        index = 0;
        console.log("创建banner广告", index);


        var windowSize = cc.winSize;

        let bannerHeight = 300;
        let bannerWidth = windowSize.width;

        this._bannerAds = qg.createBannerAd({
            adUnitId: curMod.BannerIds[index],
            style: {
            }
        });
        this._bannerAds.show();
        this._bannerAds.onError(function (err) {
            console.log("banner广告展示失败");
            console.log(err);
        })
        if (callback) {
            callback();
        }
        /*
        this._bannerAds.onLoad(function () {
            console.log('banner广告加载');
            if (callback) {
                callback();
            }
        });*/
    },
    //显示底部广告
    showBannerAd2(index, callback) {
        if (require('GameMgr').Instance().ApiType !== 4) {
            return;
        }
        index = 0;
        console.log("创建banner广告", index);


        var windowSize = cc.winSize;

        let bannerHeight = 300;
        let bannerWidth = windowSize.width;

        this._bannerAds = qg.createBannerAd({
            adUnitId: curMod.BannerIds[index],
            style: {
            }
        });
        this._bannerAds.show();
        this._bannerAds.onError(function (err) {
            console.log("banner广告展示失败");
            console.log(err);
            console.log(JSON.parse(err));
        })
        if (callback) {
            callback();
        }
        /*
        this._bannerAds.onLoad(function () {
            console.log('banner广告加载');
            if (callback) {
                callback();
            }
        });*/
    },

    //banner重加载
    retryShow() {
        if (require('GameMgr').Instance().ApiType !== 4) {
            return;
        }
        let bannerAdRetey = qg.createBannerAd({
            posId: 'xxxxx',
            style: {}
        })
        let adShowRetry = bannerAdRetey.show()
        adShowRetry && adShowRetry.catch((error) => {
            console.log("banner广告展示失败-重试")
            console.log(JSON.stringify(error))
        })
    },
    //隐藏所有底部广告
    hideBannerAds() {
        if (require('GameMgr').Instance().ApiType !== 4) {
            return;
        }
        if (this._bannerAds) {
            this._bannerAds.hide();
        }
        require("ADShow3").ClosePanel();
        //this._bannerAds.offLoad();
        //this._bannerAds.offError();
        /*
        this._bannerAds.onHide(function () {
            console.log('banner 广告隐藏')
        })*/
    },
    /**
     * 获取微信信息
     */
    getOppoInfo() {
        var id = require('GameMgr').Instance().ApiType;
        console.log("渠道ID:" + id);
        var self = this;
        //if (require('GameMgr').Instance().ApiType === 3) {
        if (qg.getSystemInfoSync().platformVersionCode >= 1053) {
            qg.login({
                success: function (res) {
                    var data = JSON.stringify(res.data);
                    console.log(data);
                    console.log("登录成功", res);
                    console.log(res);
                    require('GameMgr').Instance().SetplMsg(res.data.nickName, res.data.avatar);
                    if (res.data.token) {
                        console.log('当前用户信息: ' + JSON.stringify(res.data));
                        curMod._wxUserInfo = res.data.token;
                        // 使用token进行服务端对接
                    }
                },
                fail: function (res) {
                    // errCode、errMsg
                    console.log(JSON.stringify(res));
                    console.log('登录失败' + JSON.stringify(err));
                    //cc.director.loadScene('LoadScene');
                    //self.setLogin() // 重新登录
                }
            });
        }
        qg.onHide(function () {
            require('GameMgr').Instance().StopBgm();
        });
        qg.onShow(function () {
            require("energyMgr").Instance().setTili();
            if (isRewardedVideo) {
                return;
            }
            require('GameMgr').Instance().resumeBgm();
        });
    },

    printInfo(res) {
        // console.log('设备品牌:', res.brand)
        // console.log('设备型号:', res.model)
        // console.log('设备像素比:', res.pixelRatio)
        // console.log('屏幕宽度:', res.windowWidth)
        // console.log('屏幕高度:', res.windowHeight)
        // console.log('状态栏的高度:', res.statusBarHeight)
        // console.log('微信设置的语言:', res.language)
        // console.log('微信版本号:', res.version)
        // console.log('操作系统及版本:', res.system)
        // console.log('客户端平台:', res.platform)
        // console.log('用户字体大小:', res.fontSizeSetting)
        // console.log('客户端基础库版本 :', res.SDKVersion)
        // console.log('设备性能等级:', res.benchmarkLevel)
        if (res.system.indexOf('Android') != -1) {
            curMod._isAndroid = true;
        }
    },
});

头条

// Learn cc.Class:
//  - [Chinese] https://docs.cocos.com/creator/manual/zh/scripting/class.html
//  - [English] http://docs.cocos2d-x.org/creator/manual/en/scripting/class.html
// Learn Attribute:
//  - [Chinese] https://docs.cocos.com/creator/manual/zh/scripting/reference/attributes.html
//  - [English] http://docs.cocos2d-x.org/creator/manual/en/scripting/reference/attributes.html
// Learn life-cycle callbacks:
//  - [Chinese] https://docs.cocos.com/creator/manual/zh/scripting/life-cycle-callbacks.html
//  - [English] https://www.cocos2d-x.org/docs/creator/manual/en/scripting/life-cycle-callbacks.html

var curMod = cc.Class({
    extends: cc.Component,

    properties: {
        // foo: {
        //     // ATTRIBUTES:
        //     default: null,        // The default value will be used only when the component attaching
        //                           // to a node for the first time
        //     type: cc.SpriteFrame, // optional, default is typeof default
        //     serializable: true,   // optional, default is true
        // },
        // bar: {
        //     get () {
        //         return this._bar;
        //     },
        //     set (value) {
        //         this._bar = value;
        //     }
        // },
    },

    statics: {
        _instance: null,
        _isAndroid: false,
        InterstitialAdId: "7n3hmusc8s11hf1c9l",
        RewardedVideoAdId: ["输入对应广告id"],
        BannerIds: ['输入对应广告id'],

        ShareTitle: "看过许多美景——身边依然还是你",
        ShareImgId: '1sptkc92obm2siacp3', // 通过 MP 系统审核的图片编号
        ShareImgUrl: 'https://mmocgame.qpic.cn/wechatgame/3gfJUsiaHCx28sibf4QvxkWEwK6UicbQricJn4M7ia9OoUIPaDXXn1tib6eSZWtpu7hOGz/0',

        _wxUserInfo: {},
        _systemInfo: {},

        Instance() {
            return curMod._instance;
        },

        GetInfo() {
            return curMod._wxUserInfo;
        },
    },

    // LIFE-CYCLE CALLBACKS:

    link() {
        require('GameMgr').Instance().sendData("login", { "code": res.code, "channelId": 1 }, function (data) {
            if (data.code === 0) {
                console.log("返回数据", data);
            }
            else {
                console.log("连接失败", data);
                return;
            };
        });
    },


    onLoad() {
        console.log('tt onload, curMod._instance=', curMod._instance);
        if (curMod._instance) {
            return;
        }
        curMod._instance = this;
        if (require('GameMgr').Instance().ApiType !== 2) {
            return;
        }

        this.craetTTRecorder();
        //...
        this._bannerAd = null;
        this._intersitialAd = null;
        this._rewardedVideoAd = null;
        //this.setLogin();

        this.scheduleOnce(this.createBannerAds, 1);
        this.scheduleOnce(this.createInterstitialAd, 10);

        //var callBackFun = this.createRewardedVideoAd(0);
        // this.scheduleOnce(callBackFun, 3);
    },


    start() {
    },

    shareAppMessage() {
        if (require('GameMgr').Instance().ApiType !== 2) {
            return;
        }
        console.log('shareAppMessage...');

        //var maxGuanqia = cc.sys.localStorage.getItem('local_guanIndex');
        tt.shareAppMessage({
            templateId: curMod.ShareImgId, // 替换成通过审核的分享ID
            query: "",
            success() {
                console.log("分享成功");
            },
            fail(e) {
                console.log("分享失败");
            }
        });

        this.closeTime = new Date().getTime();
        this._shareTime = new Date().getTime();
        this.isShared = true;
    },

    showInterstitialAd() {
        if (require('GameMgr').Instance().ApiType !== 2) {
            return;
        }
        this.createInterstitialAd();
        return;
        if (!this._intersitialAd) {
            this.createInterstitialAd();
            return;
        }
        this._intersitialAd.show();
    },


    showRewardedVideoAd(index) {
        if (require('GameMgr').Instance().ApiType !== 2) {
            return;
        }
        var self = this;
        index = 0;
        //this.AudioCloseTime = new Date().getTime();
        //console.log("创建视频广告", index, id, this.RewardedVideoAdId, this.RewardedVideoAdId[id]);
        var videoAd = tt.createRewardedVideoAd({
            adUnitId: curMod.RewardedVideoAdId[index]
        });
        //videoAd.load();
        // 显示广告
        videoAd
            .show()
            .then(() => {
                console.log("广告显示成功");
            })
            .catch(err => {
                console.log("广告组件出现问题", err);
                // 可以手动加载一次
                videoAd.load().then(() => {
                    console.log("手动加载成功");
                    // 加载成功后需要再显示广告
                    return videoAd.show();
                });
            });
        videoAd.onClose(res => {
            console.log(res);
            if (res.isEnded) {
                // 给予奖励
                // 正常播放结束,可以下发游戏奖励
                require('GameMgr').Instance().WadBack();
            }
            else {
                /*
                if (require('GameMgr').Instance().ApiType === 2) {
                    let curTime = new Date().getTime();
                    console.log("看视频时间:", curTime, self.AudioCloseTime);
                    if (curTime - self.AudioCloseTime >= 10000) {
                        require('GameMgr').Instance().ShowADrewords();
                        // 正常播放结束,可以下发游戏奖励
                        require('GameMgr').Instance().setDaily(2);
                    }
                    else {*/
                require('GameMgr').Instance().WadBack2();
                return;
            }
        });

        if (!this._rewardedVideoAd) {
            return;
        }
    },



    showBannerAd(index) {
        if (require('GameMgr').Instance().ApiType !== 2) {
            return;
        }
        if (!this._bannerAds) {
            return;
        }
        index = 0;
        for (let i = 0; i < this._bannerAds.length; i++) {
            if (i != index) {
                this._bannerAds[i].hide();
            }
        }
        console.log(index)
        if (this._bannerAds[index]) {
            console.log("this._bannerAds", this._bannerAds[index])
            this._bannerAds[index].show();
            this._bannerAds[index].onLoad(function () {
                this._bannerAds[index]
                    .show()
                    .then(() => {
                        console.log("底部广告显示成功");
                    })
                    .catch(err => {
                        console.log("底部广告组件出现问题", err);
                    });
            });
        }
    },

    //隐藏所有广告
    hideBannerAds() {
        if (require('GameMgr').Instance().ApiType !== 2) {
            return;
        }
        if (!this._bannerAds) {
            return;
        }
        if (this._bannerAds && this._bannerAds.length != null) {
            if (this._bannerAds.length > 0) {
                for (var i = 0; i < this._bannerAds.length; i++) {
                    if (this._bannerAds && this._bannerAds[i]) {
                        this._bannerAds[i].hide();
                    }
                }
            }
        }
    },

    createBannerAds() {
        if (require('GameMgr').Instance().ApiType !== 2) {
            return;
        }
        let winSize = curMod._systemInfo; //wx.getSystemInfoSync();
        let bannerHeight = 130;
        let bannerWidth = 300;

        this._bannerAds = [];
        var length = curMod.BannerIds.length;
        for (let i = 0; i < length; i++) {
            var self = this;
            const { windowWidth, windowHeight } = tt.getSystemInfoSync();
            var targetBannerAdWidth = 200;
            let banner = tt.createBannerAd({
                adUnitId: curMod.BannerIds[i],
                adIntervals: 30,
                style: {
                    width: targetBannerAdWidth,
                    top: windowHeight - (targetBannerAdWidth / 16) * 9,// 根据系统约定尺寸计算出广告高度
                    left: (windowWidth - targetBannerAdWidth) / 5,
                }
            });
            //banner.style.left = (windowWidth - targetBannerAdWidth) / 2;
            banner.onError(function (res) {
                console.log('banner, ', res);
            });
            this._bannerAds[i] = banner;
        }
    },

    createInterstitialAd() {
        let self = this;

        if (this._intersitialAd) {
            return;
        }
        console.log('createInterstitialAd', tt.getSystemInfoSync().appName);
        var isToutiaio = tt.getSystemInfoSync().appName === "Toutiao";
        // 插屏广告仅今日头条安卓客户端支持
        if (isToutiaio) {
            var interstitialAd = tt.createInterstitialAd({
                adUnitId: curMod.InterstitialAdId
            });
            console.log('插屏广告创建');
            interstitialAd
                .load()
                .then(() => {
                    console.log('插屏广告加载');
                    interstitialAd.show();
                })
                .catch(err => {
                    console.log('插屏广告加载出错');
                    console.log(err);
                });
        }
    },

    craetTTRecorder() {
        if (require('GameMgr').Instance().ApiType !== 2) {
            return;
        }
        console.log('录屏');
        var self = this;
        this.state = 0;
        this.RecorderManager = tt.getGameRecorderManager();
        //录屏开始
        this.RecorderManager.onStart(res => {
            console.log('录屏开始');
            var url = "color/TTvideo1";
            require('GameMgr').Instance().setPic(url);
            require('GameMgr').Instance().VideoShareShow(false);
            require('GameMgr').Instance().SetVTimer();
            this.state = 1;
        });
        this.RecorderManager.onStop(res => {
            console.log(res.videoPath);
            console.log('录屏结束');
            var url = "color/videoStart";
            require('GameMgr').Instance().setPic(url);
            require('GameMgr').Instance().stopVTimer();
            self.videoPath = res.videoPath;
            if (self.videoPath) {
                require('GameMgr').Instance().VideoShareShow(true);
            }
            var self1 = self;
            self.RecorderManager.clipVideo({
                path: self1.videoPath,
                timeRange: [10, 0],
                success(res) {
                    console.log(res.videoPath);
                    self1.videoPath = res.videoPath;
                },
                fail(e) {
                    console.error(e);
                }
            });
            this.state = 0;
            var GameState = require('GameMgr').Instance().gameState;
            if (!GameState) {
                require("TipShow").Instance().showTip("是否分享录屏获取奖励!", 2, function () {
                    self.TTShareVideo();
                    if (fun) {
                        fun();
                    }
                })
            }
        });
    },

    TTShareVideo(fun) {
        if (require('GameMgr').Instance().ApiType !== 2) {
            return;
        }
        if (!this.videoPath) {
            return;
        }
        tt.shareAppMessage({
            channel: "video",
            title: "分享视频",
            desc: "分享精彩一刻",
            imageUrl: "",
            templateId: "", // 替换成通过审核的分享ID
            query: "",
            extra: {
                videoPath: this.videoPath, // 可替换成录屏得到的视频地址
                videoTopics: ["录屏分享", "小游戏"]
            },
            success() {
                require('GameMgr').Instance().VideoShareShow(false);
                console.log("分享视频成功");
                if (fun) {
                    fun();
                }
                var count = require('PlayerMessage').Instance().GetUserData().RecordShareCount;
                console.log("分享次数" + count);
                if (count < 3) {
                    require('PlayerMessage').Instance().GetUserData().RecordShareCount++;
                    require("energyMgr").Instance().setEnergy(10);
                    require("TipShow").Instance().showTip2((3 - count), 1, function () {
                    }, function () {
                    }, 1, "Ok_Btn", 6);
                    return;
                }
                require("TipShow").Instance().showTip("分享成功!", 1, function () { });
            },
            fail(e) {
                require('GameMgr').Instance().VideoShareShow(false);
                console.log("分享视频失败", e);
                if (e.errMsg !== "shareAppMessage:cancel") {
                    require("TipShow").Instance().showTip("分享视频失败\n录制时间过短", 1, function () {
                    })
                }
            }
        });
    },

    TTRecorderStop(fun) {
        if (require('GameMgr').Instance().ApiType !== 2) {
            return;
        }
        var time = require('GameMgr').Instance().getVTime();
        if (time < 5) {
            require("TipShow").Instance().showTip("录制时间过短", 1, function () {
            })
            return;
        }
        var self = this;
        if (this.state === 1) {
            this.RecorderManager.stop();
        }
    },

    TTRecorderStart() {
        if (require('GameMgr').Instance().ApiType !== 2) {
            return;
        }
        if (this.state === 0) {
            this.RecorderManager.start({
                duration: 30,
            })
        }
    },

    TTRecorderCheck() {
        if (require('GameMgr').Instance().ApiType !== 2) {
            return;
        }
        if (this.state === 0) {
            this.TTRecorderStart();
        }
        else if (this.state === 1) {
            this.TTRecorderStop();
        }
    },

    createRewardedVideoAd(number) {
    },

    PYQshow() {
        tt.hideShareMenu();
    },

    PYQhid() {
        tt.hideShareMenu();
    },

    setLogin() {
        console.log('!')
        // let isWeChat = (cc.sys.platform === cc.sys.WECHAT_GAME);
        if (require('GameMgr').Instance().ApiType !== 2) {
            return;
        }
        let self = this;

        wx.login({
            success(res) {
                console.log('请求登录');
                console.log(res)
                if (!res.isLogin) {
                    self.scheduleOnce(function () {
                        self.setLogin();
                    }, 0.5);
                }
                if (res.code) {
                    console.log('登录成功!')
                    console.log(res)
                    //发起网络请求

                    // cc.log(url);
                } else {
                    console.log('登录失败!' + res.errMsg)
                }
            },
            complete() {
                console.log('登录调用完成');
            },
            fail(err) {
                console.log(err);
                console.log('再次登录');
                /*
                self.scheduleOnce(function () {
                    self.setLogin();
                }, 0.5);*/
            },
        })
    },

    /**
     * 获取微信信息
     */
    getWeiXinInfo() {
        if (require('GameMgr').Instance().ApiType !== 2) {
            return;
        }
        let self = this;

        tt.showShareMenu({
        });

        wx.onShareAppMessage(function () {
            return {
                title: curMod.ShareTitle,
                imageUrlId: curMod.ShareImgId,
                imageUrl: curMod.ShareImgUrl,
            }
        });

        wx.onShow(function (para) {
            //console.log('onShow...' + JSON.stringify(para));
            if (require('GameMgr').Instance().ApiType === 2) {
                // 用户点击了【关闭广告】按钮
                // 小于 2.1.0 的基础库版本,res 是一个 undefined
                if (this.WatchVAD) {
                    // 正常播放结束,可以下发游戏奖励
                }
            }
        });

        wx.onHide(function (para) {
            //console.log('onHide...' + JSON.stringify(para));
        });
        let sysInfo = window.wx.getSystemInfoSync();
        //获取微信界面大小
        let width = sysInfo.screenWidth;
        let height = sysInfo.screenHeight;

        curMod._systemInfo = sysInfo;
        this.printInfo(sysInfo);

        window.wx.getSetting({
            success(res) {
                //console.log(res.authSetting);
                if (res.authSetting["scope.userInfo"]) {
                    //console.log("用户已授权");
                    window.wx.getUserInfo({
                        success(res) {
                            //console.log(res);
                            curMod._wxUserInfo = res.userInfo;
                            //此时可进行登录操作
                            console.log('curMod._wxUserInfo=' + JSON.stringify(curMod._wxUserInfo));
                            var imgurl = curMod._wxUserInfo.avatarUrl + "?aaa=aa.jpg";
                            console.log(curMod._wxUserInfo);
                            var name = curMod._wxUserInfo.nickName;
                            require('GameMgr').Instance().SetplMsg(name, url);
                        }
                    });
                } else {
                    tt.openSetting();
                    tt.authorize({
                        scope: "scope.userInfo",
                        success(res) {
                            console.log("scope.userInfo", res);
                            curMod._wxUserInfo = res.userInfo;
                            var imgurl = curMod._wxUserInfo.avatarUrl + "?aaa=aa.jpg";
                            console.log(curMod._wxUserInfo);
                            var name = curMod._wxUserInfo.nickName;
                            require('GameMgr').Instance().SetplMsg(name, url);
                        }
                    });
                }
            }
        });
    },

    printInfo(res) {
        // console.log('设备品牌:', res.brand)
        // console.log('设备型号:', res.model)
        // console.log('设备像素比:', res.pixelRatio)
        // console.log('屏幕宽度:', res.windowWidth)
        // console.log('屏幕高度:', res.windowHeight)
        // console.log('状态栏的高度:', res.statusBarHeight)
        // console.log('微信设置的语言:', res.language)
        // console.log('微信版本号:', res.version)
        // console.log('操作系统及版本:', res.system)
        // console.log('客户端平台:', res.platform)
        // console.log('用户字体大小:', res.fontSizeSetting)
        // console.log('客户端基础库版本 :', res.SDKVersion)
        // console.log('设备性能等级:', res.benchmarkLevel)

        if (res.system.indexOf('Android') != -1) {
            curMod._isAndroid = true;
        }
    },
});

qq

// Learn cc.Class:
//  - [Chinese] https://docs.cocos.com/creator/manual/zh/scripting/class.html
//  - [English] http://docs.cocos2d-x.org/creator/manual/en/scripting/class.html
// Learn Attribute:
//  - [Chinese] https://docs.cocos.com/creator/manual/zh/scripting/reference/attributes.html
//  - [English] http://docs.cocos2d-x.org/creator/manual/en/scripting/reference/attributes.html
// Learn life-cycle callbacks:
//  - [Chinese] https://docs.cocos.com/creator/manual/zh/scripting/life-cycle-callbacks.html
//  - [English] https://www.cocos2d-x.org/docs/creator/manual/en/scripting/life-cycle-callbacks.html

var curMod = cc.Class({
    extends: cc.Component,

    properties: {
        // foo: {
        //     // ATTRIBUTES:
        //     default: null,        // The default value will be used only when the component attaching
        //                           // to a node for the first time
        //     type: cc.SpriteFrame, // optional, default is typeof default
        //     serializable: true,   // optional, default is true
        // },
        // bar: {
        //     get () {
        //         return this._bar;
        //     },
        //     set (value) {
        //         this._bar = value;
        //     }
        // },
    },

    statics: {
        _instance: null,
        InterstitialAdId: '7a531f4336e642620e10c7c9f009e7a2',
        RewardedVideoAdId: ['62c90b649c27dddf2817a3415cc36304', '0b62a8e298bc4aa64a859f72e1248760', 'e87a2d6e197d9cb593dedc47ec2a958e', '42721fd340bd4262e5ea6ea38d258c6a', '1f002aef690eee1f4bcf69d92a802332', '3335b1a36cdb65adb516a45a5eabcf6d'],
        BannerIds: ['0ba8e3c2f10b8e1577c4c9668f0b7e19', '30b6187d00f2ba0cecfb02f4ba5d0b5f', '1e7c36c5d57fa40acc68b848076d9da9', '624c71eacd80cdf422ea15de70d854c9', '459ce86621e60c6ffa9db1e7d4ce6a0b', '0c94b66c464fca401100528d5483b69d', '912f94ab25b8d7c51ef39eb5dcb2c0ef', '6c6b43a83ed6ff8911c0558dc08ea376', '75f03ebd095941f92d4456a388458060'], //, 'adunit-905904089942c58e'],
        AppBoxId: "69972a8a54610f1a6e73e6c8ed35fd43",
        ShareTitle: '看过许多美景——身边依然还是你',
        //ShareImgId: '5JWEBFBdTHiZ5EcslmutbA==', // 通过 MP 系统审核的图片编号
        //ShareImgUrl: 'https://mmocgame.qpic.cn/wechatgame/3gfJUsiaHCx28sibf4QvxkWEwK6UicbQricJn4M7ia9OoUIPaDXXn1tib6eSZWtpu7hOGz/0',

        _wxUserInfo: {},
        _systemInfo: {},

        Instance() {
            return curMod._instance;
        },
        GetInfo() {
            return curMod._wxUserInfo;
        },
    },

    onLoad() {
        console.log('vivo onload, curMod._instance=', curMod._instance);
        if (curMod._instance) {
            return;
        }
        curMod._instance = this;

        if (require('GameMgr').Instance().ApiType !== 5) {
            return;
        }
        this._bannerAd = null;
        this._intersitialAd = null;
        this._rewardedVideoAd = null;
        //...
        //this.setLogin();//用户登录,获取用户信息
        this.createBannerAds();
        return;
        this.AppBoxCreat();
        this.SGP = require("sg.es5");
        this.SGP.plugin.Service.init({ appId: "1110268371" }, (data) => {
            console.log("init data:" + JSON.stringify(data));
        });
    },

    start() {
    },

    //显示
    CreatAppBox() {
        if (require('GameMgr').Instance().ApiType !== 5) {
            return;
        }
        if (this.appbox) {
            this.appbox.show();
        }
        else {
            this.AppBoxCreat();
        }
        return;
        this.SGP.plugin.Service.platform.navigateToMiniProgram({
            appId: "1110268371",
            pkgName: "shuangzitiao", //oppo必须,其他平台忽略
            path: "",
            extraData: {},
            callback: (success, code, msg) => {
                console.log("navigateToMiniProgram", success + "," + code + "," + msg);
            }
        });
    },

    AppBoxCreat() {
        this.appbox = qq.createAppBox({
            adUnitId: curMod.AppBoxId,
        });
        this.appbox.load();
        //appbox.onError(function (res) {
        //    console.log('appbox, ', res);
        //});
    },

    // update (dt) {},
    //分享
    shareAppMessage() {
        console.log("qq3", require('GameMgr').Instance().ApiType);
        if (require('GameMgr').Instance().ApiType !== 5) {
            return;
        }
        qq.showShareMenu({
            showShareItems: ['qq', 'qzone', 'wechatFriends', 'wechatMoment']
        })
        qq.aldShareAppMessage({
            title: curMod.ShareTitle,
            shareAppType: "qq",
            success() {
                console.log("分享成功");
                require('GameMgr').Instance().setDaily(5);
                require('GameMgr').onWxShow(1001);
            },
            fail() {
                console.log("分享失败");
                require('GameMgr').Instance().showTip("取消分享,获取奖励失败", 0, "取消", "确定", function () {
                }, function () { return; });
            },
            Component() {

            },
        });
        qq.aldOnShareAppMessage(() => ({
            title: curMod.ShareTitle,
        }));
        /*
        this.SGP.plugin.Service.platform.shareAppMessage({
            title: curMod.ShareTitle,
        });*/
    },

    //显示插屏广告
    showInterstitialAd() {
        console.log("qq2");
        if (require('GameMgr').Instance().ApiType !== 5) {
            return;
        }
        let interstitialAd = qq.createInterstitialAd({
            adUnitId: curMod.InterstitialAdId
        });
        interstitialAd.load();
        interstitialAd.onLoad(() => {
            interstitialAd.show();
        });

        interstitialAd.onError(err => {
            console.log("插屏广告展示失败", err);
            console.log(JSON.stringify(err));
        })
    },

    //显示视频广告
    showRewardedVideoAd(index) {
        console.log("qq1");
        if (require('GameMgr').Instance().ApiType !== 5) {
            return;
        }
        console.log("激励广告加载", index);
        let rewardedAd;
        rewardedAd = qq.createRewardedVideoAd({
            adUnitId: curMod.RewardedVideoAdId[index]
        });

        rewardedAd.load();

        rewardedAd.show();

        rewardedAd.onLoad(() => {
        })

        rewardedAd.onError(err => {
            console.log("激励广告展示失败")
            console.log(JSON.stringify(err));
            //require('GameMgr').Instance().showTip(JSON.stringify(err.data.errMsg) + "\n请稍后再试", 0, "取消", "确定", function () {
            //}, function () { return; });
        })

        rewardedAd.onClose(res => {
            if (res && res.isEnded) {
                console.log("正常播放结束,可以下发游戏奖励");
                require('GameMgr').Instance().ShowADrewords();
                require('GameMgr').Instance().setDaily(2);

            } else {
                console.log("播放中途退出,不下发游戏奖励");
                require('GameMgr').Instance().showTip("中途退出,获取奖励失败", 0, "取消", "确定", function () {
                }, function () { });
            }
        });
    },


    //显示底部广告
    showBannerAd(index) {
        if (require('GameMgr').Instance().ApiType !== 5) {
            return;
        }
        if (!this._bannerAds) {
            this.createBannerAds();
            return;
        }
        if (this._bannerAds[index]) {
            console.log("this._bannerAds", this._bannerAds[index])
            this._bannerAds[index].show();
        }
    },


    createBannerAds() {
        let sysInfo = window.wx.getSystemInfoSync();
        //获取微信界面大小
        let width = sysInfo.screenWidth;
        let height = sysInfo.screenHeight;
        let bannerHeight = height * 0.2;
        let bannerWidth = width * 0.8;
        console.log("****************", cc.winSize);
        this._bannerAds = [];
        var length = curMod.BannerIds.length;
        for (let i = 0; i < length; i++) {
            let banner = qq.createBannerAd({
                adUnitId: curMod.BannerIds[i],
                style: {
                    height: bannerHeight,
                    width: bannerWidth,
                    left: (width / 2 - bannerWidth / 2),
                    top: (height - bannerHeight / 2),
                }
            });
            banner.onLoad(() => {
                this._bannerAds[i] = banner;
            })
            banner.onError(function (res) {
                console.log('banner, ', res);
            });
        }
    },

    //隐藏所有底部广告
    hideBannerAds() {
        if (require('GameMgr').Instance().ApiType !== 5) {
            return;
        }
        if (!this._bannerAds) {
            return;
        }
        if (this._bannerAds && this._bannerAds.length != null) {
            if (this._bannerAds.length > 0) {
                for (var i = 0; i < this._bannerAds.length; i++) {
                    if (this._bannerAds && this._bannerAds[i]) {
                        this._bannerAds[i].hide();
                    }
                }
            }
        }
    },


    wxGameStart(id) {
        if (require('GameMgr').Instance().ApiType !== 5) {
            return;
        }
        var Id = parseInt(id / 1000) + "." + (id % 1000);
        cc.log(Id);
        var Id = parseInt(id / 1000) + "." + (id % 1000);
        cc.log(Id);
        var stagename = "第" + parseInt(id / 1000) + "-" + (id % 1000) + "关";
        wx.aldStage.onStart({
            stageId: Id,     //关卡ID 该字段必传
            stageName: stagename, //关卡名称  该字段必传
            //userId: "06_bmjrPtlm6_2sgVt7hMZOPfL2M" //用户ID 可选
        })
    },

    wxGameING(id, number) {
        if (require('GameMgr').Instance().ApiType !== 5) {
            return;
        }
        // 在关卡中使用道具
        var Id = parseInt(id / 1000) + "." + (id % 1000);
        var stagename = "第" + parseInt(id / 1000) + "." + (id % 1000) + "关";
        var msg = "";
        if (number === 1) {
            msg = "吸金币";
        }
        else if (number === 2) {
            msg = "二段跳";
        }
        wx.aldStage.onRunning({
            stageId: Id,
            stageName: stagename,
            //userId: "123456",
            event: "tools",
            params: {
                itemName: msg,
            }
        });
    },

    wxGameOver(id, state) {
        //关卡完成
        if (require('GameMgr').Instance().ApiType !== 5) {
            return;
        }
        var Id = parseInt(id / 1000) + "." + (id % 1000);
        var stagename = "第" + parseInt(id / 1000) + "." + (id % 1000) + "关";
        var complete = "";
        if (state === 0) {
            complete = "死亡";
            state = "fail";
        }
        else if (state === 1) {
            complete = "复活";
            state = "fail";
        } else if (state === 2) {
            complete = "通关";
            state = "complete";
        } else if (state === 3) {
            complete = "重新开始";
            state = "fail";
        }
        wx.aldStage.onEnd({
            stageId: Id,    //关卡ID 该字段必传
            stageName: stagename, //关卡名称  该字段必传
            //userId: "06_bmjrPtlm6_2sgVt7hMZOPfL2M",  //用户ID 可选
            event: state,   //关卡完成  关卡进行中,用户触发的操作    该字段必传
            params: {
                desc: complete,  //描述
            }
        })
    },


    setLogin() {
        var id = require('GameMgr').Instance().ApiType;
        console.log("渠道ID:" + id);

        if (id === 5) {
            var self = this;
            qq.login({
                success(res) {
                    console.log(res);
                    console.log(JSON.stringify(res));
                    if (res.code) {
                        require('GameMgr').Instance().sendData("login", { "code": res.code, "channelId": id }, function (data) {
                            if (data.code === 0) {
                                console.log("返回数据", data);
                                require('GameMgr').Instance().setLogin(data.uid, data.token, data);
                                self.getQQInfo();
                            }
                            else {
                                console.log("连接失败", data);
                                let self1 = self;
                                require('GameMgr').Instance().showTip("网络连接失败\n请稍后重试", 2, "取消", "确定", function () {
                                    cc.director.loadScene('LoadScene');
                                    return;
                                }, function () {
                                    self1.setLogin();
                                    return;
                                });
                                return;
                            }
                        });
                    } else {
                        console.log('登录失败!' + res.errMsg)
                    }
                },
                fail() {
                    // session_key 已经失效,需要重新执行登录流程
                    self.setLogin() // 重新登录
                },
            });
            qq.checkSession({
                success() {
                    // session_key 未过期,并且在本生命周期一直有效
                },
                fail() {
                    let self1 = self;
                    require('GameMgr').Instance().showTip("连接中断,请重试", 2, "取消", "确定", function () {
                        self1.setLogin();
                        return;
                    }, function () {
                        self1.setLogin();
                        return;
                    });
                }
            })
        }
    },

    getQQInfo() {
        //获取登录信息
        qq.getSetting({
            success(res) {
                let sysInfo = window.wx.getSystemInfoSync();
                //获取微信界面大小
                let width = sysInfo.screenWidth;
                let height = sysInfo.screenHeight;
                if (res.authSetting['scope.userInfo']) {
                    // 已经授权,可以直接调用 getUserInfo 获取头像昵称
                    qq.getUserInfo({
                        success(res) {
                            console.log('当前用户信息: ' + JSON.stringify(res));
                            curMod._wxUserInfo = res.userInfo;
                            var imgurl = curMod._wxUserInfo.avatarUrl + "?aaa=aa.jpg";
                            require('GameMgr').Instance().setplUrl(imgurl);
                            var name = curMod._wxUserInfo.nickName;
                            require('GameMgr').Instance().SetName(name);
                        }
                    })
                }
                else {
                    let button = window.wx.createUserInfoButton({
                        type: 'text',
                        text: '',
                        style: {
                            left: 0,
                            top: 0,
                            width: width,
                            height: height,
                            backgroundColor: '#00000000',//最后两位为透明度
                            color: '#ffffff',
                            fontSize: 20,
                            textAlign: "center",
                            lineHeight: height,
                        }
                    });
                    button.onTap((res) => {
                        console.log('当前用户信息: ' + JSON.stringify(res));
                        curMod._wxUserInfo = res.userInfo;
                        var imgurl = curMod._wxUserInfo.avatarUrl + "?aaa=aa.jpg";
                        require('GameMgr').Instance().setplUrl(imgurl);
                        var name = curMod._wxUserInfo.nickName;
                        require('GameMgr').Instance().SetName(name);
                        button.destroy();
                    })
                }
            }
        });
    },

    printInfo(res) {
        // console.log('设备品牌:', res.brand)
        // console.log('设备型号:', res.model)
        // console.log('设备像素比:', res.pixelRatio)
        // console.log('屏幕宽度:', res.windowWidth)
        // console.log('屏幕高度:', res.windowHeight)
        // console.log('状态栏的高度:', res.statusBarHeight)
        // console.log('微信设置的语言:', res.language)
        // console.log('微信版本号:', res.version)
        // console.log('操作系统及版本:', res.system)
        // console.log('客户端平台:', res.platform)
        // console.log('用户字体大小:', res.fontSizeSetting)
        // console.log('客户端基础库版本 :', res.SDKVersion)
        // console.log('设备性能等级:', res.benchmarkLevel)
        if (res.system.indexOf('Android') != -1) {
            curMod._isAndroid = true;
        }
    },
});

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐