Commit 4b08db29 authored by liuxinjun's avatar liuxinjun

laya的sdk

parents
#/////////////////////////////////////////////////////////////////////////////
# Fireball Projects
#/////////////////////////////////////////////////////////////////////////////
library/
temp/
local/
build/
#/////////////////////////////////////////////////////////////////////////////
# Logs and databases
#/////////////////////////////////////////////////////////////////////////////
*.log
*.sql
*.sqlite
#/////////////////////////////////////////////////////////////////////////////
# files for debugger
#/////////////////////////////////////////////////////////////////////////////
*.sln
*.csproj
*.pidb
*.unityproj
*.suo
#/////////////////////////////////////////////////////////////////////////////
# OS generated files
#/////////////////////////////////////////////////////////////////////////////
.DS_Store
ehthumbs.db
Thumbs.db
#/////////////////////////////////////////////////////////////////////////////
# exvim files
#/////////////////////////////////////////////////////////////////////////////
*UnityVS.meta
*.err
*.err.meta
*.exvim
*.exvim.meta
*.vimentry
*.vimentry.meta
*.vimproject
*.vimproject.meta
.vimfiles.*/
.exvim.*/
quick_gen_project_*_autogen.bat
quick_gen_project_*_autogen.bat.meta
quick_gen_project_*_autogen.sh
quick_gen_project_*_autogen.sh.meta
.exvim.app
#/////////////////////////////////////////////////////////////////////////////
# webstorm files
#/////////////////////////////////////////////////////////////////////////////
.idea/
#//////////////////////////
# VS Code
#//////////////////////////
.vscode/
\ No newline at end of file
{
"ver": "1.0.1",
"uuid": "747b0c1c-abbc-4720-a7e3-19205bf52be6",
"subMetas": {}
}
\ No newline at end of file
{
"ver": "1.0.0",
"uuid": "effc9204-83b3-4c05-8909-2837b3fc328e",
"subMetas": {}
}
\ No newline at end of file
/*
* JavaScript MD5
* https://github.com/blueimp/JavaScript-MD5
*
* Copyright 2011, Sebastian Tschan
* https://blueimp.net
*
* Licensed under the MIT license:
* https://opensource.org/licenses/MIT
*
* Based on
* A JavaScript implementation of the RSA Data Security, Inc. MD5 Message
* Digest Algorithm, as defined in RFC 1321.
* Version 2.2 Copyright (C) Paul Johnston 1999 - 2009
* Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet
* Distributed under the BSD License
* See http://pajhome.org.uk/crypt/md5 for more info.
*/
/* global define */
;(function ($) {
'use strict'
/*
* Add integers, wrapping at 2^32. This uses 16-bit operations internally
* to work around bugs in some JS interpreters.
*/
function safeAdd (x, y) {
var lsw = (x & 0xffff) + (y & 0xffff)
var msw = (x >> 16) + (y >> 16) + (lsw >> 16)
return (msw << 16) | (lsw & 0xffff)
}
/*
* Bitwise rotate a 32-bit number to the left.
*/
function bitRotateLeft (num, cnt) {
return (num << cnt) | (num >>> (32 - cnt))
}
/*
* These functions implement the four basic operations the algorithm uses.
*/
function md5cmn (q, a, b, x, s, t) {
return safeAdd(bitRotateLeft(safeAdd(safeAdd(a, q), safeAdd(x, t)), s), b)
}
function md5ff (a, b, c, d, x, s, t) {
return md5cmn((b & c) | (~b & d), a, b, x, s, t)
}
function md5gg (a, b, c, d, x, s, t) {
return md5cmn((b & d) | (c & ~d), a, b, x, s, t)
}
function md5hh (a, b, c, d, x, s, t) {
return md5cmn(b ^ c ^ d, a, b, x, s, t)
}
function md5ii (a, b, c, d, x, s, t) {
return md5cmn(c ^ (b | ~d), a, b, x, s, t)
}
/*
* Calculate the MD5 of an array of little-endian words, and a bit length.
*/
function binlMD5 (x, len) {
/* append padding */
x[len >> 5] |= 0x80 << (len % 32)
x[((len + 64) >>> 9 << 4) + 14] = len
var i
var olda
var oldb
var oldc
var oldd
var a = 1732584193
var b = -271733879
var c = -1732584194
var d = 271733878
for (i = 0; i < x.length; i += 16) {
olda = a
oldb = b
oldc = c
oldd = d
a = md5ff(a, b, c, d, x[i], 7, -680876936)
d = md5ff(d, a, b, c, x[i + 1], 12, -389564586)
c = md5ff(c, d, a, b, x[i + 2], 17, 606105819)
b = md5ff(b, c, d, a, x[i + 3], 22, -1044525330)
a = md5ff(a, b, c, d, x[i + 4], 7, -176418897)
d = md5ff(d, a, b, c, x[i + 5], 12, 1200080426)
c = md5ff(c, d, a, b, x[i + 6], 17, -1473231341)
b = md5ff(b, c, d, a, x[i + 7], 22, -45705983)
a = md5ff(a, b, c, d, x[i + 8], 7, 1770035416)
d = md5ff(d, a, b, c, x[i + 9], 12, -1958414417)
c = md5ff(c, d, a, b, x[i + 10], 17, -42063)
b = md5ff(b, c, d, a, x[i + 11], 22, -1990404162)
a = md5ff(a, b, c, d, x[i + 12], 7, 1804603682)
d = md5ff(d, a, b, c, x[i + 13], 12, -40341101)
c = md5ff(c, d, a, b, x[i + 14], 17, -1502002290)
b = md5ff(b, c, d, a, x[i + 15], 22, 1236535329)
a = md5gg(a, b, c, d, x[i + 1], 5, -165796510)
d = md5gg(d, a, b, c, x[i + 6], 9, -1069501632)
c = md5gg(c, d, a, b, x[i + 11], 14, 643717713)
b = md5gg(b, c, d, a, x[i], 20, -373897302)
a = md5gg(a, b, c, d, x[i + 5], 5, -701558691)
d = md5gg(d, a, b, c, x[i + 10], 9, 38016083)
c = md5gg(c, d, a, b, x[i + 15], 14, -660478335)
b = md5gg(b, c, d, a, x[i + 4], 20, -405537848)
a = md5gg(a, b, c, d, x[i + 9], 5, 568446438)
d = md5gg(d, a, b, c, x[i + 14], 9, -1019803690)
c = md5gg(c, d, a, b, x[i + 3], 14, -187363961)
b = md5gg(b, c, d, a, x[i + 8], 20, 1163531501)
a = md5gg(a, b, c, d, x[i + 13], 5, -1444681467)
d = md5gg(d, a, b, c, x[i + 2], 9, -51403784)
c = md5gg(c, d, a, b, x[i + 7], 14, 1735328473)
b = md5gg(b, c, d, a, x[i + 12], 20, -1926607734)
a = md5hh(a, b, c, d, x[i + 5], 4, -378558)
d = md5hh(d, a, b, c, x[i + 8], 11, -2022574463)
c = md5hh(c, d, a, b, x[i + 11], 16, 1839030562)
b = md5hh(b, c, d, a, x[i + 14], 23, -35309556)
a = md5hh(a, b, c, d, x[i + 1], 4, -1530992060)
d = md5hh(d, a, b, c, x[i + 4], 11, 1272893353)
c = md5hh(c, d, a, b, x[i + 7], 16, -155497632)
b = md5hh(b, c, d, a, x[i + 10], 23, -1094730640)
a = md5hh(a, b, c, d, x[i + 13], 4, 681279174)
d = md5hh(d, a, b, c, x[i], 11, -358537222)
c = md5hh(c, d, a, b, x[i + 3], 16, -722521979)
b = md5hh(b, c, d, a, x[i + 6], 23, 76029189)
a = md5hh(a, b, c, d, x[i + 9], 4, -640364487)
d = md5hh(d, a, b, c, x[i + 12], 11, -421815835)
c = md5hh(c, d, a, b, x[i + 15], 16, 530742520)
b = md5hh(b, c, d, a, x[i + 2], 23, -995338651)
a = md5ii(a, b, c, d, x[i], 6, -198630844)
d = md5ii(d, a, b, c, x[i + 7], 10, 1126891415)
c = md5ii(c, d, a, b, x[i + 14], 15, -1416354905)
b = md5ii(b, c, d, a, x[i + 5], 21, -57434055)
a = md5ii(a, b, c, d, x[i + 12], 6, 1700485571)
d = md5ii(d, a, b, c, x[i + 3], 10, -1894986606)
c = md5ii(c, d, a, b, x[i + 10], 15, -1051523)
b = md5ii(b, c, d, a, x[i + 1], 21, -2054922799)
a = md5ii(a, b, c, d, x[i + 8], 6, 1873313359)
d = md5ii(d, a, b, c, x[i + 15], 10, -30611744)
c = md5ii(c, d, a, b, x[i + 6], 15, -1560198380)
b = md5ii(b, c, d, a, x[i + 13], 21, 1309151649)
a = md5ii(a, b, c, d, x[i + 4], 6, -145523070)
d = md5ii(d, a, b, c, x[i + 11], 10, -1120210379)
c = md5ii(c, d, a, b, x[i + 2], 15, 718787259)
b = md5ii(b, c, d, a, x[i + 9], 21, -343485551)
a = safeAdd(a, olda)
b = safeAdd(b, oldb)
c = safeAdd(c, oldc)
d = safeAdd(d, oldd)
}
return [a, b, c, d]
}
/*
* Convert an array of little-endian words to a string
*/
function binl2rstr (input) {
var i
var output = ''
var length32 = input.length * 32
for (i = 0; i < length32; i += 8) {
output += String.fromCharCode((input[i >> 5] >>> (i % 32)) & 0xff)
}
return output
}
/*
* Convert a raw string to an array of little-endian words
* Characters >255 have their high-byte silently ignored.
*/
function rstr2binl (input) {
var i
var output = []
output[(input.length >> 2) - 1] = undefined
for (i = 0; i < output.length; i += 1) {
output[i] = 0
}
var length8 = input.length * 8
for (i = 0; i < length8; i += 8) {
output[i >> 5] |= (input.charCodeAt(i / 8) & 0xff) << (i % 32)
}
return output
}
/*
* Calculate the MD5 of a raw string
*/
function rstrMD5 (s) {
return binl2rstr(binlMD5(rstr2binl(s), s.length * 8))
}
/*
* Calculate the HMAC-MD5, of a key and some data (raw strings)
*/
function rstrHMACMD5 (key, data) {
var i
var bkey = rstr2binl(key)
var ipad = []
var opad = []
var hash
ipad[15] = opad[15] = undefined
if (bkey.length > 16) {
bkey = binlMD5(bkey, key.length * 8)
}
for (i = 0; i < 16; i += 1) {
ipad[i] = bkey[i] ^ 0x36363636
opad[i] = bkey[i] ^ 0x5c5c5c5c
}
hash = binlMD5(ipad.concat(rstr2binl(data)), 512 + data.length * 8)
return binl2rstr(binlMD5(opad.concat(hash), 512 + 128))
}
/*
* Convert a raw string to a hex string
*/
function rstr2hex (input) {
var hexTab = '0123456789abcdef'
var output = ''
var x
var i
for (i = 0; i < input.length; i += 1) {
x = input.charCodeAt(i)
output += hexTab.charAt((x >>> 4) & 0x0f) + hexTab.charAt(x & 0x0f)
}
return output
}
/*
* Encode a string as utf-8
*/
function str2rstrUTF8 (input) {
return unescape(encodeURIComponent(input))
}
/*
* Take string arguments and return either raw or hex encoded strings
*/
function rawMD5 (s) {
return rstrMD5(str2rstrUTF8(s))
}
function hexMD5 (s) {
return rstr2hex(rawMD5(s))
}
function rawHMACMD5 (k, d) {
return rstrHMACMD5(str2rstrUTF8(k), str2rstrUTF8(d))
}
function hexHMACMD5 (k, d) {
return rstr2hex(rawHMACMD5(k, d))
}
function md5 (string, key, raw) {
if (!key) {
if (!raw) {
return hexMD5(string)
}
return rawMD5(string)
}
if (!raw) {
return hexHMACMD5(key, string)
}
return rawHMACMD5(key, string)
}
if (typeof define === 'function' && define.amd) {
define(function () {
return md5
})
} else if (typeof module === 'object' && module.exports) {
module.exports = md5
} else {
$.md5 = md5
}
})(this)
\ No newline at end of file
{
"ver": "1.0.5",
"uuid": "d74f5771-2091-4328-b08b-f287b53cd220",
"isPlugin": false,
"loadPluginInWeb": true,
"loadPluginInNative": true,
"loadPluginInEditor": false,
"subMetas": {}
}
\ No newline at end of file
/**
1.安装apidoc,参考链接:
http://apidocjs.com
2.按照格式弄好后,执行命令
apidoc -i ./apiTest/assets/Sdk -o api/
在小程序后台添加合法域名:
https://game.llewan.com:1899
https://login.llewan.com:1799
https://log.llewan.com:1999
https://res.llewan.com:2099
https://glog.aldwx.com
*/
var md5 = require("md5");
var sdk_conf = require("sdk_conf");
var mta = require("mta");
var sdk = {
md5: md5,
mta: mta,
ip1: "https://login.llewan.com:1799",
ip2: "https://game.llewan.com:1899",
ip3: "https://log.llewan.com:1999",
ip4: "https://res.llewan.com:2099",
loginBg: "https://res.g.llewan.com/uploadfile/common/20180831/20180831173032_3279.png",
loginBt: "https://res.g.llewan.com/uploadfile/common/20180831/20180831180006_1583.png",
debug: false,//是否开启调试
login: '/Login/common',
modify: '/Login/modify',
Config: '/Config/common',
//游戏数据存储/获取
set: "/game/set",
get: "/game/get",
time: "/game/time",
ConfigData: {
"config1": {},
"config2": {},
"config3": {},
"config4": {},
},
Share: "/Share/common",
ShareList: [],
Logcommon: "/Log/common",
BannerAd: null,
VideoAd: null,
//.即将废弃,请不要操作此变量。
userid: 0,
initFlag: 0,
//视频成功回调
videoSuccess: null,
//视频失败回调
videoFail: null,
isGameStart: false,
gameOnlineKey: "游戏在线",
shareStartTime: -1,
shareInfo: null,
/**
* @apiGroup A
* @apiName init
* 从v1.006版本的sdk已经废弃改方法,只需要调用sdk.WeChatLogin方法就可以了
*
* sdk.WeChatLogin((d)=>{
* var config1 = sdk.getConfig1();
* if(config1.hz2==1)
* {
* //显示
* xxx.active = true;
* xxx.addClickListener(() => {
* var d = sdk.getButtonConfig('hz2');
* //跳转到对应的小程序或者游戏
* sdk.navigateToMiniProgram(d);
* });
* }else
* {
* //隐藏
* }
*
* });
*/
init(args, callback) {
var self = this;
if (!self.ip1) {
console.error("sdk 请调用WechatLogin!");
wx.showToast({ title: '请先登录', icon: 'loading', duration: 8 });
return;
}
if (args.debug) {
this.debug = args.debug;
}
if (args.userid) {
this.userid = args.userid;
}
this.checkUpdate();
if (true) {
//1.初始化后台配置信息
this.Post(this.ip2 + this.Config, {}, function (d) {
// console.log(d);
if (d && d.c == 1) {
self.ConfigData = d.d;
//2.初始化分享信息
self.Post(self.ip2 + self.Share, {}, function (d2) {
// console.log("初始化分享信息:",d2)
if (d2 && d2.c == 1) {
self.ShareList = d2.d;
} else {
console.log("sdk 初始化分享信息失败:", d2)
}
callback(true);
});
} else {
if (self.debug) {
console.log("sdk 后台配置信息初始化失败,再次初始化:", d)
}
self.init(args, callback);
// return;
}
});
if (this.getUser()) {
this.userid = this.getUser().uid;
}
if (this.userid && self.initFlag === 0) {
//2.统计:分享信息 测试: uid=56032607&share_id=22&share_uid=56032607
var option = wx.getLaunchOptionsSync();
// console.log("==option==", option)
if (option.query.share_id && option.query.uid) {
option.query.share_uid = option.query.uid;
option.query.uid = this.userid;
// console.log('==3统计信息==',option)
this.Post(this.ip3 + this.Logcommon, { log_type: "ShareEnter", data: JSON.stringify(option) }, function (d) {
// console.log("==3统计信息结果==", d)
});
}
wx.onShow((option) => {
// console.log(option)
if (option.query.uid) {
option.query.share_uid = option.query.uid;
option.query.uid = self.userid;
// console.log('==4统计信息==',option)
self.Post(self.ip3 + self.Logcommon, { log_type: "ShareEnter", data: JSON.stringify(option) }, function (d) {
// console.log("==4统计信息结果==", d)
});
}
})
//5.统计:每次打开小游戏调用
wx.getSystemInfo({
success(res) {
var loginData = res;
loginData.uid = self.userid;
loginData.share_uid = option.query.share_uid;
loginData.scene = option.scene;
loginData.source_id = option.query.source_id;
loginData.source_id2 = option.query.source_id2;
loginData.special_flag = option.query.special_flag;
self.setItem("deviceModel", res.model);
if (sdk_conf.game_online) {
//开启游戏统计情况下
self.gameStart({}, null);
}
wx.getNetworkType({
success(res2) {
loginData.network_type = res2.networkType;
console.log("sdk LoginData", loginData)
self.Get(self.ip3 + self.Logcommon, { log_type: "LoginData", data: JSON.stringify(loginData) }, function (d) {
//很重要防止因为配置获取失败,重复调用
self.initFlag = 1;
});
}
})
}
})
}
//为了方便技术在浏览器中调试
this.setWeChatListener();
}
},
/**
* @apiGroup C
* @apiName WeChatLogin
* @api {新增、授权、登陆} 微信登录 WeChatLogin 对外提供新增、授权、登陆调用以及初始化
* 注意v1.006版本sdk 只需要调用登录就可以了不在需要调用init了,sdk内部已经做了init操作了
*
* @apiSuccessExample {json} 示例:
* sdk.WeChatLogin((d)=>{
* var config1 = sdk.getConfig1();
* if(config1.hz2==1)
* {
* //显示
* xxx.active = true;
*
* xxx.addClickListener(() => {
* var d = sdk.getButtonConfig('hz2');
* //跳转到对应的小程序或者游戏
* sdk.navigateToMiniProgram(d);
* });
* }else
* {
* //隐藏
* }
*
* });
*
*/
WeChatLogin(callback) {
//根据sdk_conf初始化api
this.init_api();
var self = this;
if (true) {
var userinfo = this.getUser();
var wxauth = this.getItem("wxauth"); //记录微信是否授权
if (userinfo && wxauth) {
console.log("sdk 直接进入游戏");
//用户信息获取到并且授权了
self.init({}, (config) => {
console.log('sdk 初始化结果:', config);
callback(userinfo);
});
} else if (userinfo && !wxauth) {
//用户信息存在但是没有授权,就应该去授权后调用服务端member/update用户信息
this.WxAuthLogin((userData) => {
self.init({}, (config) => {
console.log('sdk 初始化结果:', config);
callback(userData);
});
});
} else if (!userinfo && wxauth) {
//用户信息没有但是有授权,就应该去登陆并且去授权后调用服务端member/update用户信息
this.WxAuthLogin((userData) => {
//callback(d);
self.init({}, (config) => {
console.log('sdk 初始化结果:', config);
callback(userData);
});
});
}
else {
//没有用户信息,也没有授权,就应该去登陆并且去授权后调用服务端member/update用户信息
self.WxLogin((d) => {
//if(d.c==1)
//{
self.WxAuthLogin((userData) => {
self.init({}, (config) => {
console.log('sdk 初始化结果:', config);
callback(userData);
});
});
//}else
//{
// console.error("sdk 登陆失败",d);
//}
});
}
}
},
/**
* @apiGroup C
* @apiName wxAuth
* @api {微信授权} 微信授权登录 WxAuthLogin(授权)不对外提供调用
*
*/
WxAuthLogin(callback) {
var self = this;
if (true) {
var options = wx.getLaunchOptionsSync();
var referee_id = options.query.uid; //.推荐人id
var source_id = options.query.source_id; //.用户来源id
var source_id2 = options.query.source_id2; //.用户来源子id
var share_id = options.query.share_id; //.分享素材ID
var special_flag = options.query.special_flag;
var userinfo = this.getUser();
wx.getSystemInfo({
success(res) {
var width = 507 / 2;
var height = 464 / 2;
self.button = wx.createUserInfoButton({
type: 'image',
image: self.loginBt,
style: { width: width, height: height, left: res.screenWidth / 2 - width / 2, top: res.screenHeight / 2 - height / 2 }
})
self.button.onTap((res1) => {
// 处理用户拒绝授权的情况
// if (res1.errMsg.indexOf('auth deny') > -1 || res1.errMsg.indexOf('auth denied') > -1 ) {
// wx.showToast();
// }
wx.showToast({ title: '登录中...', icon: 'loading', duration: 8 });
wx.getSetting({
success(auths) {
if (auths.authSetting["scope.userInfo"]) {
self.setItem("wxauth", 1);
console.log('sdk 用户已经授权');
var reqData = {
rawData: res1.rawData,
iv: res1.iv,
encryptedData: res1.encryptedData,
signature: res1.signature,
referee_id: referee_id,
source_id: source_id,
source_id2: source_id2,
share_id: share_id,
special_flag: special_flag,
}
// console.log('==登录参数==', reqData)
self.Post(self.ip1 + self.modify, reqData, function (data) {
console.log('sdk 更新用户信息结果', data)
if (data.c == 1) {
self.setItem('userinfo', JSON.stringify(data.d));
wx.hideToast();
maskNode.destroy();
self.button.hide();
//.登录成功,重新初始化
self.userid = data.d.uid;
//self.init({},(d)=>{})
callback(data.d);
} else {
console.log(' sdk 登录接口请求失败', data)
wx.showToast({ title: '登录失败请重试3' });
}
});
} else {
callback(false)
}
}
})
})
self.button.show()
}
})
//.登录遮罩背景
// var maskNode = new cc.Node('Sprite');
// maskNode.parent = cc.director.getScene().getChildByName('Canvas');
// maskNode.addComponent(cc.BlockInputEvents)
// var sp = maskNode.addComponent(cc.Sprite);
// maskNode.opacity = 178;
// maskNode.color = new cc.Color(25,88,95,255);
// sp.sizeMode = cc.Sprite.SizeMode.CUSTOM;
// self.createImage(sp, self.loginBg);
// maskNode.width = cc.view.getVisibleSize().width;
// maskNode.height = cc.view.getVisibleSize().height;
// console.log(maskNode.width, maskNode.height)
//.微信登录按钮
if (self.button) {
self.button.show();
} else {
}
}
},
setWeChatListener() {
let self = this;
wx.onHide(function (res) {
//监听小游戏隐藏到后台事件。锁屏、按 HOME 键退到桌面、显示在聊天顶部等操作会触发此事件。
console.log("sdk 小游戏隐藏到后台");
self.uploadSceneEvent(null, '隐藏小游戏到后台', null);
if (self.isGameStart && sdk_conf.game_online) {
// var data = JSON.parse(this.getItem("游戏在线"));
// var nowTime = new Date().getTime();
// data.take_time = data.take_time+ ((nowTime/1000)-data.last_time);
// data.last_time = nowTime/1000;
// this.setItem("游戏在线",JOSN.stringify(data));
self.setSceneEnd(self.getGameOnlineKey(), {});
}
if (self.shareStartTime > 0) {
//隐藏发生在分享调起
console.log("sdk 隐藏发生在分享调起");
}
});
wx.onShow(function (res) {
//监听小游戏回到前台的事件
console.log("sdk 监听小游戏回到前台的事件");
var nowTime = new Date().getTime();
if (self.isGameStart && sdk_conf.game_online) {
var onlineKey = self.getGameOnlineKey();
var dataString = self.getItem(onlineKey);
var data = JSON.parse(dataString);
data.last_time = nowTime / 1000;
console.log("onShow->" + onlineKey, JSON.stringify(data));
self.setItem(onlineKey, JSON.stringify(data));
}
if (self.shareStartTime > 0) {
var shareTime = (nowTime / 1000) - self.shareStartTime;
if (shareTime >= sdk_conf.share_time_limit) {
console.log("sdk 分享成功");
if (self.shareInfo.successCallback) {
//分享成功 调用api记录分享数据
self.shareInfo.successCallback();
console.log("sdk 分享成功回调");
}
//分享成功记录到服务器
var option = { 'uid': sdk.userid, 'share_id': self.shareInfo.sysid };
self.Get(self.ip3 + self.Logcommon, { log_type: "ShareClick", data: JSON.stringify(option) }, function (d) {
console.log("sdk 分享成功记录到服务器");
});
} else {
console.log("sdk 分享失败");
//分享失败 回调失败
if (self.shareInfo.failCallback) {
self.shareInfo.failCallback();
console.log("sdk 分享失败回调");
}
}
//重置分享数据
self.shareStartTime = -1;
self.shareInfo = null;
console.log("sdk 清空分享数据记录");
}
});
},
WeChatLoginNoAuth(callback) {
//根据sdk_conf初始化api
this.init_api();
var self = this;
if (true) {
var userinfo = this.getUser();
if (userinfo) {
console.log("sdk 直接进入游戏");
//用户信息获取到并且授权了
self.init({}, (config) => {
console.log('sdk 初始化结果:', config);
callback(userinfo);
});
}
else {
//没有用户信息,也没有授权,就应该去登陆并且去授权后调用服务端member/update用户信息
self.WxLogin((userData) => {
self.init({}, (config) => {
console.log('sdk 初始化结果:', config);
callback(userData);
});
});
}
}
},
/**
* @apiGroup C
* @apiName wxLogin
* @api {新增} 获取设备信息新增用户 wxLogin 不对外提供调用
*
*/
WxLogin(callback) {
var self = this;
if (true) {
var options = wx.getLaunchOptionsSync();
var referee_id = options.query.uid; //.推荐人id
var source_id = options.query.source_id; //.用户来源id
var source_id2 = options.query.source_id2; //.用户来源子id
var share_id = options.query.share_id; //.分享素材ID
var special_flag = options.query.special_flag;
//wx.getSystemInfo({
// success(res){
wx.login({
success(res2) {
var reqData = {
code: res2.code,
referee_id: referee_id,
source_id: source_id,
source_id2: source_id2,
share_id: share_id,
special_flag: special_flag
// model: res.model,
// platform: res.platform,
// wx_version: res.version,
// network_type: res.networkType,
// scene_value: res.scene,
// brand: res.brand,
// sdk_version: res.SDKVersion,
}
console.log('sdk 注册参数', reqData)
self.Post(self.ip1 + self.login, reqData, function (data) {
console.log('sdk 新增登陆结果', data);
if (data.c == 1) {
self.setItem('userinfo', JSON.stringify(data.d));
callback(data.d);
} else {
console.log('sdk 登录接口请求失败', data)
wx.showToast({ title: '登录失败请重试1' });
}
});
},
fail() {
wx.showToast({ title: '登录失败请重试2' });
//console.error("systemInfo",res);
callback(false)
},
});
//}
//});
}
},
/**
* 微信授权
*
* 用户点击游戏中授权按钮之后将授权的数据res传递进来
*
* self.button = wx.createUserInfoButton({
})
* self.button.onTap((res) => {
* sdk.WechatAuth(res,function (d) {
*
* })
* });
*/
WechatAuth(res, callback) {
if (true) {
var options = wx.getLaunchOptionsSync();
var referee_id = options.query.share_uid; //.推荐人id
var source_id = options.query.source_id; //.用户来源id
var source_id2 = options.query.source_id2; //.用户来源子id
var share_id = options.query.share_id; //.分享素材ID
var special_flag = options.query.special_flag;
self.setItem("wxauth", 1);
console.log('sdk 用户已经授权');
var reqData = {
rawData: res.rawData,
iv: res.iv,
encryptedData: res.encryptedData,
signature: res.signature,
referee_id: referee_id,
source_id: source_id,
source_id2: source_id2,
share_id: share_id,
special_flag: special_flag,
}
console.log('sdk 授权参数', reqData)
self.Post(self.ip1 + self.modify, reqData, function (data) {
console.log('sdk 更新用户信息结果', data)
if (data.c == 1) {
self.setItem('userinfo', JSON.stringify(data.d));
//.登录成功,重新初始化
self.userid = data.d.uid;
//self.init({},(d)=>{})
callback(data.d);
} else {
console.log(' sdk 授权接口请求失败', data)
wx.showToast({ title: '授权失败请重试3' });
}
});
}
},
/**
* 初始化接口
*/
init_api() {
if (sdk_conf.env === 'prod') {
this.ip1 = sdk_conf.env_apis.prod.ip1;
this.ip2 = sdk_conf.env_apis.prod.ip2;
this.ip3 = sdk_conf.env_apis.prod.ip3;
this.ip4 = sdk_conf.env_apis.prod.ip4;
} else {
this.ip1 = sdk_conf.env_apis.test.ip1;
this.ip2 = sdk_conf.env_apis.test.ip2;
this.ip3 = sdk_conf.env_apis.test.ip3;
this.ip4 = sdk_conf.env_apis.test.ip4;
}
console.log("sdk ip1", this.ip1);
console.log("sdk ip2", this.ip2);
console.log("sdk ip3", this.ip3);
console.log("sdk ip4", this.ip4);
},
//.根据权重随机获取指定type类型的分享信息。(没有this.ShareList数据不能调用)
getShareByWeight(type) {
if (this.ShareList.length > 0) {
//1.获取某种type的集合
var tArray = [];
for (var i = 0; i < this.ShareList.length; i++) {
if (type == this.ShareList[i].type) {
this.ShareList[i].weight = parseInt(this.ShareList[i].weight);
tArray.push(this.ShareList[i]);
}
}
//2.根据权重配比:从i集合(权重越大占比越多)中随机获取。
var iArray = [];
for (var i = 0; i < tArray.length; i++) {
for (var j = 0; j < tArray[i].weight; j++) {
iArray.push(i);
}
}
var i = iArray[parseInt(Math.random() * iArray.length)];
//3.结果处理:正则替换昵称
var item = tArray[i];
if (item.title.indexOf("&nickName") != -1) {
item.title = item.title.replace(/&nickName/g, this.getUser().nickName);
}
return JSON.parse(JSON.stringify(item));
} else {
return null;
}
},
/**
* @apiGroup C
* @apiName onShareAppMessage
* @api {分享} 注册微信右上角分享 onShareAppMessage(分享)
* @apiParam {int} type=0 后台自定义的分享类型;例如:0:右上角分享、1:普通分享 2:分享加金币
* @apiParam {int} specialFlag=0 特殊标记,例如0:默认、1:邀新好友、2:邀旧好友
* @apiParam {String} [title] 转发标题
* @apiParam {String} [imageUrl] 转发显示图片的链接
* @apiParam {String} [query] 必须是 key1=val1&key2=val2 的格式。
* @apiParam {callback} [success] 成功回调
* @apiParam {callback} [fail] 失败回调
*
* @apiSuccessExample {json} 示例:
* sdk.onShareAppMessage({type: 0, query: "uid=520" });
*/
onShareAppMessage(obj) {
var self = this;
if (true) {
//.微信右上角分享
var specialFlag = 0;
wx.showShareMenu({ withShareTicket: true })
wx.onShareAppMessage(function (res) {
//.默认0:右上角分享
var tpye = 0;
if (obj.type) {
tpye = obj.type;
}
if (obj.specialFlag) {
specialFlag = obj.specialFlag;
}
var shareInfo = self.getShareByWeight(tpye)
if (obj.title) {
shareInfo.title = obj.title;
}
if (obj.imageUrl) {
shareInfo.imageUrl = obj.imageUrl;
}
if (shareInfo.query) {
shareInfo.query += obj.query + "&share_id=" + shareInfo.sysid + "&uid=" + self.userid + "&special_flag=" + specialFlag;
} else {
if (obj.query) {
shareInfo.query = "share_id=" + shareInfo.sysid + "&uid=" + self.userid + "&special_flag=" + specialFlag + "&" + obj.query;
} else {
shareInfo.query = "share_id=" + shareInfo.sysid + "&uid=" + self.userid + "&special_flag=" + specialFlag;
}
}
if (obj.success) {
shareInfo.successCallback = obj.success;
}
if (obj.fail) {
shareInfo.failCallback = obj.fail;
}
var nowTime = new Date().getTime();
self.shareStartTime = nowTime / 1000;
self.shareInfo = shareInfo;
// var option = {'uid': sdk.userid, 'share_id': shareInfo.sysid };
// self.Get(self.ip3 + self.Logcommon, { log_type: "ShareClick", data: JSON.stringify(option) }, function (d) {
// });
return shareInfo;
})
}
},
/**
* @apiGroup C
* @apiName shareAppMessage
* @api {分享} 主动拉起微信分享 shareAppMessage(分享)
* @apiParam {int} type=1 后台自定义的分享类型;例如:0:右上角分享、1:普通分享 2:分享加金币
* @apiParam {int} specialFlag=0 特殊标记,例如0:默认、1:邀新好友、2:邀旧好友
* @apiParam {String} [title] 转发标题
* @apiParam {String} [imageUrl] 转发显示图片的链接
* @apiParam {String} [query] 必须是 key1=val1&key2=val2 的格式。
* @apiParam {callback} [success] 成功回调
* @apiParam {callback} [fail] 失败回调
*
* @apiSuccessExample {json} 示例:
* sdk.shareAppMessage({type: 1, query: "uid=520" });
*/
shareAppMessage(obj) {
var self = this;
//.默认1:普通分享
var tpye = 1;
var specialFlag = 0;
if (obj.type) {
tpye = obj.type;
}
if (obj.specialFlag) {
specialFlag = obj.specialFlag;
}
var shareInfo = this.getShareByWeight(tpye);
if (obj.title) {
shareInfo.title = obj.title;
}
if (obj.imageUrl) {
shareInfo.imageUrl = obj.imageUrl;
}
if (shareInfo.query) {
shareInfo.query += obj.query + "&share_id=" + shareInfo.sysid + "&uid=" + self.userid + "&special_flag=" + specialFlag;
} else {
if (obj.query) {
shareInfo.query = "share_id=" + shareInfo.sysid + "&uid=" + self.userid + "&special_flag=" + specialFlag + "&" + obj.query;
} else {
shareInfo.query = "share_id=" + shareInfo.sysid + "&uid=" + self.userid + "&special_flag=" + specialFlag;
}
}
if (obj.success) {
shareInfo.successCallback = obj.success;
}
if (obj.fail) {
shareInfo.failCallback = obj.fail;
}
console.log("sdk 微信分享", shareInfo);
if (true) {
wx.shareAppMessage(shareInfo);
var nowTime = new Date().getTime();
self.shareStartTime = nowTime / 1000;
self.shareInfo = shareInfo;
// var option = {'uid': sdk.userid, 'share_id': shareInfo.sysid };
// self.Get(self.ip3 + self.Logcommon, { log_type: "ShareClick", data: JSON.stringify(option) }, function (d) {
// });
}
},
/**
* @apiGroup C
* @apiName Get
* @api {Get} 发起网络请求 Get(发起Get请求)
*
* @apiParam {String} url 请求地址
* @apiParam {Object} reqData 请求参数
* @apiParam {Object} callback 不存在返回null
* @apiSuccessExample {json} 示例:
* sdk.Get("https://xxx.xxx", { user_id: user_id }, function (d) {
* console.log(d)
* });
*/
Get(url, reqData, callback) {
var self = this;
reqData.game = sdk_conf.game;
reqData.version = sdk_conf.version;
reqData.dev_platform = sdk_conf.dev_platform;
reqData.llewan_sdk_version = sdk_conf.llewan_sdk_version;
var ts = new Date().getTime();
reqData.ts = ts;
var token = "";
if (this.getUser()&&this.getUser()!=null) {
token = this.getUser().token;
}
var options = wx.getLaunchOptionsSync();
var source_id = options.query.source_id;
//数据验证签名。规则为:MD5(ts.substr(9,4)+game.substr(0,2)+version.substr(0,1)+key),时间戳后4位、data前3位、key(服务端提供)然后进行MD5加密
reqData.sign = md5(ts.toString().substr(9, 4) + sdk_conf.game.substr(0, 2) + sdk_conf.version.substr(0, 1) + sdk_conf.md5_key);
url += "?";
for (var item in reqData) {
url += item + "=" + reqData[item] + "&";
}
url += "token=" + token + "&";
url += "source_id=" + source_id + "&";
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function () {
if (xhr.readyState == 4) {
if (xhr.status >= 200 && xhr.status < 400) {
var response = xhr.responseText;
if (response) {
var responseJson = JSON.parse(response);
callback(responseJson);
} else {
if (self.debug) {
console.log("sdk 返回数据不存在", url)
}
callback(null);
}
} else {
if (self.debug) {
console.log("sdk 请求失败", url)
}
callback(null);
}
}
};
//console.log("get url is :",url);
xhr.open("GET", url, true);
xhr.send();
},
/**
* @apiGroup C
* @apiName Post
* @api {Post} 发起网络请求 Post(发起Post请求)
*
* @apiParam {String} url 请求地址
* @apiParam {Object} reqData 请求参数
* @apiParam {Object} callback 不存在返回null
* @apiSuccessExample {json} 示例:
* sdk.Post(sdk.ip + sdk.common, { user_id: user_id }, function (d) {
* console.log(d)
* });
*/
Post: function (url, reqData, callback) {
var self = this;
reqData.game = sdk_conf.game;
reqData.version = sdk_conf.version;
reqData.dev_platform = sdk_conf.dev_platform;
reqData.llewan_sdk_version = sdk_conf.llewan_sdk_version;
var ts = new Date().getTime();
var token = "";
if (this.getUser()&&this.getUser()!=null) {
token = this.getUser().token;
}
var options = wx.getLaunchOptionsSync();
var source_id = options.query.source_id;
reqData.ts = ts;
reqData.sign = md5(ts.toString().substr(9, 4) + sdk_conf.game.substr(0, 2) + sdk_conf.version.substr(0, 1) + sdk_conf.md5_key);
//1.拼接请求参数
var param = "";
for (var item in reqData) {
param += item + "=" + reqData[item] + "&";
}
param += "token=" + token + "&";
param += "source_id=" + source_id + "&";
//2.发起请求
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function () {
if (xhr.readyState == 4) {
if (xhr.status >= 200 && xhr.status < 400) {
var response = xhr.responseText;
// console.log(response)
if (response) {
var responseJson = JSON.parse(response);
callback(responseJson);
} else {
if (self.debug) {
console.log("sdk 返回数据不存在")
}
callback(null);
}
} else {
if (self.debug) {
console.log("sdk 请求失败", xhr)
}
callback(null);
}
}
};
xhr.open("POST", url, true);
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhr.send(param);//reqData为字符串形式: "key=value"
},
/**
* @apiGroup C
* @apiName checkUpdate
* @api {检测版本更新} 微信小游戏(冷启动的时候会检查,如果有更新则会重启小游戏进行更新) checkUpdate(版本更新)
*
* @apiSuccessExample {json} 示例:
* sdk.checkUpdate();
*/
checkUpdate() {
var self = this;
if (true && typeof wx.getUpdateManager === 'function') {
const updateManager = wx.getUpdateManager()
updateManager.onCheckForUpdate(function (res) {
if (self.debug) {
console.log("sdk 请求完新版本信息的回调", res.hasUpdate)
}
})
updateManager.onUpdateReady(function () {
if (self.debug) {
console.log("sdk 新的版本已经下载好,调用 applyUpdate 应用新版本并重启")
}
updateManager.applyUpdate()
})
updateManager.onUpdateFailed(function () {
if (self.debug) {
console.log("sdk 新的版本下载失败")
}
})
}
},
/**
* @apiGroup C
* @apiName getConfig1
* @api {运营配置} 游戏后台配置信息,运营人员使用的通用配置开关 getConfig1(运营配置)
* @apiParam {Object} callback 不存在返回null
*
* @apiSuccessExample {json} 示例:
* var d = sdk.getConfig1();
*/
getConfig1() {
return JSON.parse(this.ConfigData.config1);
},
/**
* @apiGroup C
* @apiName getConfig2
* @api {程序配置} 游戏后台配置信息,程序员使用的游戏数据开关,可随便自定义数据:例如复活次数等 getConfig2(程序配置)
* @apiParam {Object} callback 不存在返回null
*
* @apiSuccessExample {json} 示例:
* var d = sdk.getConfig2();
*/
getConfig2() {
return JSON.parse(this.ConfigData.config2);
},
/**
* @apiGroup C
* @apiName getConfig3
* @api {运营配置} 游戏后台配置信息,运营人员使用的通用配置开关 相关按钮根据时间来配置以及跳转方式按钮属性getConfig3(运营配置)
* @apiParam {Object} callback 不存在返回null
*
* @apiSuccessExample {json} 示例:
* var d = sdk.getConfig3();
*/
getConfig3() {
return JSON.parse(this.ConfigData.config3);
},
/**
* @apiGroup C
* @apiName getConfig4
* @api {技术程序控制} 游戏服务端控制一些需要服务端判断的比如:ip地区配置,getConfig4(技术程序)
* @apiParam {Object} callback 不存在返回null
*
* @apiSuccessExample {json} 示例:
* var d = sdk.getConfig4();
*/
getConfig4() {
return JSON.parse(this.ConfigData.config4);
},
/**
* @apiGroup C
* @apiName getUser
* @api {获取本地用户信息} 获取本地用户信息(登录成功后,会在本地存储用户信息) getUser(获取用户信息)
*
* @apiSuccessExample {json} 示例:
* //.不存在返回null
* var user = sdk.getUser();
*/
getUser() {
var userinfo = this.getItem('userinfo');
if (userinfo) {
return JSON.parse(userinfo);
} else {
return null;
}
},
/**
* @apiGroup C
* @apiName setItem
* @api {set} 数据存储 setItem(存)
* @apiParam {String} key 键
* @apiParam {String} value 值
*
* @apiSuccessExample {json} 示例:
* sdk.setItem("nick","hello")
*/
setItem(key, value) {
// wx.setStorage({
// key: key,
// data: value,
// })
Laya.LocalStorage.setItem(key,value);
// cc.sys.localStorage.setItem(key, value);
},
/**
* @apiGroup C
* @apiName getItem
* @api {数据存储} 数据存储 getItem(取)
* @apiParam {String} key 键
* @apiParam {String} value 值
*
* @apiSuccessExample {json} 示例:
* var nick = sdk.getItem("nick")
*/
getItem(key) {
return Laya.LocalStorage.getItem(key);
// return cc.sys.localStorage.getItem(key);
},
/**
* @apiGroup C
* @apiName removeItem
* @api {数据存储} 数据存储 removeItem(删)
* @apiParam {String} key 键
*
* @apiSuccessExample {json} 示例:
* sdk.removeItem("nick")
*/
removeItem(key) {
//cc.sys.localStorage.removeItem(key);
Laya.LocalStorage.removeItem(key, value);
},
/**
* @apiGroup C
* @apiName onMessage
* @api {主域监听子域发送的消息} 主域监听子域发送的消息 onMessage(监听消息)
* @apiParam {callback} callback 回调函数
*
* @apiSuccessExample {json} 示例:
* sdk.onMessage((d)=>{
* console.log(d)
* })
*/
onMessage(callback) {
if (true) {
wx.onMessage(function (d) {
// if(d.message == "common_back"){//.子域: 返回子域首页
// cc.director.loadScene("common_children")
// }
callback(d)
});
}
},
/**
* @apiGroup C
* @apiName postMessage
* @api {主域向子域发送消息} 主域向子域发送消息 postMessage(发送消息)
* @apiParam {String} msg 发送给子域的消息
*
* @apiSuccessExample {json} 示例:
* sdk.postMessage("hello")
*/
postMessage(msg) {
if (true) {
wx.postMessage({ message: msg });
}
},
//.主域上报数据: 对用户托管数据进行写数据操作,允许同时写多组 KV 数据。
setUserCloudStorage(kvDataList, callback) {
if (true) {
wx.setUserCloudStorage({
KVDataList: kvDataList,
success(res) {
callback(res)
},
fail(res) {
callback(res)
}
})
}
},
//.获取当前用户托管数据当中对应 key 的数据。该接口只可在开放数据域下使用
getUserCloudStorage(keyList, callback) {
if (true) {
wx.getUserCloudStorage({
keyList: keyList,
success(res) {
callback(res)
},
fail(res) {
callback(res)
}
})
}
},
//.在小游戏是通过群分享卡片打开的情况下,可以通过调用该接口获取群同玩成员的游戏数据。该接口只可在开放数据域下使用。
getGroupCloudStorage(shareTicket, keyList, callback) {
if (true) {
wx.getGroupCloudStorage({
shareTicket: shareTicket,
keyList: keyList,
success(res) {
callback(res)
},
fail(res) {
callback(res)
}
})
}
},
//.拉取当前用户所有同玩好友的托管数据。该接口只可在开放数据域下使用
getFriendCloudStorage(keyList, callback) {
if (true) {
wx.getFriendCloudStorage({
keyList: keyList,
success(res) {
callback(res)
},
fail(res) {
callback(res)
}
})
}
},
/**
* @apiGroup C
* @apiName sortList
* @api {对子域数据进行排序} 对子域数据进行排序 sortList(子域排序)
* @apiParam {String} ListData 要排序的微信子域数据
* @apiParam {String} field 排序字段
* @apiParam {String} order 正序:true ; 倒序:false
*
* @apiSuccessExample {json} 示例:
* wx.getFriendCloudStorage({
* keyList: ["score"],
* success(res){
* var ListData = sdk.sortList(res.data, 'score', true));
* console.log("=排序后的数据=", ListData);
* },
* fail(){
* console.log(res)
* }
*})
*/
sortList(ListData, field, order) {
ListData.sort(function (a, b) {
var AMaxScore = 0;
var KVDataList = a.KVDataList;
for (var i = 0; i < KVDataList.length; i++) {
if (KVDataList[i].key == field) {
AMaxScore = KVDataList[i].value;
}
}
var BMaxScore = 0;
KVDataList = b.KVDataList;
for (var i = 0; i < KVDataList.length; i++) {
if (KVDataList[i].key == field) {
BMaxScore = KVDataList[i].value;
}
}
if (order) {
return parseInt(AMaxScore) - parseInt(BMaxScore);
} else {
return parseInt(BMaxScore) - parseInt(AMaxScore);
}
});
return ListData;
},
/**
* @apiIgnore
* @apiGroup C
* @apiName getMyRank3
* @api {排名与我相邻的3位玩家信息} 排名与我相邻的3位玩家信息 getMyRank3(Top3)
* @apiParam {String} ListData 要排序的微信子域数据
* @apiParam {String} me 我的子域信息
*
* @apiSuccessExample {json} 示例:
* wx.getUserInfo({
* openIdList: ['selfOpenId'],
* lang: 'zh_CN',
* success(res){
* //.Top3
* var dList = sdk.getMyRank3(dataList,res.data[0]);
* console.log(dList)
* },
* fail(error) {
* console.log(error)
* }
* })
*
*
*/
getMyRank3(ListData, me) {
var dataList = [];
for (var i = 0; i < ListData.length; i++) {
if (ListData.length <= 3) {
//.只有3个人或以下
if (ListData[i].avatarUrl == me.avatarUrl && ListData[i].nickname == me.nickName) {
ListData[i].isSelf = true;//.标记自己
}
dataList = ListData;
for (var i = 0; i < dataList.length; i++) {
dataList[i].rank = i;
}
} else {
if (ListData[i].avatarUrl == me.avatarUrl && ListData[i].nickname == me.nickName) {
ListData[i].isSelf = true;//.标记自己
if (i == ListData.length - 1) {
//.自己分数最低
ListData[i].rank = i;
ListData[i - 1].rank = i - 1;
ListData[i - 2].rank = i - 2;
dataList.push(ListData[i - 2])
dataList.push(ListData[i - 1])
dataList.push(ListData[i])
} else if (i == 0) {
//.自己分数最高
ListData[i].rank = i;
ListData[i + 1].rank = i + 1;
ListData[i + 2].rank = i + 2;
dataList.push(ListData[i])
dataList.push(ListData[i + 1])
dataList.push(ListData[i + 2])
} else {
//.居中
ListData[i - 1].rank = i - 1;
ListData[i].rank = i;
ListData[i + 1].rank = i + 1;
dataList.push(ListData[i - 1])
dataList.push(ListData[i])
dataList.push(ListData[i + 1])
}
break;
}
}
}
return dataList;
},
createBannerAdByAdId(obj, bannerAdUnitId) {
var self = this;
if (true) {
if (this.BannerAd) {
return this.BannerAd;
} else {
if (!obj.style) {
obj.style = {};
var phone = wx.getSystemInfoSync();
this.w = phone.screenWidth / 2;
this.h = phone.screenHeight;
obj.style.left = 0;
obj.style.top = 0;
obj.style.width = 300;
}
this.BannerAd = wx.createBannerAd({
adUnitId: bannerAdUnitId,
style: obj.style,
})
this.BannerAd.onResize(function (res) {
console.log("sdk BannerAd广告缩放事件:", res)
self.BannerAd.style.left = self.w - self.BannerAd.style.realWidth / 2 + 0.1;
self.BannerAd.style.top = self.h - self.BannerAd.style.realHeight + 0.1;
});
this.BannerAd.onLoad(function (res) {
console.log("sdk BannerAd广告加载事件:", res)
});
this.BannerAd.onError(function (res) {
console.log("sdk BannerAd广告错误事件:", res)
});
return this.BannerAd;
}
}
},
/**
* @apiGroup C
* @apiName createBannerAd
* @api {微信登录} 创建banner广告组件 createBannerAd(广告)
* @apiParam {String} adUnitId 广告单元id
* @apiParam {String} style banner 广告组件的样式
*
* @apiSuccessExample {json} 示例:
* //.参考文档:https://developers.weixin.qq.com/minigame/dev/document/ad/wx.createBannerAd.html
* //var bannerAd = sdk.createBannerAd({
* // style:{
* // left: 0,
* // top: 0,
* // width: 100,
* // height: 200
* // }
* //});
*
* //.极简版(默认底部Banner)
* var bannerAd = sdk.createBannerAd({});
* bannerAd.show()
*
*/
createBannerAd(obj) {
var self = this;
if (true) {
if (this.BannerAd) {
return this.BannerAd;
} else {
if (!obj.style) {
obj.style = {};
var phone = wx.getSystemInfoSync();
this.w = phone.screenWidth / 2;
this.h = phone.screenHeight;
obj.style.left = 0;
obj.style.top = 0;
obj.style.width = 300;
}
this.BannerAd = wx.createBannerAd({
adUnitId: this.getConfig4().bannerAdUnitId,
style: obj.style,
})
this.BannerAd.onResize(function (res) {
console.log("sdk BannerAd广告缩放事件:", res)
self.BannerAd.style.left = self.w - self.BannerAd.style.realWidth / 2 + 0.1;
self.BannerAd.style.top = self.h - self.BannerAd.style.realHeight + 0.1;
});
this.BannerAd.onLoad(function (res) {
console.log("sdk BannerAd广告加载事件:", res)
});
this.BannerAd.onError(function (res) {
console.log("sdk BannerAd广告错误事件:", res)
});
return this.BannerAd;
}
}
},
/**
* @apiGroup C
* @apiName createRewardedVideoAd
* @api {微信登录} 创建banner广告组件 createRewardedVideoAd(广告)
* @apiParam {String} adUnitId 广告单元id
*
* @apiSuccessExample {json} 示例:
* //.参考文档:https://developers.weixin.qq.com/minigame/dev/document/ad/wx.createRewardedVideoAd.html
* sdk.videoSuccess = function(){
* //视频成功处理逻辑
* this.successFunction();
* };
* sdk.videoFail = function(){
* //视频失败处理逻辑
* this.failFunction();`
* };
* var videoAd = sdk.createRewardedVideoAd();
* videoAd.load().then(() => videoAd.show());
*
*/
createRewardedVideoAd() {
let self = this;
if (true) {
if (this.VideoAd) {
return this.VideoAd;
} else {
this.VideoAd = wx.createRewardedVideoAd({ adUnitId: this.getConfig4().videoAdUnitId })
this.VideoAd.onLoad(function (res) {
console.log("sdk VideoAd广告加载事件:", res)
});
var closeFun = function (res) {
// 用户点击了【关闭广告】按钮
// 小于 2.1.0 的基础库版本,res 是一个 undefined
if (res && res.isEnded || res === undefined) {
console.log("sdk 看视频成功");
self.videoSuccess();
} else {
console.error("sdk 看视频失败");
self.videoFail();
}
};
this.VideoAd.onClose(closeFun);
this.VideoAd.onError(function (res) {
//console.log("sdk VideoAd广告错误事件:", res)
wx.showToast({
title: '暂未开通,请谅解!',
icon: 'none'
});
});
return this.VideoAd;
}
}
},
/**
* @apiGroup C
* @apiName Screenshot
* @api {微信小游戏截图保存} 微信小游戏截图保存 Screenshot(截图)
*
* @apiSuccessExample {json} 示例:
* //.摄像机组件、回调
* sdk.Screenshot((d)=>{
* if(d){
* console.log("图片保存成功:", d)
* }else{
* console.log("图片保存失败:", d)
* }
* })
*
*/
Screenshot(callback) {
var self = this;
//1.判断是否授权
wx.getSetting({
success(res) {
// console.log("授权状态", res.authSetting['scope.writePhotosAlbum'])
if (res.authSetting['scope.writePhotosAlbum']) {
self.capture(callback);
} else {
// console.log("未授权", res)
wx.authorize({
scope: 'scope.writePhotosAlbum',
success(res2) {
// console.log("success res2",res2)
self.Screenshot(callback);
},
fail(res2) {
// console.log("重新授权")
wx.showModal({
title: '提示',
content: '请开启保存到相册功能',
showCancel: false,
success() {
wx.openSetting({
success(res3) {
// console.log("===重新授权===", res3)
if (res3.authSetting['scope.writePhotosAlbum']) {
self.Screenshot(callback);
} else {
wx.showToast({ title: "授权失败" })
callback(null)
}
}
})
}
})
}
})
}
},
fail() {
callback(null)
}
})
},
//.一般性存储到服务器数据方法,并且做了本地缓存
/**
* @apiGroup C
* @apiName setToServer
* @api {setToServer} 数据存储 setToServer(存)
* @apiParam {String} dataKey 键
* @apiParam {String} dataType 数据类型,首字母大学的驼峰形式,例如:ShareGroup 或者 ShareLimit
* @apiParam {String} data 需要保存的数据
* @apiParam {String} expireTime 过期时间 单位(秒),0:默认一天;-1:永不失效(10年);
*
* 注意:dataKey和dataType共同确定一个数据的key值,也就是说 如果同样传递key111但是如果dataType不一样,sdk会认为是不同的两个数据key
*
* var data = {'key3':'test'};
* sdk.setToServer("testKeyttt3","TestData",data,3600);
*
*/
setToServer: function (dataKey, dataType, data, expireTime) {
var self = this;
if (expireTime == -1) {
expireTime = 7 * 24 * 60 * 60;
} else if (expireTime == 0) {
expireTime = 24 * 60 * 60;
}
dataKey = sdk_conf.game + ":" + dataType + ":" + this.getUser().uid + ":" + dataKey;
self.setLocalCache(dataKey, JSON.stringify(data), expireTime);
console.log("sdk setToServer " + dataKey + " : " + JSON.stringify(data));
this.Get(this.ip2 + this.set, { key: dataKey, data: JSON.stringify(data), data_type: dataType, expireTime: String(expireTime) }, function (d) {
console.log("sdk setToServer 服务端返回", JSON.stringify(d));
if (d.c == 0) {
console.error("sdk 设置失败,请联系服务端技术查看问题!");
}
});
},
//.一般性获取服务器数据方法,并且做了本地缓存
/**
* @apiGroup C
* @apiName getFromServer
* @api {getFromServer} 数据存储 getFromServer(获取)
* @apiParam {String} dataKey 键
* @apiParam {String} dataType 数据类型 首字母大学的驼峰形式,例如:ShareGroup 或者 ShareLimit
* @apiParam {String} data 特殊情况下需要传递额外数据状况,一般不传递
* @apiParam {String} callback 回调
*
* sdk.getFromServer("testKey","TestData",null,(d)=>{
console.log("获取返回",d.key3);
});
*/
getFromServer: function (dataKey, dataType, data, callbackFunction) {
var self = this;
dataKey = sdk_conf.game + ":" + dataType + ":" + this.getUser().uid + ":" + dataKey;
var cacheData = this.getLocalCache(dataKey)
console.log("sdk getFromServer " + dataKey + " :" + cacheData);
if (cacheData == -1) {
//去远程服务器拿数据
this.Get(this.ip2 + this.get, { key: dataKey, data_type: dataType, data: JSON.stringify(data) }, function (d) {
console.log("sdk getFromServer " + dataKey + " 本地不存在,去服务器获取值:" + JSON.stringify(d.d));
callbackFunction(d.d);
});
} else if (cacheData == 0) {
//本地缓存过期了直接返回
//callbackFunction(null);
//去远程服务器拿数据
this.Get(this.ip2 + this.get, { key: dataKey, data_type: dataType, data: JSON.stringify(data) }, function (d) {
console.log("sdk getFromServer " + dataKey + " 本地已经过期,去服务器获取值:" + JSON.stringify(d.d));
callbackFunction(d.d);
});
} else {
//获取到数据
console.log("cacheData->" + cacheData);
try {
cacheData = JSON.parse(cacheData);
} catch (e) {
console.error("sdk json 转换异常");
}
callbackFunction(cacheData);
}
},
/**
* @apiGroup C
* @apiName setLocalCache
* @api {set} 数据存储 setLocalCache(存)
* @apiParam {String} key 键
* @apiParam {String} value 值
* @apiParam {String} expireTime 过期时间单位(秒)
*
* @apiSuccessExample {json} 示例:
* sdk.setLocalCache("nick","hello")
*/
setLocalCache(key, value, expireTime) {
var nowTime = new Date().getTime();
console.log("sdk setLocalCache nowTime", nowTime);
expireTime = nowTime + expireTime * 1000;
console.log("sdk setLocalCache expireTime", expireTime);
var localData = { 'data': value, 'expireTime': expireTime };
this.setItem(key, JSON.stringify(localData));
},
/**
* @apiGroup C
* @apiName getLocalCache
* @api {数据存储} 数据存储 getLocalCache(取)
* @apiParam {String} key 键
*
* @apiSuccessExample {json} 示例:
* var nick = sdk.getLocalCache("nick")
*/
getLocalCache(key) {
var nowTime = new Date().getTime();
console.log("sdk getLocalCache nowTime", nowTime);
var localData = this.getItem(key);
console.log("sdk getLocalCache " + key + " 本地获取值:" + localData);
if (localData) {
var data = JSON.parse(localData);
var expireTime = data.expireTime;
if (nowTime >= expireTime) {
this.removeItem(key);
console.log("sdk getLocalCache dataKey : " + key + " is expire");
return 0;
} else {
var data = data.data;
console.log("sdk getLocalCache dataKey : " + key + " is " + data);
return data;
}
} else {
//本地不存在数据,应该去远程服务器拿数据
return -1;
}
},
/**
* @apiGroup C
* @apiName getServerTime
* @api {数据存储} 数据获取 getServerTime (取)
* @apiSuccessExample {json} 示例:
* sdk.getServerTime((d)=>{
if(d.c==1){
console.log("获取返回",d.nowTime);
}
});
*/
getServerTime(callbackFunction) {
this.Post(this.ip2 + this.time, {}, function (d) {
callbackFunction(d);
});
},
/**
* @apiGroup C
* @apiName formatTime
* @api 数据获取 formatTime (取)
* @apiParam {Date} time 时间
* @apiParam {String} type 类型 date or time
* @apiParam {String} split 分隔符 / - : 空
* @apiSuccessExample {json} 示例:
* var time = this.formatTime(new Date(),"date",""); 20180920
* var time = this.formatTime(new Date(),"time",""); 20180920122324
*/
formatTime(time, type, split) {
var mat = {};
mat.M = time.getMonth() + 1;//月份记得加1
mat.H = time.getHours();
mat.s = time.getSeconds();
mat.m = time.getMinutes();
mat.Y = time.getFullYear();
mat.D = time.getDate();
mat.d = time.getDay();//星期几
mat.d = this.formatZero(mat.d);
mat.H = this.formatZero(mat.H);
mat.M = this.formatZero(mat.M);
mat.D = this.formatZero(mat.D);
mat.s = this.formatZero(mat.s);
mat.m = this.formatZero(mat.m);
if (type == "date") {
if (split.indexOf(":") > -1) {
mat.Y = mat.Y.toString().substr(2, 2);
return mat.Y + "/" + mat.M + "/" + mat.D
} else if (split.indexOf("/") > -1) {
return mat.Y + "/" + mat.M + "/" + mat.D
} else if (split.indexOf("-") > -1) {
return mat.Y + "-" + mat.M + "-" + mat.D
} else if (split.indexOf("-") > -1) {
return mat.Y + "-" + mat.M + "-" + mat.D
} else {
return mat.Y + mat.M + mat.D
}
} else {
if (split.indexOf(":") > -1) {
mat.Y = mat.Y.toString().substr(2, 2);
return mat.Y + "/" + mat.M + "/" + mat.D + " " + mat.H + ":" + mat.m + ":" + mat.s;
} else if (split.indexOf("/") > -1) {
return mat.Y + "/" + mat.M + "/" + mat.D + " " + mat.H + "/" + mat.m + "/" + mat.s;
} else if (split.indexOf("-") > -1) {
return mat.Y + "-" + mat.M + "-" + mat.D + " " + mat.H + "-" + mat.m + "-" + mat.s;
} else if (split.indexOf("-") > -1) {
return mat.Y + "-" + mat.M + "-" + mat.D + " " + mat.H + "-" + mat.m + "-" + mat.s;
} else {
return mat.Y + mat.M + mat.D + mat.H + mat.m + mat.s;
}
}
},
formatZero(str) {
str = str.toString();
if (str.length < 2) {
str = '0' + str;
}
return str;
},
getUploadRowCount() {
var res = sdk_conf.default_upload_row_count;
try {
res = this.getConfig4().uploadRowCount;
if (!res) {
res = sdk_conf.default_upload_row_count;
}
} catch (e) {
res = sdk_conf.default_upload_row_count;
}
return res;
},
getUploadInterval() {
var res = sdk_conf.default_upload_interval;
try {
res = this.getConfig4().uploadInterval;
if (!res) {
res = sdk_conf.default_upload_interval;
}
} catch (e) {
res = sdk_conf.default_upload_interval;
}
return res;
},
/**
* @apiGroup C
* @apiName uploadSceneEvent
* @api {数据存储} 数据存储 uploadSceneEvent(存) 将事件信息发送到乐玩服务器记录
* @apiParam {JsonArray} eventJsonArray 要上传的json数组
* sdk.uploadSceneEvent(null,'游戏结束',null) //游戏上传场景数据
* sdk.uploadSceneEvent(jsonArray,'',null) //将要上传的数据传递过来
*/
uploadSceneEvent(eventJsonArray, uploadEvent, callbackFunction) {
var lastUploadDataTime = this.getItem("lastUploadDataTime");
var nowTime = new Date().getTime() / 1000;
console.log("nowTime:" + nowTime + ";lastUploadDataTime:" + lastUploadDataTime);
if (lastUploadDataTime) {
//存在更新时间 暂不做任何处理
} else {
//上次更新时间没有就等于当前时间
lastUploadDataTime = nowTime;
this.setItem("lastUploadDataTime", lastUploadDataTime);
}
if (eventJsonArray === null) {
//如果没有传递要上传的数据
var eventData = this.getItem("eventData");
try {
eventJsonArray = JSON.parse(eventData);
console.log(uploadEvent);
this.uploadData(eventJsonArray, uploadEvent, callbackFunction);
} catch (e) {
console.error("埋点没有数据上传!");
}
} else if (eventJsonArray.data.length >= this.getUploadRowCount()) {
uploadEvent = "数据累计(" + this.getUploadRowCount() + "条)上传";
console.log(uploadEvent);
this.uploadData(eventJsonArray, uploadEvent, callbackFunction);
} else if ((nowTime - lastUploadDataTime) >= this.getUploadInterval()) {
uploadEvent = "定时(" + this.getUploadInterval() + "秒)上传";
console.log(uploadEvent);
this.uploadData(eventJsonArray, uploadEvent, callbackFunction);
}
},
uploadData(eventJsonArray, uploadEvent, callbackFunction) {
var nowTime = new Date().getTime() / 1000;
eventJsonArray.upload_event = uploadEvent;
//达到一定数量级
console.log("当前上传数据", eventJsonArray);
this.Post(this.ip3 + this.Logcommon, { log_type: "SceneEventLog", data: JSON.stringify(eventJsonArray) }, function (d) {
if (callbackFunction) {
callbackFunction(d);
}
});
//上传完了之后删除数据
this.removeItem("eventData");
this.setItem("lastUploadDataTime", nowTime);
},
/**
* @apiGroup C
* @apiName setSceneEvent
* @api {数据存储} 数据存储 setEvent(存) 将事件信息发送到乐玩服务器记录
* @apiParam {String} sceneName 场景名称,比如:第1关,第2关,厨房,矿坑
* @apiParam {String} eventName 事件名称,比如:点击、加载、触摸、移动
* @apiParam {String} eventId 事件ID 通常谢按钮的英文或者中文名字,比如:首页-开始闯关
* @apiParam {JSON} params 参数相关
* @apiSuccessExample {json} 示例:
* sdk.setSceneEvent("第一关","点击","首页-开始闯关",{'uid':'8975621'},null)
*/
setSceneEvent(sceneName, eventName, eventId, params, callbackFunction) {
var eventData = this.getItem("eventData");
var deviceModel = this.getItem('deviceModel');
var eventJsonArray = {};
var data = [];
var insertData = {};
if (eventData) {
eventJsonArray = JSON.parse(eventData);
data = eventJsonArray.data;
//console.log("已经存在:"+data);
}
var uid = -1;
try {
uid = this.getUser().uid;
} catch (e) {
uid = -1;
}
insertData.uid = uid;
insertData.scene_name = sceneName;
insertData.event_id = eventId;
insertData.event_name = eventName;
insertData.params = JSON.stringify(params);
insertData.device_model = deviceModel;
insertData.event_time = this.formatTime(new Date(), "time", "-")
//console.log("添加数据",JSON.stringify(insertData));
data.push(insertData);
eventJsonArray.data = data;
//console.log("添加后:"+JSON.stringify(eventJsonArray.data));
this.setItem("eventData", JSON.stringify(eventJsonArray));
this.uploadSceneEvent(eventJsonArray, '', callbackFunction);
},
/**
* @apiGroup C
* @apiName setScore
* @api {数据存储} 数据存储 setScore(存) 将玩家分数保存到服务器,服务器会进行分数判断,每个用户每天只会有一个最高分数保存
* @apiParam {int} score 玩家分数,游戏最好自己判断一下是否是【当天】最高分数
* @apiSuccessExample {json} 示例:
* sdk.setScore(10,null)
*/
setScore(score, callbackFunction) {
var data = {};
data.uid = this.getUser().uid;
data.score = score;
this.Post(this.ip3 + this.Logcommon, { log_type: "ScoreLog", data: JSON.stringify(data) }, function (d) {
if (callbackFunction) {
callbackFunction(d);
}
});
},
/**
* @apiGroup C
* @apiName setOnline
* @api {数据存储} 数据存储 setOnline(存) 将玩家在线通知服务端记录
* @apiParam {int} regularTime 时间参数,一般值定时每次调用时间间隔
* @apiParam {int} end是否结束,1:表示为最后一次后面不在调用一般用户离开程序时候调用,0:表示不是。一般都是用传递0,
* @apiSuccessExample {json} 示例:
* sdk.setOnline(10,null)
*/
setOnline(regularTime, end, callbackFunction) {
var data = {};
data.uid = this.getUser().uid;
data.regular_time = regularTime;
data.end = end;
this.Post(this.ip3 + this.Logcommon, { log_type: "OnlineLog", data: JSON.stringify(data) }, function (d) {
if (callbackFunction) {
callbackFunction(d);
}
});
},
/**
* @apiGroup C
* @apiName sceneStart
* @api {数据存储} 数据存储 sceneStart(存) 玩家进场景界面开始调用
* @apiParam {String} sceneName 场景名称,比如:第1关,第2关,厨房,矿坑,如果有调用setSceneEvent 两个传递场景名称必须要一样
* @apiParam {JSON} extraData 额外数据,可以传递从哪里进入场景,比如:正常进入 或者 奖励进入
* @apiSuccessExample {json} 示例:
* sdk.sceneStart('第1关','正常进入',null)
*/
setSceneStart(sceneName, params) {
if (sceneName == this.gameOnlineKey) {
var cacheData = this.getItem(sceneName);
var nowTime = new Date().getTime();
var data = {};
if (cacheData) {
data = JSON.parse(cacheData);
data.last_time = nowTime / 1000;
console.log(this.gameOnlineKey, JSON.stringify(data));
this.setItem(sceneName, JSON.stringify(data));
} else {
var deviceModel = this.getItem('deviceModel');
data.uid = this.getUser().uid;
data.scene_name = sceneName;
data.start_time = nowTime / 1000;
data.last_time = nowTime / 1000;
data.take_time = 0;
data.end_time = nowTime / 1000;
data.params = JSON.stringify(params);
data.device_model = deviceModel;
console.log(this.gameOnlineKey, JSON.stringify(data));
this.setItem(sceneName, JSON.stringify(data));
}
} else {
var nowTime = new Date().getTime();
var deviceModel = this.getItem('deviceModel');
var data = {};
data.uid = this.getUser().uid;
data.scene_name = sceneName;
data.start_time = nowTime / 1000;
data.last_time = nowTime / 1000;
data.take_time = 0;
data.end_time = nowTime / 1000;
data.params = JSON.stringify(params);
data.device_model = deviceModel;
console.log("场景数据开始", JSON.stringify(data));
this.setItem(sceneName, JSON.stringify(data));
}
},
/**
* @apiGroup C
* @apiName sceneEnd
* @api {数据存储} 数据存储 sceneEnd(存) 玩家结束游戏场景调用
* @apiParam {String} sceneName 场景名称,比如:第1关,第2关,厨房,矿坑,如果有调用setSceneEvent 两个传递场景名称必须要一样
* @apiParam {JSON} extraData 额外数据,如果是正常结束可以传递 从哪里退出的场景,比如:正常退出 或者 返回按钮退出
* @apiSuccessExample {json} 示例:
* sdk.sceneEnd('第1关','返回按钮退出',(d)=>{
* console.log("场景回调",d);
*})
*/
setSceneEnd(sceneName, params, callbackFunction) {
var data = this.getItem(sceneName);
console.log("场景数据结束", data);
var nowTime = new Date().getTime();
if (data) {
data = JSON.parse(data);
data.end_time = nowTime / 1000;
data.take_time = data.take_time + ((nowTime / 1000) - data.last_time);
if (sceneName == this.gameOnlineKey) {
data.last_time = nowTime / 1000;
this.setItem(sceneName, JSON.stringify(data));
console.log("setSceneEnd->场景数据结束", JSON.stringify(data));
}
this.Post(this.ip3 + this.Logcommon, { log_type: "SceneLog", data: JSON.stringify(data) }, function (d) {
if (callbackFunction) {
callbackFunction(d);
}
});
}
},
/**
* @apiGroup C
* @apiName gameStart
* @api {数据存储} 数据存储 gameStart(存) 玩家进入游戏界面开始调用
* @apiParam {JSON} params 额外数据
* @apiSuccessExample {json} 示例:
* sdk.gameStart({},null)
*/
gameStart(params, callbackFunction) {
if (sdk_conf.game_online) {
this.setSceneStart(this.getGameOnlineKey(), params);
this.isGameStart = true;
} else {
console.error("您没有打开游戏在线时长统计");
}
// var nowTime = new Date().getTime();
// var data = JSON.parse(this.getItem("游戏在线"));
// data.last_time = nowTime/1000;
// this.setItem("游戏在线",JSON.stringify(data));
},
getGameOnlineKey() {
if (sdk_conf.game_online) {
if (this.gameOnlineKey == '游戏在线') {
//如果当前是默认游戏在线名称
this.gameOnlineKey = this.gameOnlineKey + this.formatTime(new Date(), "date", "");
} else {
//已经生成了游戏在线key
var nowGameKey = '游戏在线' + this.formatTime(new Date(), "date", "");
if (this.gameOnlineKey == nowGameKey) {
//如果还在当天之内
} else {
//如果已经过了一天了,做最后一次数据上传
this.setSceneEnd(this.gameOnlineKey, {});
//修改当前在线的key
this.gameOnlineKey = nowGameKey;
//并且开始新的游戏开始
this.setSceneStart(this.gameOnlineKey, {});
}
}
return this.gameOnlineKey;
} else {
console.error("您没有打开游戏在线时长统计");
}
},
/**
* @apiGroup C
* @apiName gameOver
* @api {数据存储} 数据存储 gameOver(存) 玩家结束游戏调用
* @apiParam {JSON} params 额外数据
* @apiSuccessExample {json} 示例:
* sdk.gameOver({},null)
*/
gameOver(params, callbackFunction) {
if (sdk_conf.game_online) {
this.setSceneEnd(this.getGameOnlineKey(), params);
} else {
console.error("您没有打开游戏在线时长统计");
}
},
/**
* @apiGroup C
* @apiName getButtonConfig
* @api {数据存储} 数据存储 getButtonConfig(取)
* @apiParam {String} buttonKey 按钮的键值 比如 hz2 hz3
*
* @apiSuccessExample {json} 示例:
* var d = sdk.getButtonConfig("hz2");
* 特别说明:对于视频分享切换的解析返回的json为:
* {"type":"share","count":5,"left_count":3,"use_count":2,"next":"key_1"}
* 技术获取之后根据d.type判断类型然后做响应处理就可以了;
*
*
*/
getButtonConfig(buttonKey) {
return this.getButtonConfig2(buttonKey, 1);
},
/**
* @apiGroup C
* @apiName getButtonConfig
* @api {数据存储} 数据存储 getButtonConfig(取)
* @apiParam {String} buttonKey 按钮的键值 比如 hz2 hz3
* @apiParam {int} isCount 值为1或者0 1:表示本次调用使用次数加一;0:表示本次调用使用次数不发生变化
*
* @apiSuccessExample {json} 示例:
* var d = sdk.getButtonConfig("hz2");
* 特别说明:对于视频分享切换的解析返回的json为:
* {"type":"share","count":5,"left_count":3,"use_count":2,"next":"key_1"}
* 技术获取之后根据d.type判断类型然后做响应处理就可以了;
*
*
*/
getButtonConfig2(buttonKey, isCount) {
var c3 = this.getConfig3();
if (c3.length > 0) {
for (var i = 0; i < c3.length; i++) {
var c = c3[i];
if (c.key === buttonKey) {
var dl = c.date_list;
for (var i = 0; i < dl.length; i++) {
var d = dl[i];
var nowTime = new Date().getTime();
var date = this.formatTime(new Date(), "date", "");
if (nowTime >= d.s_time && nowTime <= d.e_time) {
if (c.type === 'mix') {
var countKey = buttonKey + ":" + date + ":" + i + ":count";
var count = this.getItem(countKey);
console.log(buttonKey + "->" + countKey, count);
if (!count) {
count = 1;
}
var startKey = buttonKey + ":" + date + ":" + i + ":start:" + d.data.start.type + ":" + count;
var startVal = this.getItem(startKey);
console.log(buttonKey + "->" + startKey, startVal);
if (!startVal) {
startVal = 0;
}
if (startVal >= d.data.start.count) {
return this.nextConfig(buttonKey, date, d.data, d.data.start.next, i, count, isCount);
} else {
//当前记录的次数小于配置次数
if (isCount == 1) {
startVal++;
this.setItem(startKey, startVal);
d.data.start.left_count = d.data.start.count - startVal;
d.data.start.use_count = startVal;
}
return d.data.start;
}
} else {
return d;
}
}
}
}
}
return null;
} else {
return null;
}
},
nextConfig(buttonKey, date, data, nextKey, i, count, isCount) {
if (nextKey == 'end') {
return null;
}
var nextCacheKey = buttonKey + ":" + date + ":" + i + ":" + nextKey + ":" + data[nextKey].type + ":" + count;
var nextCacheVal = this.getItem(nextCacheKey);
console.log("nextConfig->" + nextCacheKey, nextCacheVal);
if (!nextCacheVal) {
nextCacheVal = 1;
} else {
nextCacheVal = nextCacheVal + 1;
}
//计数的话
if (isCount == 1) {
this.setItem(nextCacheKey, nextCacheVal);
}
if (nextCacheVal >= data[nextKey].count) {
//当前缓存中的记录当前key的次数已经超过配置次数
if (data[nextKey].next == 'start') {
var countKey = buttonKey + ":" + date + ":" + i + ":count";
count = count + 1;
this.setItem(countKey, count);
}
//往下递归
return this.nextConfig(buttonKey, date, data, data[nextKey].next, i, count, isCount);
} else {
//计数的话
if (isCount == 1) {
data[nextKey].left_count = data[nextKey].count - nextCacheVal;
data[nextKey].use_count = nextCacheVal;
}
return data[nextKey];
}
},
/**
* @apiGroup C
* @apiName navigateToMiniProgram
* @api 跳转到小程序或者小游戏注意有时间限定 navigateToMiniProgram
* @apiParam {json} config json包含app_id,path,extraData,env_version
* @apiParam {fucntion} success 成功返回
* @apiParam {fucntion} fail 失败返回
* @apiParam {fucntion} complete 完成返回
*
* @apiSuccessExample {json} 示例:
* var d = sdk.getButtonConfig('hz2');
* sdk.navigateToMiniProgram(d);
*/
navigateToMiniProgram(config, success, fail, complete) {
//var nowTime =new Date().getTime();
//if(nowTime >=config.s_time && nowTime <=config.e_time)
//{
wx.navigateToMiniProgram({
appId: config.app_id, // 要打开的小程序appId
path: config.path, // 打开的页面路径,如果为空则打开首页
extraData: config.extra, // 需要传递给目标小程序的数据
envVersion: config.env_version, //特殊情况下需要跳转到对应小程序的开发版本
success: success,
fail: fail,
complete: complete,
});
//}
},
};
module.exports = sdk;
// window.sdk = sdk;
{
"ver": "1.0.5",
"uuid": "0599a0fa-1702-49cc-a866-f63749f89c28",
"isPlugin": false,
"loadPluginInWeb": true,
"loadPluginInNative": true,
"loadPluginInEditor": false,
"subMetas": {}
}
\ No newline at end of file
var sdk_conf = {
//.开发调试环境:prod 或 test,env_apis配合使用,主要是将接口切换正式环境和测试环境,上线务必修改为:prod
env:'prod',
//.游戏唯一标识:由游戏技术修改
game: 'jinjibazuqiu-weixin',
//.当前游戏版本:由游戏技术修改
version: '1.0.0',
//以下广告ID获取已经废弃,改成从服务端配置config4中获取
//.banner广告单元id
//bannerAdUnitId: '',
//.video广告单元id
//videoAdUnitId: '',
//.开发平台:由sdk维护者确定,weixin 或 toutiao,接入游戏的技术不需要修改
dev_platform: 'weixin',
//.乐玩sdk的版本号:由sdk维护者确定,接入游戏的技术不需要修改
llewan_sdk_version:'1.103',
//.接口加密key,切勿修改
md5_key: '$5dfjr$%dsadsfdsii',
//相关api配置,由sdk维护者确定,接入游戏的技术不需要修改
env_apis:{
prod:{
ip1: "https://login.llewan.com:1799",
ip2: "https://game.llewan.com:1899",
ip3: "https://log.llewan.com:1999",
ip4: "https://res.llewan.com:2099",
},
test:{
ip1: "https://login.test.llewan.com",
ip2: "https://game.test.llewan.com",
ip3: "https://log.test.llewan.com",
ip4: "https://res.test.llewan.com",
}
},
default_upload_row_count:20,
default_upload_interval:120,
//游戏在线统计时长开启与关闭。true为开启,false为关闭
game_online:true,
//分享调起时间设置
share_time_limit:2,
};
module.exports = sdk_conf;
var sdk_conf = {
//.开发调试环境:prod 或 test,env_apis配合使用,主要是将接口切换正式环境和测试环境,上线务必修改为:prod
env:'prod',
//.游戏唯一标识:由游戏技术修改
game: 'jinjibazuqiu-weixin',
//.当前游戏版本:由游戏技术修改
version: '1.2.5',
//以下广告ID获取已经废弃,改成从服务端配置config4中获取
//.banner广告单元id
//bannerAdUnitId: '',
//.video广告单元id
//videoAdUnitId: '',
//.开发平台:由sdk维护者确定,weixin 或 toutiao,接入游戏的技术不需要修改
dev_platform: 'weixin',
//.乐玩sdk的版本号:由sdk维护者确定,接入游戏的技术不需要修改
llewan_sdk_version:'1.009',
//.接口加密key,切勿修改
md5_key: '$5dfjr$%dsadsfdsii',
//相关api配置,由sdk维护者确定,接入游戏的技术不需要修改
env_apis:{
prod:{
ip1: "https://login.llewan.com:1799",
ip2: "https://game.llewan.com:1899",
ip3: "https://log.llewan.com:1999",
ip4: "https://res.llewan.com:2099",
},
test:{
ip1: "https://login.test.llewan.com",
ip2: "https://game.test.llewan.com",
ip3: "https://log.test.llewan.com",
ip4: "https://res.test.llewan.com",
}
},
default_upload_row_count:20,
default_upload_interval:120,
//游戏在线统计时长开启与关闭。true为开启,false为关闭
game_online:true,
//分享调起时间设置
share_time_limit:2,
};
module.exports = sdk_conf;
{
"ver": "1.0.0",
"uuid": "803feea7-b90b-4f4d-b29b-7b46d0ab006a",
"subMetas": {}
}
\ No newline at end of file
{
"ver": "1.0.5",
"uuid": "7c8ef11c-1c9e-45dc-ae6b-815921116c50",
"isPlugin": false,
"loadPluginInWeb": true,
"loadPluginInNative": true,
"loadPluginInEditor": false,
"subMetas": {}
}
\ No newline at end of file
This source diff could not be displayed because it is too large. You can view the blob instead.
{
"compilerOptions": {
"target": "es6",
"module": "commonjs",
"experimentalDecorators": true
},
"exclude": [
"node_modules",
".vscode",
"library",
"local",
"settings",
"temp"
]
}
\ No newline at end of file
{
"engine": "cocos-creator-js",
"packages": "packages"
}
\ No newline at end of file
{
"start-scene": "current",
"group-list": [
"default"
],
"collision-matrix": [
[
true
]
],
"excluded-modules": [],
"design-resolution-width": 960,
"design-resolution-height": 640,
"fit-width": false,
"fit-height": true,
"use-project-simulator-setting": false,
"simulator-orientation": false,
"use-customize-simulator": false,
"simulator-resolution": {
"width": 960,
"height": 640
},
"cocos-analytics": {
"enable": false,
"appID": "13798",
"appSecret": "959b3ac0037d0f3c2fdce94f8421a9b2"
}
}
\ No newline at end of file
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment