cocos-creator使用记录14_从web服务器获得分享图信息

1.流程
1.1.搭建一个可以转发http的服务器
要注意:这个服务器要可以被跨域访问,设置一下header就行,如何设置,自行探索。 
过程: 
(1)客户端请求该转发服务器,并把要获取的资源链接当参数传过去; 
(2)转发服务器收到请求之后解析一下参数,把资源链接提取出来,直接请求资源链接; 
(3)资源链接返回的数据给转发服务器; 
(4)转发服务器把收到的资源数据原封不动返回给客户端。 
1.2.获取分享图数据,将分享语和图片url赋值给微信函数


2.请求分享图服务器给出的API        
URL:https://www.mysite.net/common/game/share_list?app_name=run        
参数:app_name 指每个游戏唯一标识,英文数字下划线
返回:        
{
"code":0,
"msg":"\u6210\u529f", //成功
"data":{
"list":[ //会有多条数据
{
"id":"2",
"appName":"run", //游戏唯一标识
"image":"http:\/\/static.mysite.cn\/wxgame\/share\/201805\/Rw8FchPdz2EAQmZ2.png",
"position":"1", //位置:1.发起挑战,2.群分享续命,3.普通分享,4.分享得金币',5.胜利炫耀,6.分享成绩,7.查看群分享 
"title":"\u54c8\u54c8\u54c8", //分享文字
"weight":"1", //权重(当有多个同类可选择时,按权重随机)
"status":"0",
"createdAt":"1525343079",
"updatedAt":"1525433841"
}
...
]
}
}


3.客户端实例
这里以我的项目2048为例。
3.1.登陆微信公众平台注册https://www.mysite.net
在“设置”/“开发设置”页面中,设置服务器域名如下
request合法域名:https://www.mysite.net
若不设置,在微信开发者工具中会报错。


3.2.获得分享图信息
Start.js------------
var common = require('Common');
cc.Class({
extends: cc.Component,
properties: {
},
onLoad: function(){
this.httpRequest();
},
httpRequest: function() {
cc.log('发送请求');
//注意url最后面的游戏唯一标识,要使用自己项目对应的
var urlStr = 'https://www.mysite.net/common/game/share_list?app_name=2048';
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function () {
if (xhr.readyState === 4 && (xhr.status >= 200 && xhr.status < 400)) {
cc.log('收到数据', xhr);
var res = xhr.response;
common.shareList = [];
for(var i = 0; i < res.data.list.length; i++){
//2048只有1.发起挑战,2.群分享续命,3.普通分享,5.胜利炫耀,6.分享成绩
if(res.data.list[i].position == 1 || res.data.list[i].position == 2 || res.data.list[i].position == 3 || res.data.list[i].position == 5 || res.data.list[i].position == 6){
common.shareList.push({"position":res.data.list[i].position,"title":res.data.list[i].title, "imageUrl":res.data.list[i].image, "weight":res.data.list[i].weight});
}
}
}
};
xhr.open('GET', urlStr, true);
xhr.send();
},
});


Common.js------------
module.exports = {
    shareList: [], //分享图列表(其中元素{position,title,imageUrl,weight})(position:1.发起挑战,2.群分享续命,3.普通分享,4.分享得金币',5.胜利炫耀,6.分享成绩)


    getShareInfo: function(position){ //获得分享图信息
        if(position < 1 || position > 6) return null;
        var ret = null;
        var sameList = [];
        for(var i = 0; i < this.shareList.length; i++){
            if(this.shareList[i].position == position){
                sameList.push(i);
            }
        }
        if(sameList.length == 0){ //0
        }else if(sameList.length == 1){ //只有1张
            ret = {"title":this.shareList[sameList[0]].title, "imageUrl":this.shareList[sameList[0]].imageUrl};
        }else{ //有多张
            var str2 = "";
            var weightSum = 0; //权重和
            for(var i = 0; i < sameList.length; i++){ 
                weightSum += parseInt(this.shareList[sameList[i]].weight);
                str2 += this.shareList[sameList[i]].weight + ",";
            }
            console.log("权重:" + str2);
            console.log("weightSum=" + weightSum);
            var rate = []; //几率
            for(var i = 0; i < sameList.length; i++){ 
                rate.push(parseInt(this.shareList[sameList[i]].weight) / weightSum);
            }
            var str1 = "";
            for(var i = 0; i < rate.length; i++){
                str1 += rate[i] + ",";
            }
            console.log("几率:" + str1);
            var checkNum = []; //所有分享图的几率范围 0-20%-40%-...-100%
            checkNum.push(0);
            for(var i = 0; i < rate.length; i++){ //初始化
                checkNum.push(0);
            }
            for(var i = 1; i < checkNum.length; i++){ //累加几率
                for(var j = 1; j < i + 1 && j < checkNum.length; j++){ 
                    checkNum[i] += rate[j - 1];
                }
            }
            var str = "";
            for(var i = 0; i < checkNum.length; i++){ 
                str += checkNum[i] + ",";
            }
            console.log("几率范围:" + str);
            var num = Math.random();
            for(var i = 0; i < checkNum.length - 1; i++){ 
                if(num >= checkNum[i] && num < checkNum[i + 1]){
                    ret = {"title":this.shareList[sameList[i]].title, "imageUrl":this.shareList[sameList[i]].imageUrl};
                    break;
                }
            }
        }
        return ret;
    },
};


