【cocos creator】微信小程序,api,登录,分享,广告,游戏圈,广告回调


//WeChat.js
// 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: {
    },

    statics: {
        _instance: null,
        _isAndroid: false,

        InterstitialAdId: '',//插屏广告
        RewardedVideoAdId: '',//视频广告
        BannerIds: ['', ''],
        //底部广告

        ShareTitle: '',// 分享文案
        ShareImgId: '', // 通过 MP 系统审核的图片编号
        ShareImgUrl: '',//图片url

        _wxUserInfo: {},
        _systemInfo: {},

        Instance() {
            return curMod._instance;
        },

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

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

        if (!window.wx) {
            return;
        }

        //...
        this._bannerAd = null;
        this._intersitialAd = null;
        this._rewardedVideoAd = null;
        this.getWeiXinInfo();

        if (curMod._isAndroid) {
            //console.log('curMod._isAndroid...')
            //cc.game.setFrameRate(40);
        }
        //cc.game.setFrameRate(45);

        //load all ads
        // setTimeout(() => {
        //     this.createBannerAds();
        //     this.createInterstitialAd();
        //     this.createRewardedVideoAd();
        // }, 200);

    },


    start() {
        if (!window.wx) {
            return;
        }
        this.showClub();
        this._bannerAds = [];
        //加载广告
        this.scheduleOnce(this.createBannerAds, 1);
        this.scheduleOnce(this.createRewardedVideoAd, 3);
        this.scheduleOnce(this.createInterstitialAd, 3);
        //this.tex = new cc.Texture2D();
    },
    /*
    _updateSubDomainCanvas() {
        if (!this.tex) {
            return;
        }
        var openDataContext = wx.getOpenDataContext();
        var sharedCanvas = openDataContext.canvas;
        this.tex.initWithElement(sharedCanvas);
        this.tex.handleLoadedTexture();
        this.display.spriteFrame = new cc.SpriteFrame(this.tex);
    },*/
