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

711 lines
22 KiB
TypeScript
Raw Permalink Blame History

This file contains ambiguous Unicode characters

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

/**
* 微信广告sdk
* ts 版本
* 单例
*/
import PlayData from "../../PlayData";
import Utils from "../../Utils";
export enum CustomAdType{
//0:单个1横向多个2竖向多个3矩阵
One = 0,
Heng = 1,
Shu = 2,
More = 3
}
/**
* scope 对应接口 描述
* scope.userInfo wx.getUserInfo 用户信息
* scope.userLocation wx.getLocation 地理位置
* scope.werun wx.getWeRunData 微信运动步数
* scope.writePhotosAlbum wx.saveImageToPhotosAlbum 保存到相册
* scope.WxFriendInteraction 对应开放数据域内的 wx.getFriendCloudStorage 、wx.getGroupCloudStorage 、wx.getGroupInfo 、wx.getPotentialFriendList 、wx.getUserCloudStorageKeys 、wx.getUserInfo 、GameServerManager.getFriendsStateData 接口,以及主域内的 wx.getUserInteractiveStorage 接口。 是否授权使用你的微信朋友信息
* scope.gameClubData wx.getGameClubData 游戏圈加圈、点赞、发表数据
*/
export enum Scope {
userInfo = 'scope.userInfo',
WxFriendInteraction = 'scope.WxFriendInteraction'
}
export default class weixinAdsApi {
public static _instance:weixinAdsApi = null
isvideoend: boolean;
checkVideo: boolean;
private _type: any;
public static get Instance(){
if (null == this._instance) {
this._instance = new weixinAdsApi();
}
return this._instance
}
// private _platform:string
// get platform():string {
// this._platform = 'wx'
// return this._platform
// }
// set plaform(str){
// this._platform = str
// }
videoRecordingState:any = 0;
video_recorder:any = null;
videoStartTime:any = null;
videoPath:any = null;
videoIsExist:any = 0;//视频是否存在 默认存在
recorderTime:any = 120; //视频录制时间
videoAd:any = null; //激励视频
chaPingErr:any = false; //插屏报错(触发频繁限制等)
chaPing:any = null
bannerAd:any = null; //横屏广告
videoCallBack = null //激励视频成功回调
videoFailCallBack = null //激励视频失败回调
isshowbanner = false
gameCode: any = null
Ad_Custom_One_CallBack = null
Ad_Custom_DanGe = null //单个
Ad_Custom_HengXiang = null //横向
Ad_Custom_ShuXiang_R = null //竖向 靠右边
Ad_Custom_ShuXiang_L = null //竖向 靠左边
Ad_Custom_JuZhen = null //矩阵
//微信小游戏 广告配置
wx_info:any = {
gamename:"xxxxx",//游戏名称
shareTitle:'xxxxx',//分享标题
appId:'xxxx', //appid
bannerId: "adunit-a4267657099024a0",//横幅
videoId:'', //6---30s 激励
videoId2:'adunit-a96b930e78a0646b', //6---60s 激励 // 主要用这个
chapingId:'adunit-16e1da009c227036', //插屏
gezi:'', //格子 微信已经下线
NativeAd:{ // 原生
juzhen:'xxxx', //矩阵
dangezi:'xxxx', //单个
duogezi_hengxiang:'xxxxx', //横向多个
duogezi_shuxiang:'xxxxx' //竖向多个
},
templateId: ['','','',''],
videoTopics:['','']
}
/**
* 获取平台 类
*/
getPlatformClass(){
//@ts-ignore
var p_class = wx
return p_class
}
/**
* 获取分享标题
*/
getShareTitle(){
var title = ''
title = this.wx_info.shareTitle
return title
}
/**
* 获取名字
*/
getName(){
var name = ''
name = this.wx_info.gamename
return name
}
/**
* 获取appid
*/
getAppId(){
var appid = ''
appid = this.wx_info.appId
return appid
}
/**
* 获取AppSecret
*/
getAppSecret(){
var appSecret = ''
return appSecret
}
/**
* 获取bannerid
*/
getBannerId(){
var bannerID = ''
bannerID = this.wx_info.bannerId
return bannerID
}
/**
* 获取videoid
*/
getVideoId(){
var videoId = ''
videoId = this.wx_info.videoId
return videoId
}
getVideoId2(){
var videoId = ''
videoId = this.wx_info.videoId2
return videoId
}
/**
* 获取id
* @param {*012} type
*/
getNativeAd(type){
var id = ''
if(type == 0){
id = this.wx_info.NativeAd.dangezi
}else if(type == 1){
id = this.wx_info.NativeAd.duogezi_hengxiang
}else if(type == 2){
id = this.wx_info.NativeAd.duogezi_shuxiang
}else if(type == 3){
id = this.wx_info.NativeAd.juzhen
}
console.log('打印获取的广告id=', id)
return id
}
/**
* 获取插屏广告id
*/
getChaPingId(){
var chapingId = ''
chapingId = this.wx_info.chapingId
return chapingId
}
/**
* 获取分享审核id
*/
getTemplateId(){
var templateId = ''
return templateId
}
/**
* 游戏登录
*/
gameLogin(_force){
console.log('游戏登录2')
var self = this
this.getPlatformClass().login({
success (res) {
if (res.code) {
//发起网络请求
self.gameCode = res.code
console.log('login 调用成功',res);
} else {
console.log('登录失败!' + res.errMsg)
}
}
})
}
/**
* 开启分享菜单
*/
showShareMenu(){
//@ts-ignore
wx.showShareMenu({
success: (res) => {
console.log('开启被动转发成功!');
},
fail: (res) => {
console.log(res);
console.log('开启被动转发失败!');
}
});
// 获取当前棋局oneChess信息JSON.stringfy()后传入query
//@ts-ignore
wx.onShareAppMessage(() => {
return {
title: '队长带你们装13,带你们起飞!',
imageUrl: 'https://mmocgame.qpic.cn/wechatgame/fIiaXSY0ANicSQhzmT6k9nyNPFW01mXictfeWiaRqU7yfLGNvMbnngu9wJ5t1fkNd7CR/0', // 分享图片要放在 wechatgame/res/raw-assets 路径下
query: '' // query最大长度(length)为2048
}
});
}
/**
* 游戏分享
*/
game_share(callBack){
this.getPlatformClass().shareAppMessage({
title : '队长带你们装13,带你们起飞!',
imageUrlId: "2Hxj5qnpQGSGGVMrXd/nyw==", // 替换成通过审核的分享ID
imageUrl:'https://mmocgame.qpic.cn/wechatgame/fIiaXSY0ANicSQhzmT6k9nyNPFW01mXictfeWiaRqU7yfLGNvMbnngu9wJ5t1fkNd7CR/0',
query: "",
success() {
//console.log("分享成功");
callBack()
},
fail(e) {
//console.log("分享失败");
}
});
}
/**
* 分享到好友
* @param callback
*/
shareGameToFriend(callback, note?:string){
console.log('分享到好友')
let notestr = '你的好友邀请你一起战斗'
if(note) notestr = note
let title = this.getName()
this.getPlatformClass().shareAppMessage({
channel: "invite", // 拉起邀请面板分享游戏好友
title: title,
desc: notestr,
imageUrl: "",
query: "",
success() {
//console.log("分享成功");
},
fail(e) {
//console.log("分享失败");
},
});
}
/**
* banner 广告显示
*/
bannerAds_Show(){
var self = this
if (self.bannerAd == null) {
self.isshowbanner = false
let winSize = this.getPlatformClass().getSystemInfoSync();
let bannerWidth:number = winSize.windowWidth;
let bannerHeight = 100;
// // 广告
let bannerID = this.getBannerId()
self.bannerAd = this.getPlatformClass().createBannerAd({
adUnitId: bannerID,
adIntervals:30, //自动刷新时间 最少30 。 无,不自动
style: {
left: (winSize.windowWidth - bannerWidth) / 2,
top: winSize.windowHeight - bannerHeight ,
width: bannerWidth,
height: bannerHeight,
}
})
self.bannerAd.onResize(res => {
self.bannerAd.style.left = (winSize.windowWidth - res.width) / 2;
self.bannerAd.style.top = winSize.windowHeight - res.height ;
})
self.bannerAd.onError(function (res) {
console.log('banner失败',res);
self.bannerAd = null
//self.bannerAds_Load()
})
self.bannerAd.onLoad(() => {
console.log('banner 广告加载成功')
//gameConfig.isshowbanner = true
})
}
if (self.bannerAd != null) {
self.bannerAd.show();
}
}
/**
* banner 广告隐藏
*/
bannerAds_Hide(){
if (this.bannerAd != null) {
this.bannerAd.hide();
}
}
/**
* 插屏广告加载
*/
chaPingAds_Load(){
var chapingId = this.getChaPingId()
this.chaPing = this.getPlatformClass().createInterstitialAd({ adUnitId: chapingId })
this.chaPing.onError(err => {
console.log('插屏广告拉取失败',err)
//gameConfig.chaPing = wx.createInterstitialAd({ adUnitId: chapingId })
})
}
/**
* 插屏广告显示
*/
chaPingAds_Show(callback?){
var self = this
if(self.chaPingErr == true){
if(callback){
return callback()
}
}
self.chaPingErr = true
setTimeout(()=>{
self.chaPingErr = false
},45000)
self.chaPing.show()
.then(()=>{
if(callback){
callback()
}
})
.catch((err) => {
console.error(err)
console.log('展示广告失败')
if(callback){
callback()
}
})
}
/**
* 激励广告加载
*/
motivational_Video_Load(){
var self = this
var videoId = this.getVideoId2()
console.log('打印激励视频id', videoId)
self.videoAd = this.getPlatformClass().createRewardedVideoAd({
adUnitId: videoId,
//multiton: true
})
self.videoAd.onError((res)=>{
console.log('激励视频错误',res)
})
self.videoAd.load()
var endCallBack = function(res){
if (res.isEnded == true) {
if(self.videoCallBack != null){
console.log('获取奖励')
self.videoCallBack()
//analysisReport.Instance.gameEventInfo.successShowVideo ++
//analysisReport.Instance.reportAnalytics(EventField.successShowVideo, {videonum:analysisReport.Instance.gameEventInfo.successShowVideo})
}
if(this._type != -1){
self.showToast('已获得')
}
} else {
if (self.videoFailCallBack != null){
//analysisReport.Instance.gameEventInfo.failShowVideo ++
//analysisReport.Instance.reportAnalytics(EventField.failShowVideo, {videonum:analysisReport.Instance.gameEventInfo.failShowVideo})
self.videoFailCallBack()
}
}
self.isvideoend = true
setTimeout(()=>{
self.checkVideo = false
},60000)
}
self.videoAd.onClose(endCallBack); //绑定结束回调
}
/**
* 展示激励视频
* 参数1 成功回调
* 参数2 失败回调 可以省略
*/
motivational_Video_Show(success, faile, type?){
var self = this
if(this.checkVideo == true) return this.showToast('勿频繁点击')
setTimeout(()=>{
self.checkVideo = false
},1000)
this.videoCallBack = success
this.videoFailCallBack = faile
this._type = type
if(self.videoAd == null || self.videoAd == undefined){
return this.videoCallBack()
}
self.videoAd.onError((res)=>{
console.log('广告出错监听', res)
})
// /**展示 */
self.videoAd
.show()
.then(() => {
})
.catch(err => {
self.showToast('激励视频播放失败')
console.log('打印激励视频错误', err)
// 可以手动加载一次
self.videoAd.load().then(() => {
// 加载成功后需要再显示广告
return self.videoAd.show();
});
});
}
/**
* 创建原生广告模板
* @param {0:单个,1:横向多个,2:竖向多个,3:矩阵} type
*/
createCustomAd(type){
//console.log('创建原生广告type=', type)
let inifo = this.getPlatformClass().getSystemInfoSync()
if(Utils.compareVersion( inifo.SDKVersion ,'2.11.1')>= 0){
if(type == CustomAdType.One){ //单个
//常规样式默认画布为 60×104 像素
//卡片样式默认画布为 68×106 像素
}else if(type == CustomAdType.Heng){ //横向 顶部 水平布局默认画布为 360×106 像素
let adWidth = 360;
let adHeight = 110;
let id = this.getNativeAd(type)
this.Ad_Custom_HengXiang = this.getPlatformClass().createCustomAd({
adUnitId: id,
adIntervals:35,
style: {
left: (inifo.screenWidth - adWidth)/2,
top: inifo.screenHeight - adHeight,
fixed:false
}
})
this.Ad_Custom_HengXiang.onLoad((res)=>{
console.log('横向原生广告加载', res)
})
this.Ad_Custom_HengXiang.onError((res)=>{
console.log('横向原生广告报错', res)
})
this.Ad_Custom_HengXiang.onHide((res)=>{
console.log('横向原生监听关闭')
})
}else if(type == CustomAdType.Shu){ //竖向 靠右 垂直布局默认画布为 72×410 像素
}else if(type == CustomAdType.More){ //矩阵
// 2×5 布局默认画布为 360×188 像素
// 5×5 布局默认画布为 360×352 像素
let adWidth = 360;
let adHeight = 250;
let id = this.getNativeAd(type)
this.Ad_Custom_JuZhen = this.getPlatformClass().createCustomAd({
adUnitId: id,
adIntervals:35,
style: {
left: (inifo.screenWidth - adWidth)/2,
top: (inifo.screenHeight - adHeight)/2,
fixed:false
}
})
this.Ad_Custom_JuZhen.onLoad((res)=>{
console.log('矩阵原生广告加载', res)
})
this.Ad_Custom_JuZhen.onError((res)=>{
console.log('矩阵原生广告报错', res)
})
this.Ad_Custom_JuZhen.onHide((res)=>{
console.log('矩阵原生监听关闭')
})
}
}
}
/**
* 展示
* @param {*} ad
*/
showCustomAd(type){
switch(type){
case 0:
break
case CustomAdType.Heng:
this.Ad_Custom_HengXiang.show()
break
case 2:
break
case CustomAdType.More:
this.Ad_Custom_JuZhen.show()
break
}
}
/**
* 隐藏, 销毁原生广告模板
*/
hideCustomAd(type){
console.log('关闭原生广告',type)
switch(type){
case 0:
break
case CustomAdType.Heng:
this.Ad_Custom_HengXiang.hide()
break
case 2:
break
case CustomAdType.More:
this.Ad_Custom_JuZhen.hide()
break
}
}
/**
* 提示框
*/
showToast(str){
this.getPlatformClass().showToast({
title: str,
duration: 1000,
success(res) {
//console.log(`${res}`);
},
fail(res) {
//console.log(`showToast调用失败`);
}
});
}
/**
* 手机震动
*/
vibrateShort(){
this.getPlatformClass().vibrateShort()
}
/**
* 上传微信 游戏得分
*/
upWxHighScore(score, callBack){
this.getPlatformClass().setUserCloudStorage({
KVDataList: [{key: 'rank', value: String(score)}],
success: res => {
console.log('上传排行数据success',res);
// // 让子域更新当前用户的最高分因为主域无法得到getUserCloadStorage;
// let openDataContext = wx.getOpenDataContext();
// openDataContext.postMessage({
// type: 'updateMaxScore',
// });
callBack()
},
fail: res => {
console.log('上传排行数据fail',res);
}
});
}
/**
* 获取用户信息
*/
getUserInfo(callback){
callback()
//@ts-ignore
// wx.getSetting({
// success(res){
// console.log('获取用户权限设置成功2', res.authSetting['scope.userInfo'])
// if(res.authSetting['scope.userInfo'] == false){ //询问是否打开设置界面
// //@ts-ignore
// wx.showModal({
// title: "提示!",
// content: "用户权限未打开,请设置?",
// success(res) {
// if (res.confirm) {
// console.log("confirm, continued"); //确定设置,打开设置界面
// //@ts-ignore
// wx.openSetting({
// success(res){
// console.log('设置结果',res)
// },
// fail(){
// }
// })
// } else if (res.cancel) {
// console.log("cancel, cold");
// } else {
// // what happend?
// }
// },
// fail(res) {
// console.log(`showModal调用失败`);
// },
// });
// }
// else { //直接请求数据
// console.log('用户信息', PlayData.Instance.userInfo)
// if(PlayData.Instance.userInfo.name == ''){
// //console.log('直接请求用户信息')
// //@ts-ignore
// wx.getUserProfile({
// desc:'排行榜需要获取用户信息',
// success(res) {
// //console.log('获取用户信息成功', res);
// //window.userinfo = res.userInfo
// PlayData.Instance.userInfo.icon = res.userInfo.avatarUrl
// PlayData.Instance.userInfo.name = res.userInfo.nickName
// console.log('获取用户信息成功', res.userInfo)
// callback()
// //Storage.setUserInfo()
// let info = JSON.stringify(PlayData.Instance.userInfo)
// cc.sys.localStorage.setItem('userinfo', info)
// },
// fail(res) {
// //console.log('getUserInfo 调用失败',res);
// },
// });
// }else{callback()}
// }
// },fail(){
// //console.log('获取用户权限设置失败')
// }
// })
}
/**
* 获取用户当前的授权状态
* scope.userInfo wx.getUserInfo
* scope.WxFriendInteraction 对应开放数据域内的 wx.getFriendCloudStorage 、wx.getGroupCloudStorage 、wx.getGroupInfo 、wx.getPotentialFriendList 、wx.getUserCloudStorageKeys 、wx.getUserInfo 、GameServerManager.getFriendsStateData 接口,以及主域内的 wx.getUserInteractiveStorage 接口。
*/
getUserSetting(scopestr, callback){
if(scopestr == Scope.WxFriendInteraction){
//@ts-ignore
wx.getSetting({
success(res) {
if (!res.authSetting[scopestr]) {
//@ts-ignore
wx.authorize({
scope: scopestr,
success () { //授权成功
callback()
}
})
}else{
callback()
}
}
})
}else{
callback()
}
}
}