3.3.监听右上角的分享
Start.js------------
var common = require('Common');
cc.Class({
extends: cc.Component,
properties: {
},
onLoad: function(){
...
//开启右上角的分享
wx.showShareMenu();
this.scheduleOnce(function(){
this.shareListen();
}, 1); //延迟1秒
},


    shareListen: function(){ //监听右上角的分享 
        var data = common.getShareInfo(3);
        if(data == null){
            cc.loader.loadRes("texture/share",function(err,data){
                wx.onShareAppMessage(function(res){
                    return {
                        title: "经典2048游戏始终好玩如初,来吧!一起来回味吧!",
                        imageUrl: data.url,
                        success(res){
                            console.log("普通转发成功!!!")
                        },
                        fail(res){
                            console.log("普通失败!!!")
                        } 
                    }
                });
            });
        }else{
            console.log("右上角的分享!!!");
            wx.onShareAppMessage(function(res){
                return {
                    title: data.title,
                    imageUrl: data.imageUrl,
                    success(res){
                        console.log("普通转发成功!!!")
                    },
                    fail(res){
                        console.log("普通转发失败!!!")
                    } 
                }
            });
        }
    },
};


3.4.胜利炫耀和分享成绩
onShareBtnClicked: function(event, type){ //type:1分享挑战按钮、5炫耀一下按钮、6分享成绩按钮、
//cc.log("点击分享按钮");
console.log("type=" + type);
console.log("shareList.length=" + common.shareList.length);
var data = common.getShareInfo(type);
if(data == null){
cc.loader.loadRes("texture/share",function(err,data){ //主动拉起分享接口
wx.shareAppMessage({
title: "经典2048游戏始终好玩如初,来吧!一起来回味吧!",
imageUrl: data.url,
success(res){
console.log("转发成功!!!");
},
fail(res){
console.log("转发失败!!!");

})
});
}else{
if(type == 5){ //炫耀一下(成功的目标)
var str = data.title;
var index = this.targetScoreIndexMap[this.targetNumber];
if(index - 1 <= 0){
index = 0;
}else if(index - 1 >= 2){
index = 2;
}
var reg = /\{0\}/g;
data.title = str.replace(reg, this.targetScore[index].toString());
console.log("炫耀:" + data.title);
}else if(type == 6){ //分享成绩(失败时当前积分)
var str = data.title;
var reg = /\{0\}/g;
data.title = str.replace(reg, this.currentScore.toString());
console.log("分享成绩:" + data.title);
}
wx.shareAppMessage({ //主动拉起分享接口
title: data.title,
imageUrl: data.imageUrl,
success(res){
console.log("game:转发成功!!!")
},
fail(res){
console.log("game:转发失败!!!")

})
}
},


3.5.群分享续命
onSeekHelpBtnClicked: function(){ //加心界面求助好友群按钮
cc.log("点击加心界面求助好友群按钮");
var self = this;
var data = common.getShareInfo(2); //2群分享续命
if(data == null){
cc.loader.loadRes("texture/share",function(err,data){
wx.shareAppMessage({
title: "经典2048游戏始终好玩如初,来吧!一起来回味吧!",
imageUrl: data.url,
success(res){
if(res.shareTickets == null || res.shareTickets == undefined || res.shareTickets == ""){ //没有群信息,说明分享的是个人
self.showTipsUI("请分享到群获得生命值"); //自动消失提示框
}else{ //有群信息
if(res.shareTickets.length > 0){ 
common.heart = common.maxHeart; //恢复生命
self.timeNode.getComponent("CountDown").setState(0, 0); //设置时间文本为全满
self.onCloseBtnClicked();
self.showTipsUI("已回满生命值"); //自动消失提示框
}
}
},
fail(res){
//console.log("转发失败!!!");

})
});
}else{
wx.shareAppMessage({
title: data.title,
imageUrl: data.imageUrl,
success(res){
if(res.shareTickets == null || res.shareTickets == undefined || res.shareTickets == ""){ //没有群信息,说明分享的是个人
self.showTipsUI("请分享到群获得生命值"); //自动消失提示框
}else{ //有群信息
if(res.shareTickets.length > 0){ 
common.heart = common.maxHeart; //恢复生命
self.timeNode.getComponent("CountDown").setState(0, 0); //设置时间文本为全满
self.onCloseBtnClicked();
self.showTipsUI("已回满生命值"); //自动消失提示框
}
}
},
fail(res){
//console.log("转发失败!!!");

})
}
},

猜你喜欢

转载自blog.csdn.net/haibo19981/article/details/80452415