//游戏圈图标
    showClub() {
        if (!window.wx) {
            return;
        }
        this.clubButton = wx.createGameClubButton({
            icon: 'light',
            style: {
                left: 20, // 之所以要减20,是因为clubButton的锚点在左上角
                top: 200, // 之所以要减20,是因为clubButton的锚点在左上角 
                width: 40,
                height: 40
            }
        });
        this.clubButton.show();
    },

    //存储信息,托管游戏数据
    postDataToWX: function () {
        if (!window.wx) {
            return;
        }
        //向微信保存最高分数
        var kvDateList = new Array();
        var mypvpscore = require("PlayerMessages").Instance().getPVPMaxScore() + "";
        var mypvptime = require("PlayerMessages").Instance().getPVPMinTime() + "";
        //插入自己的分数
        var myscore = require("PlayerMessages").Instance().getMaxScore() + "";
        var mytime = require("PlayerMessages").Instance().getMinTime() + "";

        kvDateList.push({
            key: "mypvpscore",
            value: mypvpscore
        });
        kvDateList.push({
            key: "mypvptime",
            value: mypvptime
        });
        kvDateList.push({
            key: "myscore",
            value: myscore
        });
        kvDateList.push({
            key: "mytime",
            value: mytime
        });
        //托管游戏数据
        wx.setUserCloudStorage({
            KVDataList: kvDateList,
            success: function (res) {
                console.log("wx.setUserCloudStorage success");
                console.log(res);
            },
            fail: function (res) {
                console.log("wx.setUserCloudStorage fail");
                console.log(res);
            }
        });
    },

    //向子域通信
    showHaoYouPVPPaihang: function () {
        var openDataContext = wx.getOpenDataContext();
        openDataContext.postMessage({
            text: "showPVPRank",
        });
    },

    showHaoYouPKPaihang: function () {
        var openDataContext = wx.getOpenDataContext();
        openDataContext.postMessage({
            text: "showPKRank",
        });
    },

    //微信分享按钮
    WXshare: function () {
        if (!window.wx) {
            return;
        }
        cc.log('shareAppMessage...');
        if (!window.wx) {
            return;
        }
        window.wx.shareAppMessage({
            title: curMod.ShareTitle,
            imageUrlId: curMod.ShareImgId,
            imageUrl: curMod.ShareImgUrl,
        });
        this._shareTime = new Date().getTime();
    },

    //插屏广告
    showInterstitialAd() {
        this._intersitialAd.show();
    },

    //视频广告
    showRewardedVideoAd() {
        //this.createRewardedVideoAd();
        this._rewardedVideoAd.show();
    },

    //底部广告
    showBannerAd(index) {
        if (!window.wx) {
            return;
        }
        for (let i = 0; i < this._bannerAds.length; i++) {
            if (i != index) {
                this._bannerAds[i].hide();
            }
        }
        if (this._bannerAds[index]) {
            this._bannerAds[index].show();
        }
    },

    //隐藏指定广告
    hideBannerAd(index) {
        if (!window.wx) {
            return;
        }
        if (this._bannerAds && index < this._bannerAds.length && this._bannerAds[index]) {
            this._bannerAds[index].hide();
        }
    },

    //隐藏所有广告
    hideBannerAds: function () {
        if (!window.wx) {
            return;
        }
        if (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 = curMod._systemInfo; //wx.getSystemInfoSync();
        let bannerHeight = 130;
        let bannerWidth = 300;

        this._bannerAds = [];
        for (let i = 0; i < curMod.BannerIds.length; i++) {
            let banner = wx.createBannerAd({
                adUnitId: curMod.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;
        }

        this._intersitialAd = wx.createInterstitialAd({
            adUnitId: curMod.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();
            }, 5000);
        });

        this._intersitialAd.onClose(function (res) {
            //console.log('_intersitialAd, onClose, res=' + JSON.stringify(res));
            //require('GameMgr').onWxShow();
            
        });
        this._intersitialAd.load();
        //this._intersitialAd.show();
    },

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

        this._rewardedVideoAd = wx.createRewardedVideoAd({
            adUnitId: curMod.RewardedVideoAdId
        });
        this._rewardedVideoAd.onError(function (res) {
            //console.log('onError, _rewardedVideoAd, res=' + JSON.stringify(res));
            wx.showToast({
                title: 'load ad failed!',
                icon: 'success',
                duration: 2000
            });
        });
        this._rewardedVideoAd.onClose(function (res) {
            //console.log('_rewardedVideoAd, onClose, res=' + JSON.stringify(res));
            //require('GameMgr').onWxShow(5000);
            if (res && res.isEnded || res === undefined) {
                //播放完广告
            }
            else {
                // 播放中途退出,不下发游戏奖励
            }
        });
        this._rewardedVideoAd.load();
        //this._rewardedVideoAd.show();
    },

    sendMessage: function () {
        wx.postMessage({ type: "close" });
    },


    //获取微信用户登录信息,获取用户授权
    getWeiXinInfo() {
        let isWeChat = (cc.sys.platform === cc.sys.WECHAT_GAME);

        if (!isWeChat || !window.wx) {
            return;
        }

        let self = this;
        //显示右上角分享按钮
        wx.showShareMenu({
        });
        wx.onShareAppMessage(function () {
            return {
                title: curMod.ShareTitle,
                imageUrlId: curMod.ShareImgId,
                imageUrl: curMod.ShareImgUrl,
            }
        });

        //显示小程序界面
        wx.onShow(function (para) {
            //console.log('onShow...' + JSON.stringify(para));
        });

        //隐藏小程序界面
        wx.onHide(function (para) {
            //console.log('onHide...' + JSON.stringify(para));
        });

        let exportJson = {};
        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);
                            exportJson.userInfo = res.userInfo;
                            var url = res.userInfo.avatarUrl + "?aaa=aa.jpg";
                            var name = res.userInfo.nickName;
                            //登录操作
                        }
                    });
                } else {
                    //console.log("用户未授权");
                    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) => {
                        if (res.userInfo) {
                            //console.log("用户授权:", res);
                            exportJson.userInfo = res.userInfo;
                             //用户图片地址
                             var url = res.userInfo.avatarUrl + "?aaa=aa.jpg";
                             //用户昵称
                             var name = res.userInfo.nickName;
                            //此时可进行登录操作
                            button.destroy();
                        } else {
                            //console.log("用户拒绝授权:", res);
                            wx.showModal({
                                title: '警告',
                                content: '您点击了拒绝授权,将无法正常游戏,点击确定重新获取授权。',
                                success: function (res) {
                                    if (res.confirm) {
                                        wx.openSetting({
                                            success: (res) => {
                                                console.log('授权成功')
                                                exportJson.userInfo = res.userInfo;
                                                //用户图片地址
                                                var url = res.userInfo.avatarUrl + "?aaa=aa.jpg";
                                                //用户昵称
                                                var name = res.userInfo.nickName;
                                                //此时可进行登录操作
                                            }
                                        })
                                    }
                                }
                            })
                        }
                    });
                }
            }
        });
    },

    //打印信息
    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;
        }
    },
});


使用:require(‘WeChat’).Instance().方法名(参数);

链接:https://pan.baidu.com/s/1EzINULrESivcBlXqdR2-QQ
提取码:0emt
复制这段内容后打开百度网盘手机App,操作更方便哦

  • 1
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

烧仙草奶茶

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值