提交 85ec828e 作者: wangjin

优化用户授权

上级 29608894
/** /**
* 鲸鱼游戏微信小游戏接入库 * 鲸鱼游戏微信小游戏接入库
* @author 推广技术部 * @author 推广技术部
* @time: 2021-04-28 * @time: 2021-10-11
* *
* 1.优化用户授权 * 1.优化用户授权
* *
*/ */
class WechatSDK { class WechatSDK {
private sdkVersion: string = '3.0.5' private sdkVersion: string = "3.0.6";
public LaunchOptions: Object; // 启动参数对象 public LaunchOptions: Object; // 启动参数对象
public SystemInfo: Object; // 设备信息 public SystemInfo: Object; // 设备信息
public LoginData: Object; // 登录信息 public LoginData: Object; // 登录信息
private onlineTime: number = 0; // 在线时长(单位:分钟) private onlineTime: number = 0; // 在线时长(单位:分钟)
private actId: string = '' // 动态消息活动id private actId: string = ""; // 动态消息活动id
private clickCounter = 0 // 当前用户点击次数 private clickCounter = 0; // 当前用户点击次数
private GameRecorder: any = null // 录屏对象 private GameRecorder: any = null; // 录屏对象
private recorderBtn: any = null // 对局回放分享按钮对象 private recorderBtn: any = null; // 对局回放分享按钮对象
constructor() { constructor() {
console.log('当前加载SDK版本号为:', this.sdkVersion); console.log("当前加载SDK版本号为:", this.sdkVersion);
this.sdkInit(); this.sdkInit();
this.timerInit(); this.timerInit();
} }
private timerInit() { // 用户在线时间 private timerInit() {
let loginTime = new Date().getTime(); // 登录时间 // 用户在线时间
let offTime = (wx as any).getStorageSync('offlineTime'); // 离线前记录的时间点 let loginTime = new Date().getTime(); // 登录时间
let offlineTime = offTime ? ((loginTime - offTime) / (1000 * 60)).toFixed(2) : 0; // 离线时长(分钟) let offTime = (wx as any).getStorageSync("offlineTime"); // 离线前记录的时间点
if (offlineTime > 299) this.onlineTime = 0; let offlineTime = offTime ? ((loginTime - offTime) / (1000 * 60)).toFixed(2) : 0; // 离线时长(分钟)
else this.onlineTime = (wx as any).getStorageSync('onlineMinute') || 0; if (offlineTime > 299) this.onlineTime = 0;
setInterval(() => { // 每分钟记录一次 else this.onlineTime = (wx as any).getStorageSync("onlineMinute") || 0;
this.onlineTime++; setInterval(() => {
let curTime = new Date().getTime(); // 每分钟记录一次
(wx as any).setStorageSync("onlineMinute", this.onlineTime); this.onlineTime++;
(wx as any).setStorageSync("offlineTime", curTime); let curTime = new Date().getTime();
}, 60000); (wx as any).setStorageSync("onlineMinute", this.onlineTime);
} (wx as any).setStorageSync("offlineTime", curTime);
private sdkInit = async () => { }, 60000);
this.LaunchOptions = await this.getOptionsInfo(); }
this.actId = this.LaunchOptions['actId'] || ''; private sdkInit = async () => {
this.SystemInfo = await this.getSystemInfo(); this.LaunchOptions = await this.getOptionsInfo();
this.SystemInfo['networkType'] = await this.getNetworkType(); this.actId = this.LaunchOptions["actId"] || "";
this.SDKCOMMDATA['os'] = this.SystemInfo['system'].split(' ')[0].toLowerCase(); this.SystemInfo = await this.getSystemInfo();
} this.SystemInfo["networkType"] = await this.getNetworkType();
public Login = async (retry = 0) => { this.SDKCOMMDATA["os"] = this.SystemInfo["system"].split(" ")[0].toLowerCase();
if (retry > 2) { };
this.showMsg('登录异常,请联系客服.'); public Login = async (retry = 0) => {
return { error: "登录超时.." } if (retry > 2) {
} this.showMsg("登录异常,请联系客服.");
const res = await this.getWechatCode(); // 获取微信登录code return { error: "登录超时.." };
if (res.code) { }
// 请求openid const res = await this.getWechatCode(); // 获取微信登录code
const { data } = await this.sdkRequest(Links.init, { if (res.code) {
...this.SDKCOMMDATA, // 请求openid
appid: SDKConfig.appid, const { data } = await this.sdkRequest(Links.init, {
code: res.code ...this.SDKCOMMDATA,
}); appid: SDKConfig.appid,
this.LoginData = { ...data } code: res.code,
this.SDKCOMMDATA['uuid'] = data.open_id; });
// SDK后台调试模式开关 this.LoginData = { ...data };
if (typeof (data.debug_mode) != "undefined" && data.debug_mode == 1) { this.SDKCOMMDATA["uuid"] = data.open_id;
(wx as any).setEnableDebug({ // SDK后台调试模式开关
enableDebug: true if (typeof data.debug_mode != "undefined" && data.debug_mode == 1) {
}) (wx as any).setEnableDebug({
} enableDebug: true,
this.actId != "" && this.updateShareMsgInfo({}); });
return this.sdkActive(); }
} this.actId != "" && this.updateShareMsgInfo({});
retry += 1; return this.sdkActive();
this.Login(retry); }
} retry += 1;
// SDK激活 this.Login(retry);
private sdkActive = async () => { };
const { data } = await this.sdkRequest(Links.active, { ...this.SDKCOMMDATA, ...this.LoginData }); // SDK激活
this.LoginData['pay_channel'] = data.default_pay_channel; private sdkActive = async () => {
this.ActiReport(); // 上报激活 const { data } = await this.sdkRequest(Links.active, { ...this.SDKCOMMDATA, ...this.LoginData });
return this.sdkLogin(); this.LoginData["pay_channel"] = data.default_pay_channel;
} this.ActiReport(); // 上报激活
private async sdkLogin() { return this.sdkLogin();
delete this.LoginData['token']; // 强制清空登录toekn };
const { data, msg } = await this.sdkRequest(Links.login, { ...this.SDKCOMMDATA, ...this.LoginData }); private async sdkLogin() {
console.log("--SDK登录返回::", data); delete this.LoginData["token"]; // 强制清空登录toekn
if (Object.keys(data).length == 0) { const { data, msg } = await this.sdkRequest(Links.login, { ...this.SDKCOMMDATA, ...this.LoginData });
this.showMsg(msg); console.log("--SDK登录返回::", data);
return { error: msg } if (Object.keys(data).length == 0) {
} this.showMsg(msg);
this.LoginData = { ...this.LoginData, ...data } return { error: msg };
const filters = (({create_time, ip, nickname, open_id, uid, enter_game, origin_uid, origin_open_id}) => ({ create_time, ip, nickname, open_id, uid, enter_game, origin_uid, origin_open_id }))(data); }
return { this.LoginData = { ...this.LoginData, ...data };
...filters, const filters = (({ create_time, ip, nickname, open_id, uid, enter_game, origin_uid, origin_open_id }) => ({
os: this.SDKCOMMDATA['os'], // 返回系统类型IOS或者android create_time,
session_key: this.LoginData['session_key'], // 返回session_key ip,
scene: this.LaunchOptions['scene'], // 用户来源场景值 nickname,
from_appid: this.LaunchOptions['appId'] || this.LaunchOptions['appid'], open_id,
launchOptions: this.LaunchOptions uid,
} enter_game,
} origin_uid,
public payOrder = async (Params, showMessage = true) => { origin_open_id,
this.showLoading(); }))(data);
// 支付前先获取用户订单状态,如果没有未完成订单则继续支付 return {
const { code, data, msg } = await this.fetchUri(Links.order, this.md5_sign({ ...this.SDKCOMMDATA, ...Params, token: this.LoginData['token'], pay_channel: this.LoginData['pay_channel'] }), 'GET'); ...filters,
this.hideLoading(); os: this.SDKCOMMDATA["os"], // 返回系统类型IOS或者android
if (code == 0 && data.open_customer_service) { session_key: this.LoginData["session_key"], // 返回session_key
const params = { scene: this.LaunchOptions["scene"], // 用户来源场景值
title: '充值教程', from_appid: this.LaunchOptions["appId"] || this.LaunchOptions["appid"],
content: '即将跳转官方【客服会话】进行充值, 向客服回复【充值】获取充值链接', launchOptions: this.LaunchOptions,
showCancel: false, };
success: () => { }
this.Customer({ public payOrder = async (Params, showMessage = true) => {
sessionFrom: 'order_id=' + (data.order_num || '') + '&payload=' + (data.payload || ''), this.showLoading();
showMessageCard: true, // 支付前先获取用户订单状态,如果没有未完成订单则继续支付
sendMessageTitle: '回复【充值】获取充值链接', const { code, data, msg } = await this.fetchUri(
sendMessageImg: 'https://h5sdk.pthc8.com/resource/images/payTips.jpg', Links.order,
}); this.md5_sign({ ...this.SDKCOMMDATA, ...Params, token: this.LoginData["token"], pay_channel: this.LoginData["pay_channel"] }),
} "GET"
} );
this.showModal(params); this.hideLoading();
return { order_code: 2, msg: '' }; if (code == 0 && data.weixin_mini_program_app_id) {
} const params = {
if (code == 0 && data.order_type == 1) { // 跳转参数
this.MidasPaymentParams['buyQuantity'] = <number>(Params.money / 100) * <number>data.weixin_proportion // 充值金额 appId: data.weixin_mini_program_app_id, // 跳转的小程序appid
console.log("--米大师支付参数:", this.MidasPaymentParams); path: "", // 跳转到首页
// 调微信米大师支付接口 envVersion: SDKConfig.navPayEnv, //跳转方式
return new Promise((resolve, reject) => { extraData: {
(wx as any).requestMidasPayment({ ...this.SDKCOMMDATA,
...this.MidasPaymentParams, ...Params,
success: async (response) => { token: this.LoginData["token"],
console.log("--SDK支付成功:", response); weixin_mini_program_app_id: data.weixin_mini_program_app_id, // 跳转小程序的appid,获取新openid用
let coinsResult = await this.getCoins({ ...this.SDKCOMMDATA, token: this.LoginData['token'], order_num: data.order_num }); sub_product_code: data.sub_product_code, // 跳转小程序的productcode
if (coinsResult.code == 0 || coinsResult.code == 3012) { pay_channel: data.pay_channel, // 支付方式改变
resolve({ order_code: 200, msg: '' }); productKey: SDKConfig.productKey,
} },
else { };
resolve({ order_code: 0, msg: (coinsResult.msg || '') }); console.log("--发起跳转支付", params);
} this.navigateToMiniProgram(params);
}, return { order_code: 2, msg: "" }; // 切支付状态
fail: (err) => { }
console.log("--米大师支付失败:", err); if (code == 0 && data.open_customer_service) {
let msg = this.MidasErrorCode[JSON.stringify(err.errCode)] || '支付异常'; const params = {
if (showMessage) { title: "充值教程",
const params = { content: "即将跳转官方【客服会话】进行充值, 向客服回复【充值】获取充值链接",
title: '支付提示', showCancel: false,
content: msg, success: () => {
showCancel: false this.Customer({
} sessionFrom: "order_id=" + (data.order_num || "") + "&payload=" + (data.payload || ""),
this.showModal(params); showMessageCard: true,
} sendMessageTitle: "回复【充值】获取充值链接",
resolve({ order_code: err.errCode, msg: msg }); sendMessageImg: "https://h5sdk.pthc8.com/resource/images/payTips.jpg",
this.reportPaymentError({ order_code: err.errCode, msg: msg, order_num: data.order_num }); });
} },
}); };
}); this.showModal(params);
} return { order_code: 2, msg: "" };
} }
private getCoins = async (orderParams) => { // 通知服务端扣费 if (code == 0 && data.order_type == 1) {
console.log('--通知扣费:', orderParams); this.MidasPaymentParams["buyQuantity"] = <number>(Params.money / 100) * <number>data.weixin_proportion; // 充值金额
return await this.sdkRequest(Links.pay, orderParams) console.log("--米大师支付参数:", this.MidasPaymentParams);
} // 调微信米大师支付接口
public createActiveShare = async (shareInfo) => { //动态消息 return new Promise((resolve, reject) => {
let { code, data, msg } = await this.sdkRequest(Links.getActShareId, { (wx as any).requestMidasPayment({
...this.SDKCOMMDATA, ...this.MidasPaymentParams,
room_limit: shareInfo.room_limit, success: async (response) => {
target_state: 0 console.log("--SDK支付成功:", response);
}, 'POST'); let coinsResult = await this.getCoins({ ...this.SDKCOMMDATA, token: this.LoginData["token"], order_num: data.order_num });
if (code == 0) { if (coinsResult.code == 0 || coinsResult.code == 3012) {
const actId = data.activity_id; resolve({ order_code: 200, msg: "" });
const totalMembers = shareInfo.room_limit || '0'; } else {
(wx as any).updateShareMenu({ resolve({ order_code: 0, msg: coinsResult.msg || "" });
withShareTicket: true, }
isUpdatableMessage: true, },
activityId: this.actId, // 活动 ID fail: (err) => {
templateInfo: { console.log("--米大师支付失败:", err);
parameterList: [{ let msg = this.MidasErrorCode[JSON.stringify(err.errCode)] || "支付异常";
name: 'member_count', if (showMessage) {
value: '1' // 设置房间初始玩家1 const params = {
}, { title: "支付提示",
name: 'room_limit', content: msg,
value: totalMembers showCancel: false,
}] };
}, this.showModal(params);
success: (res) => { }
let ShareParams = { resolve({ order_code: err.errCode, msg: msg });
title: shareInfo.title ? shareInfo.title : SDKConfig.shareTitle, this.reportPaymentError({ order_code: err.errCode, msg: msg, order_num: data.order_num });
imageUrl: shareInfo.image ? shareInfo.image : SDKConfig.shareImageUrl, },
imageId: shareInfo.imageId ? shareInfo.imageId : SDKConfig.shareImageId, });
query: 'fromOpenId=' + this.LoginData['open_id'] + '&from=share&tag=0&actId=' + actId });
} }
this.share(ShareParams); };
}, private getCoins = async (orderParams) => {
}); // 通知服务端扣费
} else { console.log("--通知扣费:", orderParams);
console.log("--SDK错误::createActiveSahre", msg); return await this.sdkRequest(Links.pay, orderParams);
} };
} public createActiveShare = async (shareInfo) => {
//动态消息
public updateShareMsgInfo = (updateInfo) => { // 更新动态消息接口 let { code, data, msg } = await this.sdkRequest(
if (!updateInfo.activity_id || updateInfo.activity_id == '') { Links.getActShareId,
updateInfo = { {
...updateInfo, ...this.SDKCOMMDATA,
activity_id: this.actId, room_limit: shareInfo.room_limit,
version_type: SDKConfig.navPayEnv target_state: 0,
} },
} "POST"
this.sdkRequest(Links.setActShareInfo, { ...this.SDKCOMMDATA, ...updateInfo }, 'POST') );
} if (code == 0) {
public getActiveShareInfo = async () => { // 查询动态消息接口 const actId = data.activity_id;
let { code, data } = await this.sdkRequest(Links.getActShareInfo, { const totalMembers = shareInfo.room_limit || "0";
product_code: SDKConfig.productCode, (wx as any).updateShareMenu({
activity_id: this.actId withShareTicket: true,
}, 'POST') isUpdatableMessage: true,
return !code ? data : 0; activityId: this.actId, // 活动 ID
} templateInfo: {
public async phoneCode(phoneInfo, callback?) { // 发送验证码接口 parameterList: [
const { code } = await this.sdkRequest(Links.sendCode, { ...this.SDKCOMMDATA, ...phoneInfo, type: 'SDK.BIND_MOBILE' }); {
callback && callback(!code); name: "member_count",
} value: "1", // 设置房间初始玩家1
public async userPhone(phoneInfo, callback) { // 绑定手机 },
const { code } = await this.sdkRequest(Links.saveNum, { ...this.SDKCOMMDATA, open_id: this.LoginData['open_id'], ...phoneInfo, source: 'WEIXIN' }) {
callback(code); name: "room_limit",
} value: totalMembers,
public async checkUserPhoneBind() { // 查询用户绑定状态 },
const { code } = await this.sdkRequest(Links.bindPhone, { ...this.SDKCOMMDATA, uid: this.LoginData['uid'] }); ],
return !code; },
} success: (res) => {
public async getUserPaymentType(roleInfo) { // 是否支持切支付 let ShareParams = {
let { code } = await this.sdkRequest(Links.payType, { ...this.SDKCOMMDATA, ...roleInfo }); title: shareInfo.title ? shareInfo.title : SDKConfig.shareTitle,
return !code; imageUrl: shareInfo.image ? shareInfo.image : SDKConfig.shareImageUrl,
} imageId: shareInfo.imageId ? shareInfo.imageId : SDKConfig.shareImageId,
// 创建录屏对象 query: "fromOpenId=" + this.LoginData["open_id"] + "&from=share&tag=0&actId=" + actId,
public createGameRecorder = (startEventCallBack?, stopEventCallBack?, cpCallback?) => { };
try { this.share(ShareParams);
this.GameRecorder = (wx as any).getGameRecorder(); },
if (!this.GameRecorder.isFrameSupported()) { });
if (cpCallback) cpCallback({ status: 0, msg: '设备不支持录屏功能.' }); } else {
return; console.log("--SDK错误::createActiveSahre", msg);
} }
this.GameRecorder.on('start', () => { };
if (startEventCallBack) startEventCallBack();
}); public updateShareMsgInfo = (updateInfo) => {
this.GameRecorder.on('stop', (res) => { // 更新动态消息接口
console.log('--对局回放时长:', res.duration); if (!updateInfo.activity_id || updateInfo.activity_id == "") {
if (stopEventCallBack) stopEventCallBack(res); updateInfo = {
}) ...updateInfo,
if (cpCallback) cpCallback({ status: 1, msg: null }) activity_id: this.actId,
} catch (err) { version_type: SDKConfig.navPayEnv,
console.log("--录屏异常:", err); };
if (cpCallback) cpCallback({ status: 0, msg: err }) }
} this.sdkRequest(Links.setActShareInfo, { ...this.SDKCOMMDATA, ...updateInfo }, "POST");
} };
public startGameRecorder(recorderInfo: RecorderInfo) { public getActiveShareInfo = async () => {
try { // 查询动态消息接口
this.GameRecorder.start({ let { code, data } = await this.sdkRequest(
duration: recorderInfo.duration Links.getActShareInfo,
}); {
} catch (err) { product_code: SDKConfig.productCode,
console.log("$$SDK录屏异常::gameRecorder", err); activity_id: this.actId,
} },
} "POST"
public stopGameRecorder(shareInfo) { );
try { return !code ? data : 0;
this.GameRecorder.stop(); };
if (this.recorderBtn) this.recorderBtn.show(); public async phoneCode(phoneInfo, callback?) {
else this.createRecorderShareButton(shareInfo); // 发送验证码接口
} catch (err) { const { code } = await this.sdkRequest(Links.sendCode, { ...this.SDKCOMMDATA, ...phoneInfo, type: "SDK.BIND_MOBILE" });
console.log("$$SDK录屏异常::gameRecorder", err); callback && callback(!code);
} }
} public async userPhone(phoneInfo, callback) {
private createRecorderShareButton(shareInfo) { // 绑定手机
let recorderShareInfo = { const { code } = await this.sdkRequest(Links.saveNum, { ...this.SDKCOMMDATA, open_id: this.LoginData["open_id"], ...phoneInfo, source: "WEIXIN" });
style: { callback(code);
left: shareInfo.left, }
top: shareInfo.top, public async checkUserPhoneBind() {
height: shareInfo.height, // 查询用户绑定状态
iconMarginRight: shareInfo.iconMarginRight, const { code } = await this.sdkRequest(Links.bindPhone, { ...this.SDKCOMMDATA, uid: this.LoginData["uid"] });
fontSize: shareInfo.fontSize, return !code;
color: shareInfo.color, }
paddingLeft: shareInfo.paddingLeft, public async getUserPaymentType(roleInfo) {
paddingRight: shareInfo.paddingRight // 是否支持切支付
}, let { code } = await this.sdkRequest(Links.payType, { ...this.SDKCOMMDATA, ...roleInfo });
icon: shareInfo.icon || '', return !code;
image: shareInfo.image || '', }
text: shareInfo.text || '', // 创建录屏对象
share: { public createGameRecorder = (startEventCallBack?, stopEventCallBack?, cpCallback?) => {
query: 'fromOpenId=' + this.LoginData['open_id'] + '&from=share&tag=0&' + (shareInfo.query ? shareInfo.query : ''), try {
bgm: shareInfo.bgm, this.GameRecorder = (wx as any).getGameRecorder();
timeRange: shareInfo.timeRange if (!this.GameRecorder.isFrameSupported()) {
} if (cpCallback) cpCallback({ status: 0, msg: "设备不支持录屏功能." });
}; return;
this.recorderBtn = (wx as any).createGameRecorderShareButton(recorderShareInfo); }
// 当分享出现异常时才会触发点击回调 this.GameRecorder.on("start", () => {
this.recorderBtn.onTap(res => { if (startEventCallBack) startEventCallBack();
console.log('--录屏异常:', res); });
}); this.GameRecorder.on("stop", (res) => {
} console.log("--对局回放时长:", res.duration);
public hideGameRecorderShareButton() { if (stopEventCallBack) stopEventCallBack(res);
if (this.recorderBtn) this.recorderBtn.hide(); });
} if (cpCallback) cpCallback({ status: 1, msg: null });
public async checkUserAdvised() { // 防沉迷验证 } catch (err) {
let time = this.onlineTime * 60; // 转成成秒 console.log("--录屏异常:", err);
return new Promise((resolve, reject) => { if (cpCallback) cpCallback({ status: 0, msg: err });
(wx as any).checkIsUserAdvisedToRest({ }
todayPlayedTime: time, };
success: function (res) { public startGameRecorder(recorderInfo: RecorderInfo) {
resolve(res.result); // 是否建议用户休息 try {
}, this.GameRecorder.start({
fail: function (res) { duration: recorderInfo.duration,
reject(res); });
}, } catch (err) {
}) console.log("$$SDK录屏异常::gameRecorder", err);
}); }
} }
// 获取用户信息 public stopGameRecorder(shareInfo) {
public getUserInfo = (): Promise<any> => { try {
return new Promise(async (resolve, reject) => { this.GameRecorder.stop();
if ((wx as any).getUserProfile) { if (this.recorderBtn) this.recorderBtn.show();
const userInfo = await this._getUserProfile(); else this.createRecorderShareButton(shareInfo);
resolve(userInfo); } catch (err) {
return; console.log("$$SDK录屏异常::gameRecorder", err);
} }
const status = await this._getSetting(); }
const w = (wx as any).getSystemInfoSync().windowWidth; private createRecorderShareButton(shareInfo) {
const h = (wx as any).getSystemInfoSync().windowHeight; let recorderShareInfo = {
if (status == 1) { style: {
const userInfo = await this._getUserInfo(); left: shareInfo.left,
if (userInfo.nickname) { top: shareInfo.top,
// 上报用户授权 height: shareInfo.height,
this.ReportData({ iconMarginRight: shareInfo.iconMarginRight,
userInfo: { ...userInfo, nickName: encodeURI(userInfo.nickName) }, fontSize: shareInfo.fontSize,
action: 'authorize', color: shareInfo.color,
}) paddingLeft: shareInfo.paddingLeft,
} paddingRight: shareInfo.paddingRight,
resolve(userInfo); },
} else if (status == 0) { icon: shareInfo.icon || "",
// 用户已拒绝授权,再调用相关 API 或者 wx.authorize 会失败,需要引导用户到设置页面打开授权开关 image: shareInfo.image || "",
let OpenSettingButton = (wx as any).createOpenSettingButton({ text: shareInfo.text || "",
type: "text", share: {
text: "", query: "fromOpenId=" + this.LoginData["open_id"] + "&from=share&tag=0&" + (shareInfo.query ? shareInfo.query : ""),
style: { bgm: shareInfo.bgm,
left: 0, timeRange: shareInfo.timeRange,
top: 0, },
width: w, };
height: h this.recorderBtn = (wx as any).createGameRecorderShareButton(recorderShareInfo);
} // 当分享出现异常时才会触发点击回调
}); this.recorderBtn.onTap((res) => {
OpenSettingButton.onTap(async (res) => { console.log("--录屏异常:", res);
let t_status = await this._getSetting(); });
OpenSettingButton.offTap(this); }
OpenSettingButton.destroy(); public hideGameRecorderShareButton() {
OpenSettingButton = null; if (this.recorderBtn) this.recorderBtn.hide();
if (t_status == 1) { }
let userInfo = await this._getUserInfo(); public async checkUserAdvised() {
// 上报用户授权 // 防沉迷验证
this.ReportData({ let time = this.onlineTime * 60; // 转成成秒
...userInfo, return new Promise((resolve, reject) => {
action: 'authorize', (wx as any).checkIsUserAdvisedToRest({
nickName: encodeURI(userInfo.nickName) todayPlayedTime: time,
}) success: function (res) {
resolve(userInfo); resolve(res.result); // 是否建议用户休息
} },
}); fail: function (res) {
} reject(res);
else if (status == -1) { },
let userBtn = (wx as any).createUserInfoButton({ });
type: "text", });
text: "", }
withCredentials: false, // 获取用户信息
style: { public getUserInfo = (): Promise<any> => {
left: 0, return new Promise(async (resolve, reject) => {
top: 0, const status = await this._getSetting();
width: w, const w = (wx as any).getSystemInfoSync().windowWidth;
height: h, const h = (wx as any).getSystemInfoSync().windowHeight;
}, if (status == 1) {
}); const userInfo = await this._getUserInfo();
userBtn.onTap((res) => { if (userInfo.nickname) {
userBtn.offTap(this); // 上报用户授权
userBtn.destroy(); this.ReportData({
userBtn = null; userInfo: { ...userInfo, nickName: encodeURI(userInfo.nickName) },
if (res.userInfo) { action: "authorize",
let userInfo = res["userInfo"]; });
// 上报用户授权 }
this.ReportData({ resolve(userInfo);
...userInfo, } else if (status == 0) {
action: 'authorize', // 用户已拒绝授权,再调用相关 API 或者 wx.authorize 会失败,需要引导用户到设置页面打开授权开关
nickName: encodeURI(userInfo.nickName) let OpenSettingButton = (wx as any).createOpenSettingButton({
}) type: "text",
resolve(userInfo); text: "",
} style: {
}); left: 0,
} top: 0,
}); width: w,
}; height: h,
private async _getUserProfile(): Promise<any> { },
return new Promise(async function (resolve, reject) { });
(wx as any).getUserProfile({ OpenSettingButton.onTap(async (res) => {
desc: '完善用户资料', let t_status = await this._getSetting();
success: (res) => { OpenSettingButton.offTap(this);
let userInfo = res["userInfo"]; OpenSettingButton.destroy();
resolve(userInfo); OpenSettingButton = null;
}, if (t_status == 1) {
fail: (res: any) => { let userInfo = await this._getUserInfo();
console.log("--SDK:玩家头像等数据失败,用户未授权"); // 上报用户授权
resolve(); this.ReportData({
} ...userInfo,
}); action: "authorize",
}); nickName: encodeURI(userInfo.nickName),
} });
private async _getUserInfo(): Promise<any> { resolve(userInfo);
return new Promise(async function (resolve, reject) { }
(wx as any).getUserInfo({ });
withCredentials: false,//获取用户信息,withCredentials 为 true 时需要先调用 wx.login 接口。需要用户授权 scope.userInfo。 } else if (status == -1) {
success: (res) => { let userBtn = (wx as any).createUserInfoButton({
let userInfo = res["userInfo"]; type: "text",
resolve(userInfo); text: "",
}, withCredentials: false,
fail: (res: any) => { style: {
console.log("--SDK:玩家头像等数据失败,用户未授权"); left: 0,
resolve(); top: 0,
} width: w,
}); height: h,
}); },
} });
private async _getSetting(): Promise<any> { userBtn.onTap((res) => {
return new Promise(async function (resolve, reject) { userBtn.offTap(this);
(wx as any).getSetting({ userBtn.destroy();
success: function (res) { userBtn = null;
let authSetting = res.authSetting; if (res.userInfo) {
if (authSetting['scope.userInfo'] === true) resolve(1); let userInfo = res["userInfo"];
else if (authSetting['scope.userInfo'] === false) resolve(0); // 上报用户授权
else resolve(-1); this.ReportData({
}, ...userInfo,
fail: reject, action: "authorize",
}); nickName: encodeURI(userInfo.nickName),
}); });
} resolve(userInfo);
public addShareEvent = (shareInfo: shareInfo, callback?) => { }
(wx as any).onShareAppMessage(() => { });
if (callback) callback(); }
const ShareParams = { });
title: shareInfo.title ? shareInfo.title : SDKConfig.shareTitle, };
imageUrl: shareInfo.image ? shareInfo.image : SDKConfig.shareImageUrl, private async _getUserProfile(): Promise<any> {
imageUrlId: shareInfo.imageId ? shareInfo.imageId : SDKConfig.shareImageId, return new Promise(async function (resolve, reject) {
query: 'fromOpenId=' + this.LoginData['open_id'] + '&from=share&tag=0&' + (shareInfo.query ? shareInfo.query : ''), (wx as any).getUserProfile({
withShareTicket: true, desc: "完善用户资料",
}; success: (res) => {
return ShareParams; let userInfo = res["userInfo"];
}); resolve(userInfo);
(wx as any).showShareMenu({ withShareTicket: true }) },
} fail: (res: any) => {
// 暂时恢复,稍后删除 console.log("--SDK:玩家头像等数据失败,用户未授权");
public ShareApp(params?: string) { resolve({});
const ShareParams = { },
title: SDKConfig.shareTitle, });
imageUrl: SDKConfig.shareImageUrl, });
imageId: SDKConfig.shareImageId, }
query: 'fromOpenId=' + this.LoginData['open_id'] + '&from=share&tag=0&' + (params ? params : '') private async _getUserInfo(): Promise<any> {
} return new Promise(async function (resolve, reject) {
return this.share(ShareParams) if ((wx as any).getUserProfile) {
} const userInfo = await this._getUserProfile();
public ShareGameInfo = (shareInfo?) => { resolve(userInfo);
// 参数,记录分享的用户openid } else {
const ShareParams = { (wx as any).getUserInfo({
title: shareInfo && shareInfo.title ? shareInfo.title : SDKConfig.shareTitle, withCredentials: false, //获取用户信息,withCredentials 为 true 时需要先调用 wx.login 接口。需要用户授权 scope.userInfo。
imageUrl: shareInfo && shareInfo.image ? shareInfo.image : SDKConfig.shareImageUrl, success: (res) => {
imageId: shareInfo && shareInfo.imageId ? shareInfo.imageId : SDKConfig.shareImageId, let userInfo = res["userInfo"];
query: 'fromOpenId=' + this.LoginData['open_id'] + '&from=share&tag=0&' + (shareInfo.extraData ? shareInfo.extraData : '') resolve(userInfo);
} },
return this.share(ShareParams) fail: (res: any) => {
} console.log("--SDK:玩家头像等数据失败,用户未授权");
private share = (DATA): Promise<any> => { resolve({});
return new Promise((resolve, reject) => { },
(wx as any).shareAppMessage({ });
...DATA, }
withShareTicket: true, });
success: res => { }
resolve(1); private async _getSetting(): Promise<any> {
}, return new Promise(async function (resolve, reject) {
fail: res => { (wx as any).getSetting({
resolve(-1); success: function (res) {
}, let authSetting = res.authSetting;
}) if (authSetting["scope.userInfo"] === true) resolve(1);
setTimeout(function () { // 两秒后直接当分享成功返回 else if (authSetting["scope.userInfo"] === false) resolve(0);
resolve(2) else resolve(-1);
}, 3000) },
}) fail: reject,
} });
// 切换游戏 });
public navToOtherGame = (params) => { }
const obj = { // 跳转参数 public addShareEvent = (shareInfo: shareInfo, callback?) => {
appId: params.appid, // 跳转的小程序appid (wx as any).onShareAppMessage(() => {
path: '', // 跳转到首页 if (callback) callback();
envVersion: SDKConfig.navPayEnv, //跳转方式 const ShareParams = {
extraData: { title: shareInfo.title ? shareInfo.title : SDKConfig.shareTitle,
from_openid: this.LoginData['open_id'], imageUrl: shareInfo.image ? shareInfo.image : SDKConfig.shareImageUrl,
from_product: SDKConfig.productCode, imageUrlId: shareInfo.imageId ? shareInfo.imageId : SDKConfig.shareImageId,
from_uid: this.LoginData['uid'] query: "fromOpenId=" + this.LoginData["open_id"] + "&from=share&tag=0&" + (shareInfo.query ? shareInfo.query : ""),
} withShareTicket: true,
} };
this.navigateToMiniProgram(obj); return ShareParams;
} });
private navigateToMiniProgram = (params) => { (wx as any).showShareMenu({ withShareTicket: true });
if (this.SystemInfo['sdkVersion'] < '2.2') { };
this.showMsg('微信版本不兼容,请升级..') // 暂时恢复,稍后删除
} else { public ShareApp(params?: string) {
(wx as any).navigateToMiniProgram(params) const ShareParams = {
} title: SDKConfig.shareTitle,
} imageUrl: SDKConfig.shareImageUrl,
// 客服 imageId: SDKConfig.shareImageId,
public Customer = (_orderInfo?) => { query: "fromOpenId=" + this.LoginData["open_id"] + "&from=share&tag=0&" + (params ? params : ""),
try { };
(wx as any).openCustomerServiceConversation(_orderInfo) return this.share(ShareParams);
} catch (err) { }
console.log("访问客服异常-->", err) public ShareGameInfo = (shareInfo?) => {
this.showMsg('打开客服链接失败.') // 参数,记录分享的用户openid
} const ShareParams = {
} title: shareInfo && shareInfo.title ? shareInfo.title : SDKConfig.shareTitle,
public ActiReport() { imageUrl: shareInfo && shareInfo.image ? shareInfo.image : SDKConfig.shareImageUrl,
this.ReportData({ action: 'activation' }); imageId: shareInfo && shareInfo.imageId ? shareInfo.imageId : SDKConfig.shareImageId,
this.heartBeatReport(); query: "fromOpenId=" + this.LoginData["open_id"] + "&from=share&tag=0&" + (shareInfo.extraData ? shareInfo.extraData : ""),
} // 上报激活 };
public RegisterReport() { this.ReportData({ action: 'register' }) } // 上报注册 return this.share(ShareParams);
public LoginReport() { this.ReportData({ action: 'login' }) } // 上报登录 };
public RoleLevelReport(roleInfo) { this.ReportData({ ...roleInfo, action: 'roleUpgrade' }) } // 上报等级 private share = (DATA): Promise<any> => {
public CustomReport(custInfo) { this.ReportData({ ...custInfo, action: 'customevent' }) } // 自定义上报 return new Promise((resolve, reject) => {
public userClickEvent() { this.clickCounter++ } (wx as any).shareAppMessage({
private heartBeatReport() { ...DATA,
setTimeout(() => { withShareTicket: true,
this.clickReport(); success: (res) => {
this.heartBeatReport(); resolve(1);
}, 60 * 1000); },
} fail: (res) => {
private clickReport = async () => { resolve(-1);
this.ReportData({ action: 'heartBeat' }) },
this.clickCounter > 0 && this.ReportData({ action: 'userappclick', click_times: this.clickCounter }); });
this.clickCounter = 0; // 上报后归零 setTimeout(function () {
} // 两秒后直接当分享成功返回
// 上报支付异常 resolve(2);
private reportPaymentError(err: Object) { }, 3000);
let portData = { });
...this.SDKCOMMDATA, };
uid: this.LoginData['uid'], // 切换游戏
event_code: 'PaymentError', event_data: JSON.stringify(err), public navToOtherGame = (params) => {
} const obj = {
this.sdkRequest(Links.paymentErrorReport, portData, 'POST'); // 跳转参数
} appId: params.appid, // 跳转的小程序appid
// 数据上报接口,外部调用,参数中必须含有action值 path: "", // 跳转到首页
public ReportData(portData) { envVersion: SDKConfig.navPayEnv, //跳转方式
portData['launchOptions'] = this.LaunchOptions; extraData: {
portData['userInfo'] = { ...portData['userInfo'], ...{ userId: this.LoginData['uid'] || '', open_id: this.LoginData['open_id'] } }; from_openid: this.LoginData["open_id"],
portData['systemInfo'] = this.SystemInfo; from_product: SDKConfig.productCode,
portData['product_code'] = SDKConfig.productCode; from_uid: this.LoginData["uid"],
portData['time'] = Date.parse(new Date().toString()) // 获取当前时间戳秒 },
console.log('--SDK上报:', portData); };
this.request(SDKConfig.report, portData, 'POST') this.navigateToMiniProgram(obj);
} };
// 退出小游戏 private navigateToMiniProgram = (params) => {
public exitApp = () => { if (this.SystemInfo["sdkVersion"] < "2.2") {
(wx as any).exitMiniProgram() this.showMsg("微信版本不兼容,请升级..");
} } else {
private getWechatCode = (): Promise<any> => { (wx as any).navigateToMiniProgram(params);
return new Promise((resolve, reject) => { }
try { };
(wx as any).login({ // 客服
success: (res) => { public Customer = (_orderInfo?) => {
if (res.code) resolve(res); try {
else { (wx as any).openCustomerServiceConversation(_orderInfo);
this.showMsg("执行wx.login返回成功,但无code参数", 5000); } catch (err) {
resolve({ code: 0 }); console.log("访问客服异常-->", err);
} this.showMsg("打开客服链接失败.");
}, }
fail: () => { };
this.showMsg("执行wx.login返回失败", 5000); public ActiReport() {
resolve({ code: 0 }); this.ReportData({ action: "activation" });
}, this.heartBeatReport();
}); } // 上报激活
} catch (err) { public RegisterReport() {
this.showMsg("微信登录接口返回失败"); this.ReportData({ action: "register" });
} } // 上报注册
}); public LoginReport() {
} this.ReportData({ action: "login" });
private showLoading() { } // 上报登录
(wx as any).showLoading({ public RoleLevelReport(roleInfo) {
title: '请稍候..', this.ReportData({ ...roleInfo, action: "roleUpgrade" });
mask: true } // 上报等级
}) public CustomReport(custInfo) {
} this.ReportData({ ...custInfo, action: "customevent" });
private hideLoading() { (wx as any).hideLoading() } } // 自定义上报
private showModal(DATA) { public userClickEvent() {
(wx as any).showModal({ this.clickCounter++;
...DATA, }
cancelText: '取消', private heartBeatReport() {
confirmText: '确认' setTimeout(() => {
}) this.clickReport();
} this.heartBeatReport();
public showMsg = (str, duration = 3000) => { }, 60 * 1000);
(wx as any).showToast({ }
title: str, private clickReport = async () => {
icon: 'none', this.ReportData({ action: "heartBeat" });
duration: duration this.clickCounter > 0 && this.ReportData({ action: "userappclick", click_times: this.clickCounter });
}) this.clickCounter = 0; // 上报后归零
} };
private getSystemInfo = (): Promise<any> => { // 上报支付异常
return new Promise((resolve, reject) => { private reportPaymentError(err: Object) {
(wx as any).getSystemInfo({ let portData = {
success: (res) => { resolve(res) }, ...this.SDKCOMMDATA,
}) uid: this.LoginData["uid"],
}) event_code: "PaymentError",
} event_data: JSON.stringify(err),
public getNetworkType = (): Promise<any> => { };
return new Promise((resolve, reject) => { this.sdkRequest(Links.paymentErrorReport, portData, "POST");
(wx as any).getNetworkType({ }
success: (res) => { resolve(res.networkType) }, // 数据上报接口,外部调用,参数中必须含有action值
}) public ReportData(portData) {
}) portData["launchOptions"] = this.LaunchOptions;
} portData["userInfo"] = { ...portData["userInfo"], ...{ userId: this.LoginData["uid"] || "", open_id: this.LoginData["open_id"] } };
public getOptionsInfo = () => { portData["systemInfo"] = this.SystemInfo;
const options = (wx as any).getLaunchOptionsSync() portData["product_code"] = SDKConfig.productCode;
console.log("--启动参数--->", options); portData["time"] = Date.parse(new Date().toString()); // 获取当前时间戳秒
if (options.query && Object.keys(options.query).length > 0) { console.log("--SDK上报:", portData);
if (options.query.scene) { // 扫码参数 this.request(SDKConfig.report, portData, "POST");
const scene = this.toJson(decodeURIComponent(options.query.scene)); }
return scene; // 退出小游戏
} else return { ...options.query, scene: options.scene || '' }; // 普通url参数 public exitApp = () => {
} else if (options.referrerInfo && options.referrerInfo.appId) { (wx as any).exitMiniProgram();
return { ...options.referrerInfo.extraData, scene: options.scene || '', appId: options.referrerInfo.appId } // 小程序跳转附带参数 };
} else return {} private getWechatCode = (): Promise<any> => {
} return new Promise((resolve, reject) => {
// SDK上报接口 try {
private sdkRequest = async (link: string, portData, method?) => { (wx as any).login({
portData = this.md5_sign(portData) // 附上签名参数 success: (res) => {
console.log('--SDK接口:', portData); if (res.code) resolve(res);
return await this.request(link, portData, method); else {
} this.showMsg("执行wx.login返回成功,但无code参数", 5000);
// 调用微信请求接口 resolve({ code: 0 });
private request = async (URI: string, Params: any, Method = 'GET') => { }
const { code, data, msg } = await this.fetchUri(URI, Params, Method); },
if (!data) return { code, data: {}, msg } fail: () => {
if (!code) return { code, data, msg }; this.showMsg("执行wx.login返回失败", 5000);
if (code) this.showMsg(msg); // 输出接口异常 resolve({ code: 0 });
} },
private fetchUri = (URI, DATA, METHOD): Promise<any> => { });
return new Promise((resolve, reject) => { } catch (err) {
try { this.showMsg("微信登录接口返回失败");
(wx as any).request({ }
url: URI, });
method: METHOD, };
data: DATA, private showLoading() {
header: { (wx as any).showLoading({
'Content-Type': 'json' title: "请稍候..",
}, mask: true,
success: (response) => { });
resolve(response.data) }
}, private hideLoading() {
fail: resolve (wx as any).hideLoading();
}) }
} catch (err) { private showModal(DATA) {
reject(err) (wx as any).showModal({
} ...DATA,
}) cancelText: "取消",
} confirmText: "确认",
//把字符串转换成json });
private toJson = (str: string) => { }
let json = {} public showMsg = (str, duration = 3000) => {
const jsonArr = str.split('&') (wx as any).showToast({
for (let i = 0; i < jsonArr.length; i++) { title: str,
const keyArr = jsonArr[i].split('=') icon: "none",
json[keyArr[0]] = keyArr[1] || '' // 附上key和对应的value duration: duration,
} });
return json };
} private getSystemInfo = (): Promise<any> => {
//接口签名,直接返回完整对象 return new Promise((resolve, reject) => {
private md5_sign = (obj) => { (wx as any).getSystemInfo({
obj.time = Date.parse(new Date().toString()) // 获取请求的时间戳秒 success: (res) => {
let keys = Object.keys(obj).sort(); resolve(res);
let key_url = ""; },
for (let i = 0; i < keys.length; i++) { });
if (keys[i] != 'sign') key_url += keys[i] + '=' + obj[keys[i]] + '&' });
} };
key_url = key_url + SDKConfig.productKey public getNetworkType = (): Promise<any> => {
obj.sign = md5(key_url) return new Promise((resolve, reject) => {
return obj (wx as any).getNetworkType({
} success: (res) => {
// SDK接口通用参数 resolve(res.networkType);
private SDKCOMMDATA: Object = { },
source: 'WEIXIN', });
product_code: SDKConfig.productCode, });
uuid: '', };
equipmentos: '', public getOptionsInfo = () => {
package_code: '', const options = (wx as any).getLaunchOptionsSync();
time: '', console.log("--启动参数--->", options);
sign: '', if (options.query && Object.keys(options.query).length > 0) {
os: '', if (options.query.scene) {
version: this.sdkVersion // 扫码参数
} const scene = this.toJson(decodeURIComponent(options.query.scene));
// 米大师支付参数 return scene;
private MidasPaymentParams = { } else return { ...options.query, scene: options.scene || "" }; // 普通url参数
mode: 'game', // 支付的类型 } else if (options.referrerInfo && options.referrerInfo.appId) {
env: SDKConfig.midasPayEnv, // 米大师环境 return { ...options.referrerInfo.extraData, scene: options.scene || "", appId: options.referrerInfo.appId }; // 小程序跳转附带参数
currencyType: 'CNY', // 币种 } else return {};
platform: 'android', // 客户端平台 };
zoneId: '1', // 分区ID,默认1 // SDK上报接口
offerId: SDKConfig.offerid, private sdkRequest = async (link: string, portData, method?) => {
} portData = this.md5_sign(portData); // 附上签名参数
private MidasErrorCode = { console.log("--SDK接口:", portData);
'-1': '系统失败', return await this.request(link, portData, method);
'-2': '支付取消', };
'-15001': '缺少参数', // 调用微信请求接口
'-15002': '参数不合法', private request = async (URI: string, Params: any, Method = "GET") => {
'-15003': '订单重复', const { code, data, msg } = await this.fetchUri(URI, Params, Method);
'-15004': '后台错误', if (!data) return { code, data: {}, msg };
'-15005': 'appId权限被封禁', if (!code) return { code, data, msg };
'-15006': '货币类型不支持', if (code) this.showMsg(msg); // 输出接口异常
'-15007': '订单已支付', };
'-15009': '由于健康系统限制,本次支付已超过限额', private fetchUri = (URI, DATA, METHOD): Promise<any> => {
'1': '用户取消支付', return new Promise((resolve, reject) => {
'2': '客户端错误,判断到小程序在用户处于支付中时,又发起了一笔支付请求', try {
'3': 'Android 独有错误:用户使用 Google Play 支付,而手机未安装 Google Play', (wx as any).request({
'4': '用户操作系统支付状态异常', url: URI,
'5': '操作系统错误', method: METHOD,
'6': '其他错误', data: DATA,
'1000': '参数错误', header: {
'1003': '米大师Portal错误', "Content-Type": "json",
} },
} success: (response) => {
interface shareInfo { resolve(response.data);
title?: string },
image?: string fail: resolve,
imageId?: string });
query?: string } catch (err) {
success: any reject(err);
fail: any }
complete?: any });
} };
interface RecorderInfo { //把字符串转换成json
duration: number private toJson = (str: string) => {
} let json = {};
// SDK后端接口(勿改) const jsonArr = str.split("&");
const Links = { for (let i = 0; i < jsonArr.length; i++) {
init: SDKConfig.sdk_domain + '/weixin/access_token.php', // 获取openid const keyArr = jsonArr[i].split("=");
active: SDKConfig.sdk_domain + '/appInit.php', // SDK初始化接口 json[keyArr[0]] = keyArr[1] || ""; // 附上key和对应的value
login: SDKConfig.sdk_domain + '/login.php', // SDK登录接口,获取用户平台信息 }
order: SDKConfig.pay_domain + '/pay.php', //订单接口 return json;
pay: SDKConfig.pay_domain + '/notify/midas/pay.php', //扣费接口 };
payType: SDKConfig.pay_domain + '/pay_channel/status.php', // 查询支付状态 //接口签名,直接返回完整对象
sendCode: SDKConfig.sdk_domain + '/sms/send.php', // 发送验证码 private md5_sign = (obj) => {
saveNum: SDKConfig.sdk_domain + '/bind/mobile.php', // 保存手机号码 obj.time = Date.parse(new Date().toString()); // 获取请求的时间戳秒
playTime: SDKConfig.sdk_domain + '', // 获取用户在线时长 let keys = Object.keys(obj).sort();
bindPhone: SDKConfig.sdk_domain + '/bind/is_bind_mobile.php', // 用户手机绑定状态 let key_url = "";
getActShareId: SDKConfig.active_domain + '/weixin/updatable_message/create_activity_id', // 获取活动消息id for (let i = 0; i < keys.length; i++) {
setActShareInfo: SDKConfig.active_domain + '/weixin/updatable_message/updatablemsg', // 更新活动消息内容 if (keys[i] != "sign") key_url += keys[i] + "=" + obj[keys[i]] + "&";
getActShareInfo: SDKConfig.active_domain + '/weixin/updatable_message/get_activity', // 查询活动消息内容 }
paymentErrorReport: SDKConfig.sdk_domain + '/v2/analytics/event', // 上报支付错误信息 key_url = key_url + SDKConfig.productKey;
} obj.sign = md5(key_url);
// md5加密 return obj;
const rotateLeft = (lValue, iShiftBits) => { return (lValue << iShiftBits) | (lValue >>> (32 - iShiftBits)) }; var addUnsigned = function (lX, lY) { var lX4, lY4, lX8, lY8, lResult; lX8 = (lX & 2147483648); lY8 = (lY & 2147483648); lX4 = (lX & 1073741824); lY4 = (lY & 1073741824); lResult = (lX & 1073741823) + (lY & 1073741823); if (lX4 & lY4) { return (lResult ^ 2147483648 ^ lX8 ^ lY8) } if (lX4 | lY4) { if (lResult & 1073741824) { return (lResult ^ 3221225472 ^ lX8 ^ lY8) } else { return (lResult ^ 1073741824 ^ lX8 ^ lY8) } } else { return (lResult ^ lX8 ^ lY8) } }; var F = function (x, y, z) { return (x & y) | ((~x) & z) }; var G = function (x, y, z) { return (x & z) | (y & (~z)) }; var H = function (x, y, z) { return (x ^ y ^ z) }; var I = function (x, y, z) { return (y ^ (x | (~z))) }; var FF = function (a, b, c, d, x, s, ac) { a = addUnsigned(a, addUnsigned(addUnsigned(F(b, c, d), x), ac)); return addUnsigned(rotateLeft(a, s), b) }; var GG = function (a, b, c, d, x, s, ac) { a = addUnsigned(a, addUnsigned(addUnsigned(G(b, c, d), x), ac)); return addUnsigned(rotateLeft(a, s), b) }; var HH = function (a, b, c, d, x, s, ac) { a = addUnsigned(a, addUnsigned(addUnsigned(H(b, c, d), x), ac)); return addUnsigned(rotateLeft(a, s), b) }; var II = function (a, b, c, d, x, s, ac) { a = addUnsigned(a, addUnsigned(addUnsigned(I(b, c, d), x), ac)); return addUnsigned(rotateLeft(a, s), b) }; var convertToWordArray = function (string) { var lWordCount; var lMessageLength = string.length; var lNumberOfWordsTempOne = lMessageLength + 8; var lNumberOfWordsTempTwo = (lNumberOfWordsTempOne - (lNumberOfWordsTempOne % 64)) / 64; var lNumberOfWords = (lNumberOfWordsTempTwo + 1) * 16; var lWordArray = Array(lNumberOfWords - 1); var lBytePosition = 0; var lByteCount = 0; while (lByteCount < lMessageLength) { lWordCount = (lByteCount - (lByteCount % 4)) / 4; lBytePosition = (lByteCount % 4) * 8; lWordArray[lWordCount] = (lWordArray[lWordCount] | (string.charCodeAt(lByteCount) << lBytePosition)); lByteCount++ } lWordCount = (lByteCount - (lByteCount % 4)) / 4; lBytePosition = (lByteCount % 4) * 8; lWordArray[lWordCount] = lWordArray[lWordCount] | (128 << lBytePosition); lWordArray[lNumberOfWords - 2] = lMessageLength << 3; lWordArray[lNumberOfWords - 1] = lMessageLength >>> 29; return lWordArray }; var wordToHex = function (lValue) { var WordToHexValue = "", WordToHexValueTemp = "", lByte, lCount; for (lCount = 0; lCount <= 3; lCount++) { lByte = (lValue >>> (lCount * 8)) & 255; WordToHexValueTemp = "0" + lByte.toString(16); WordToHexValue = WordToHexValue + WordToHexValueTemp.substr(WordToHexValueTemp.length - 2, 2) } return WordToHexValue }; var uTF8Encode = function (string) { string = string.replace(/\x0d\x0a/g, "\x0a"); var output = ""; for (var n = 0; n < string.length; n++) { var c = string.charCodeAt(n); if (c < 128) { output += String.fromCharCode(c) } else { if ((c > 127) && (c < 2048)) { output += String.fromCharCode((c >> 6) | 192); output += String.fromCharCode((c & 63) | 128) } else { output += String.fromCharCode((c >> 12) | 224); output += String.fromCharCode(((c >> 6) & 63) | 128); output += String.fromCharCode((c & 63) | 128) } } } return output }; function md5(string) { var x = Array(); var k, AA, BB, CC, DD, a, b, c, d; var S11 = 7, S12 = 12, S13 = 17, S14 = 22; var S21 = 5, S22 = 9, S23 = 14, S24 = 20; var S31 = 4, S32 = 11, S33 = 16, S34 = 23; var S41 = 6, S42 = 10, S43 = 15, S44 = 21; string = uTF8Encode(string); x = convertToWordArray(string); a = 1732584193; b = 4023233417; c = 2562383102; d = 271733878; for (k = 0; k < x.length; k += 16) { AA = a; BB = b; CC = c; DD = d; a = FF(a, b, c, d, x[k + 0], S11, 3614090360); d = FF(d, a, b, c, x[k + 1], S12, 3905402710); c = FF(c, d, a, b, x[k + 2], S13, 606105819); b = FF(b, c, d, a, x[k + 3], S14, 3250441966); a = FF(a, b, c, d, x[k + 4], S11, 4118548399); d = FF(d, a, b, c, x[k + 5], S12, 1200080426); c = FF(c, d, a, b, x[k + 6], S13, 2821735955); b = FF(b, c, d, a, x[k + 7], S14, 4249261313); a = FF(a, b, c, d, x[k + 8], S11, 1770035416); d = FF(d, a, b, c, x[k + 9], S12, 2336552879); c = FF(c, d, a, b, x[k + 10], S13, 4294925233); b = FF(b, c, d, a, x[k + 11], S14, 2304563134); a = FF(a, b, c, d, x[k + 12], S11, 1804603682); d = FF(d, a, b, c, x[k + 13], S12, 4254626195); c = FF(c, d, a, b, x[k + 14], S13, 2792965006); b = FF(b, c, d, a, x[k + 15], S14, 1236535329); a = GG(a, b, c, d, x[k + 1], S21, 4129170786); d = GG(d, a, b, c, x[k + 6], S22, 3225465664); c = GG(c, d, a, b, x[k + 11], S23, 643717713); b = GG(b, c, d, a, x[k + 0], S24, 3921069994); a = GG(a, b, c, d, x[k + 5], S21, 3593408605); d = GG(d, a, b, c, x[k + 10], S22, 38016083); c = GG(c, d, a, b, x[k + 15], S23, 3634488961); b = GG(b, c, d, a, x[k + 4], S24, 3889429448); a = GG(a, b, c, d, x[k + 9], S21, 568446438); d = GG(d, a, b, c, x[k + 14], S22, 3275163606); c = GG(c, d, a, b, x[k + 3], S23, 4107603335); b = GG(b, c, d, a, x[k + 8], S24, 1163531501); a = GG(a, b, c, d, x[k + 13], S21, 2850285829); d = GG(d, a, b, c, x[k + 2], S22, 4243563512); c = GG(c, d, a, b, x[k + 7], S23, 1735328473); b = GG(b, c, d, a, x[k + 12], S24, 2368359562); a = HH(a, b, c, d, x[k + 5], S31, 4294588738); d = HH(d, a, b, c, x[k + 8], S32, 2272392833); c = HH(c, d, a, b, x[k + 11], S33, 1839030562); b = HH(b, c, d, a, x[k + 14], S34, 4259657740); a = HH(a, b, c, d, x[k + 1], S31, 2763975236); d = HH(d, a, b, c, x[k + 4], S32, 1272893353); c = HH(c, d, a, b, x[k + 7], S33, 4139469664); b = HH(b, c, d, a, x[k + 10], S34, 3200236656); a = HH(a, b, c, d, x[k + 13], S31, 681279174); d = HH(d, a, b, c, x[k + 0], S32, 3936430074); c = HH(c, d, a, b, x[k + 3], S33, 3572445317); b = HH(b, c, d, a, x[k + 6], S34, 76029189); a = HH(a, b, c, d, x[k + 9], S31, 3654602809); d = HH(d, a, b, c, x[k + 12], S32, 3873151461); c = HH(c, d, a, b, x[k + 15], S33, 530742520); b = HH(b, c, d, a, x[k + 2], S34, 3299628645); a = II(a, b, c, d, x[k + 0], S41, 4096336452); d = II(d, a, b, c, x[k + 7], S42, 1126891415); c = II(c, d, a, b, x[k + 14], S43, 2878612391); b = II(b, c, d, a, x[k + 5], S44, 4237533241); a = II(a, b, c, d, x[k + 12], S41, 1700485571); d = II(d, a, b, c, x[k + 3], S42, 2399980690); c = II(c, d, a, b, x[k + 10], S43, 4293915773); b = II(b, c, d, a, x[k + 1], S44, 2240044497); a = II(a, b, c, d, x[k + 8], S41, 1873313359); d = II(d, a, b, c, x[k + 15], S42, 4264355552); c = II(c, d, a, b, x[k + 6], S43, 2734768916); b = II(b, c, d, a, x[k + 13], S44, 1309151649); a = II(a, b, c, d, x[k + 4], S41, 4149444226); d = II(d, a, b, c, x[k + 11], S42, 3174756917); c = II(c, d, a, b, x[k + 2], S43, 718787259); b = II(b, c, d, a, x[k + 9], S44, 3951481745); a = addUnsigned(a, AA); b = addUnsigned(b, BB); c = addUnsigned(c, CC); d = addUnsigned(d, DD) } var tempValue = wordToHex(a) + wordToHex(b) + wordToHex(c) + wordToHex(d); return tempValue.toLowerCase() }; };
\ No newline at end of file // SDK接口通用参数
private SDKCOMMDATA: Object = {
source: "WEIXIN",
product_code: SDKConfig.productCode,
uuid: "",
equipmentos: "",
package_code: "",
time: "",
sign: "",
os: "",
version: this.sdkVersion,
};
// 米大师支付参数
private MidasPaymentParams = {
mode: "game", // 支付的类型
env: SDKConfig.midasPayEnv, // 米大师环境
currencyType: "CNY", // 币种
platform: "android", // 客户端平台
zoneId: "1", // 分区ID,默认1
offerId: SDKConfig.offerid,
};
private MidasErrorCode = {
"-1": "系统失败",
"-2": "支付取消",
"-15001": "缺少参数",
"-15002": "参数不合法",
"-15003": "订单重复",
"-15004": "后台错误",
"-15005": "appId权限被封禁",
"-15006": "货币类型不支持",
"-15007": "订单已支付",
"-15009": "由于健康系统限制,本次支付已超过限额",
"1": "用户取消支付",
"2": "客户端错误,判断到小程序在用户处于支付中时,又发起了一笔支付请求",
"3": "Android 独有错误:用户使用 Google Play 支付,而手机未安装 Google Play",
"4": "用户操作系统支付状态异常",
"5": "操作系统错误",
"6": "其他错误",
"1000": "参数错误",
"1003": "米大师Portal错误",
};
}
interface shareInfo {
title?: string;
image?: string;
imageId?: string;
query?: string;
success: any;
fail: any;
complete?: any;
}
interface RecorderInfo {
duration: number;
}
// SDK后端接口(勿改)
const Links = {
init: SDKConfig.sdk_domain + "/weixin/access_token.php", // 获取openid
active: SDKConfig.sdk_domain + "/appInit.php", // SDK初始化接口
login: SDKConfig.sdk_domain + "/login.php", // SDK登录接口,获取用户平台信息
order: SDKConfig.pay_domain + "/pay.php", //订单接口
pay: SDKConfig.pay_domain + "/notify/midas/pay.php", //扣费接口
payType: SDKConfig.pay_domain + "/pay_channel/status.php", // 查询支付状态
sendCode: SDKConfig.sdk_domain + "/sms/send.php", // 发送验证码
saveNum: SDKConfig.sdk_domain + "/bind/mobile.php", // 保存手机号码
playTime: SDKConfig.sdk_domain + "", // 获取用户在线时长
bindPhone: SDKConfig.sdk_domain + "/bind/is_bind_mobile.php", // 用户手机绑定状态
getActShareId: SDKConfig.active_domain + "/weixin/updatable_message/create_activity_id", // 获取活动消息id
setActShareInfo: SDKConfig.active_domain + "/weixin/updatable_message/updatablemsg", // 更新活动消息内容
getActShareInfo: SDKConfig.active_domain + "/weixin/updatable_message/get_activity", // 查询活动消息内容
paymentErrorReport: SDKConfig.sdk_domain + "/v2/analytics/event", // 上报支付错误信息
};
// md5加密
const rotateLeft = (lValue, iShiftBits) => {
return (lValue << iShiftBits) | (lValue >>> (32 - iShiftBits));
};
var addUnsigned = function (lX, lY) {
var lX4, lY4, lX8, lY8, lResult;
lX8 = lX & 2147483648;
lY8 = lY & 2147483648;
lX4 = lX & 1073741824;
lY4 = lY & 1073741824;
lResult = (lX & 1073741823) + (lY & 1073741823);
if (lX4 & lY4) {
return lResult ^ 2147483648 ^ lX8 ^ lY8;
}
if (lX4 | lY4) {
if (lResult & 1073741824) {
return lResult ^ 3221225472 ^ lX8 ^ lY8;
} else {
return lResult ^ 1073741824 ^ lX8 ^ lY8;
}
} else {
return lResult ^ lX8 ^ lY8;
}
};
var F = function (x, y, z) {
return (x & y) | (~x & z);
};
var G = function (x, y, z) {
return (x & z) | (y & ~z);
};
var H = function (x, y, z) {
return x ^ y ^ z;
};
var I = function (x, y, z) {
return y ^ (x | ~z);
};
var FF = function (a, b, c, d, x, s, ac) {
a = addUnsigned(a, addUnsigned(addUnsigned(F(b, c, d), x), ac));
return addUnsigned(rotateLeft(a, s), b);
};
var GG = function (a, b, c, d, x, s, ac) {
a = addUnsigned(a, addUnsigned(addUnsigned(G(b, c, d), x), ac));
return addUnsigned(rotateLeft(a, s), b);
};
var HH = function (a, b, c, d, x, s, ac) {
a = addUnsigned(a, addUnsigned(addUnsigned(H(b, c, d), x), ac));
return addUnsigned(rotateLeft(a, s), b);
};
var II = function (a, b, c, d, x, s, ac) {
a = addUnsigned(a, addUnsigned(addUnsigned(I(b, c, d), x), ac));
return addUnsigned(rotateLeft(a, s), b);
};
var convertToWordArray = function (string) {
var lWordCount;
var lMessageLength = string.length;
var lNumberOfWordsTempOne = lMessageLength + 8;
var lNumberOfWordsTempTwo = (lNumberOfWordsTempOne - (lNumberOfWordsTempOne % 64)) / 64;
var lNumberOfWords = (lNumberOfWordsTempTwo + 1) * 16;
var lWordArray = Array(lNumberOfWords - 1);
var lBytePosition = 0;
var lByteCount = 0;
while (lByteCount < lMessageLength) {
lWordCount = (lByteCount - (lByteCount % 4)) / 4;
lBytePosition = (lByteCount % 4) * 8;
lWordArray[lWordCount] = lWordArray[lWordCount] | (string.charCodeAt(lByteCount) << lBytePosition);
lByteCount++;
}
lWordCount = (lByteCount - (lByteCount % 4)) / 4;
lBytePosition = (lByteCount % 4) * 8;
lWordArray[lWordCount] = lWordArray[lWordCount] | (128 << lBytePosition);
lWordArray[lNumberOfWords - 2] = lMessageLength << 3;
lWordArray[lNumberOfWords - 1] = lMessageLength >>> 29;
return lWordArray;
};
var wordToHex = function (lValue) {
var WordToHexValue = "",
WordToHexValueTemp = "",
lByte,
lCount;
for (lCount = 0; lCount <= 3; lCount++) {
lByte = (lValue >>> (lCount * 8)) & 255;
WordToHexValueTemp = "0" + lByte.toString(16);
WordToHexValue = WordToHexValue + WordToHexValueTemp.substr(WordToHexValueTemp.length - 2, 2);
}
return WordToHexValue;
};
var uTF8Encode = function (string) {
string = string.replace(/\x0d\x0a/g, "\x0a");
var output = "";
for (var n = 0; n < string.length; n++) {
var c = string.charCodeAt(n);
if (c < 128) {
output += String.fromCharCode(c);
} else {
if (c > 127 && c < 2048) {
output += String.fromCharCode((c >> 6) | 192);
output += String.fromCharCode((c & 63) | 128);
} else {
output += String.fromCharCode((c >> 12) | 224);
output += String.fromCharCode(((c >> 6) & 63) | 128);
output += String.fromCharCode((c & 63) | 128);
}
}
}
return output;
};
function md5(string) {
var x = Array();
var k, AA, BB, CC, DD, a, b, c, d;
var S11 = 7,
S12 = 12,
S13 = 17,
S14 = 22;
var S21 = 5,
S22 = 9,
S23 = 14,
S24 = 20;
var S31 = 4,
S32 = 11,
S33 = 16,
S34 = 23;
var S41 = 6,
S42 = 10,
S43 = 15,
S44 = 21;
string = uTF8Encode(string);
x = convertToWordArray(string);
a = 1732584193;
b = 4023233417;
c = 2562383102;
d = 271733878;
for (k = 0; k < x.length; k += 16) {
AA = a;
BB = b;
CC = c;
DD = d;
a = FF(a, b, c, d, x[k + 0], S11, 3614090360);
d = FF(d, a, b, c, x[k + 1], S12, 3905402710);
c = FF(c, d, a, b, x[k + 2], S13, 606105819);
b = FF(b, c, d, a, x[k + 3], S14, 3250441966);
a = FF(a, b, c, d, x[k + 4], S11, 4118548399);
d = FF(d, a, b, c, x[k + 5], S12, 1200080426);
c = FF(c, d, a, b, x[k + 6], S13, 2821735955);
b = FF(b, c, d, a, x[k + 7], S14, 4249261313);
a = FF(a, b, c, d, x[k + 8], S11, 1770035416);
d = FF(d, a, b, c, x[k + 9], S12, 2336552879);
c = FF(c, d, a, b, x[k + 10], S13, 4294925233);
b = FF(b, c, d, a, x[k + 11], S14, 2304563134);
a = FF(a, b, c, d, x[k + 12], S11, 1804603682);
d = FF(d, a, b, c, x[k + 13], S12, 4254626195);
c = FF(c, d, a, b, x[k + 14], S13, 2792965006);
b = FF(b, c, d, a, x[k + 15], S14, 1236535329);
a = GG(a, b, c, d, x[k + 1], S21, 4129170786);
d = GG(d, a, b, c, x[k + 6], S22, 3225465664);
c = GG(c, d, a, b, x[k + 11], S23, 643717713);
b = GG(b, c, d, a, x[k + 0], S24, 3921069994);
a = GG(a, b, c, d, x[k + 5], S21, 3593408605);
d = GG(d, a, b, c, x[k + 10], S22, 38016083);
c = GG(c, d, a, b, x[k + 15], S23, 3634488961);
b = GG(b, c, d, a, x[k + 4], S24, 3889429448);
a = GG(a, b, c, d, x[k + 9], S21, 568446438);
d = GG(d, a, b, c, x[k + 14], S22, 3275163606);
c = GG(c, d, a, b, x[k + 3], S23, 4107603335);
b = GG(b, c, d, a, x[k + 8], S24, 1163531501);
a = GG(a, b, c, d, x[k + 13], S21, 2850285829);
d = GG(d, a, b, c, x[k + 2], S22, 4243563512);
c = GG(c, d, a, b, x[k + 7], S23, 1735328473);
b = GG(b, c, d, a, x[k + 12], S24, 2368359562);
a = HH(a, b, c, d, x[k + 5], S31, 4294588738);
d = HH(d, a, b, c, x[k + 8], S32, 2272392833);
c = HH(c, d, a, b, x[k + 11], S33, 1839030562);
b = HH(b, c, d, a, x[k + 14], S34, 4259657740);
a = HH(a, b, c, d, x[k + 1], S31, 2763975236);
d = HH(d, a, b, c, x[k + 4], S32, 1272893353);
c = HH(c, d, a, b, x[k + 7], S33, 4139469664);
b = HH(b, c, d, a, x[k + 10], S34, 3200236656);
a = HH(a, b, c, d, x[k + 13], S31, 681279174);
d = HH(d, a, b, c, x[k + 0], S32, 3936430074);
c = HH(c, d, a, b, x[k + 3], S33, 3572445317);
b = HH(b, c, d, a, x[k + 6], S34, 76029189);
a = HH(a, b, c, d, x[k + 9], S31, 3654602809);
d = HH(d, a, b, c, x[k + 12], S32, 3873151461);
c = HH(c, d, a, b, x[k + 15], S33, 530742520);
b = HH(b, c, d, a, x[k + 2], S34, 3299628645);
a = II(a, b, c, d, x[k + 0], S41, 4096336452);
d = II(d, a, b, c, x[k + 7], S42, 1126891415);
c = II(c, d, a, b, x[k + 14], S43, 2878612391);
b = II(b, c, d, a, x[k + 5], S44, 4237533241);
a = II(a, b, c, d, x[k + 12], S41, 1700485571);
d = II(d, a, b, c, x[k + 3], S42, 2399980690);
c = II(c, d, a, b, x[k + 10], S43, 4293915773);
b = II(b, c, d, a, x[k + 1], S44, 2240044497);
a = II(a, b, c, d, x[k + 8], S41, 1873313359);
d = II(d, a, b, c, x[k + 15], S42, 4264355552);
c = II(c, d, a, b, x[k + 6], S43, 2734768916);
b = II(b, c, d, a, x[k + 13], S44, 1309151649);
a = II(a, b, c, d, x[k + 4], S41, 4149444226);
d = II(d, a, b, c, x[k + 11], S42, 3174756917);
c = II(c, d, a, b, x[k + 2], S43, 718787259);
b = II(b, c, d, a, x[k + 9], S44, 3951481745);
a = addUnsigned(a, AA);
b = addUnsigned(b, BB);
c = addUnsigned(c, CC);
d = addUnsigned(d, DD);
}
var tempValue = wordToHex(a) + wordToHex(b) + wordToHex(c) + wordToHex(d);
return tempValue.toLowerCase();
}
Markdown 格式
0%
您添加了 0 到此讨论。请谨慎行事。
请先完成此评论的编辑!
注册 或者 后发表评论