说明
appInfo至少需要包含三个字段,id,WxRewardedVideoID,WxInterstitialID
调用示例:
this.WxAd.show('WxInterstitial',function(){
//TODO handle success
},function(err){
console.log(err)
})
代码段
import { request,toastMessage } from '@/common/utils.js';
export class InsAd{
constructor(){
this.appInfo = null;//微信小程序信息
// this.WxRewardedVideo = null;//微信激励视频
}
getInfo(){
const t = this;
return new Promise(function(resolve,reject){
if(t.appInfo&&t.appInfo.id&&/^\d+$/.test(t.appInfo.id)){
return resolve(t.appInfo);
}
return request('xxxxxxxxxxxx',{},{loading:false}).then((e)=>{
if(e&&e.data&&e.data.appInfo){
t.appInfo = e.data.appInfo;
return resolve(e.data.appInfo);
}
return reject({errMsg:'支付广告参数获取失败'});
}).catch((e)=>{
return reject({errMsg:e.message});
})
})
}
show(type,susFun,errFun){
const t = this;
showLoading('加载中...');
t.load(type).then(()=>{
t[type].susFun = susFun
t[type].show().then(()=>{
hideLoading();
}).catch(err=>{
return (typeof errFun == 'function')?errFun(err):false;
});
}).catch((err)=>{
return (typeof errFun == 'function')?errFun(err):false;
})
}
load(type){
const t = this;
return new Promise((resolve,reject)=>{
//如果已经初始化load了,则直接返回
if(t[type]&&t[type].$exist){
return resolve(t[type]);
}
// 获取初始化实例
t.getIns(type).then(()=>{
t[type]['expire'] = setTimeout(()=>{
if(!t[type].$exist){
reject({errMsg:'广告加载超时'});
clearTimeout(t[type]['expire']);
return;
}
},10000);
t[type].onClose(function(v){
if(v&&v.isEnded&&(typeof t[type].susFun == 'function')){
t[type].susFun(t[type]);
}
});
t[type].onError((err) => {
return reject(err);
})
t[type].onLoad((ppp) => {
if(!t[type].$exist){
t[type].$exist = true;
return resolve(t[type]);
}
})
}).catch((err)=>{
return reject(err);
})
})
}
getIns(type){
const t = this;
return new Promise((resolve,reject)=>{
if(t[type]){
return resolve(t[type]);
}
t.getInfo().then(()=>{
if(type=='WxRewardedVideo'&&t.appInfo&&t.appInfo.WxRewardedVideoID&&uni.createRewardedVideoAd){
const AdID = t.appInfo.WxRewardedVideoID;
if((typeof AdID == 'string')&&(AdID.length>0)){
t[type] = uni.createRewardedVideoAd({ adpid:AdID,adUnitId:AdID });
return resolve(t[type]);
}
}else if(type=='WxInterstitial'&&t.appInfo&&t.appInfo.WxInterstitialID&&uni.createInterstitialAd){
const AdID = t.appInfo.WxInterstitialID;
if((typeof AdID == 'string')&&(AdID.length>0)){
t[type] = uni.createInterstitialAd({ adpid:AdID,adUnitId:AdID });
return resolve(t[type]);
}
}else{
return reject('暂不支持该类型广告');
}
}).catch((err)=>{
return reject(err);
})
})
}
}
function showLoading(msg){
uni.showLoading({ title:msg })
}
function hideLoading(){
try{
uni.hideLoading();
}catch(e){
//TODO handle the exception
}
}