From f76f173b7043b62a68f9292d2cea122219140a95 Mon Sep 17 00:00:00 2001 From: song Date: Mon, 7 Aug 2023 14:29:38 +0800 Subject: [PATCH] X --- sdk/Analytics.ts | 29 +++++++++++++++-------------- sdk/GameServicePlus.ts | 377 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ sdk/Ge.ts | 50 ++++++++++++++++++++++++++++++++++++++++++++++++++ sdk/SDKApiPlus.ts | 144 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ sdk/SDKHttpPlus.ts | 139 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ sdk/SDKTools.ts | 23 +++++++++++++++-------- sdk/SDKToolsPlus.ts | 420 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ sdk/WxHelper.ts | 534 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ sdk/shareTools.ts | 134 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++-------------- wxsdk/WXSDK.ts | 9 +++++---- wxsdk/alipay/AlipayApi.ts | 482 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ wxsdk/alipay/AlipayBanner.ts | 238 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ wxsdk/alipay/AlipayInterstitial.ts | 68 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ wxsdk/alipay/zfbPay.ts | 183 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ wxsdk/base/SDKBaseData.ts | 2 +- wxsdk/base/SDKConst.ts | 35 ++++++++++++++++++----------------- wxsdk/base/wx.d.ts | 3 ++- wxsdk/http/SDKApi.ts | 10 ++++++++++ wxsdk/http/SDKHttp.ts | 21 +++++++-------------- wxsdk/platform/wx/WxStorage.ts.meta | 14 +++++++------- wxsdk/service/AdService.ts | 5 +++-- wxsdk/service/DataService.ts | 2 +- wxsdk/service/GameService.ts | 46 ++++++++++++++++++++-------------------------- wxsdk/service/LogService.ts | 14 +++++++------- wxsdk/service/ShareVideoService.ts | 281 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++------------------ wxsdk/service/entity/SdkData.ts.meta | 14 +++++++------- wxsdk/service/entity/ShareData.ts.meta | 14 +++++++------- wxsdk/share/SDKShare.ts | 59 ++++++++++++++++++++++++++++++++++++++++++++++++++++------- wxsdk/share/SDKVideo.ts | 145 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++-------------------------------------------- wxsdk/utils/RandomUtils.ts | 3 ++- wxsdk/wx/WxApi.ts | 8 +++++--- wxsdk/wx/WxBanner.ts | 13 +++++++++---- wxsdk/wx/WxInit.ts | 7 ++++++- wxsdk/wx/WxLogin.ts | 44 +++++++++++++++++++++++++++++++++----------- wxsdk/wx/WxPay.ts | 5 +++-- wxsdk/wx/WxSystem.ts | 6 +++--- 36 files changed, 3357 insertions(+), 224 deletions(-) create mode 100644 sdk/GameServicePlus.ts create mode 100644 sdk/Ge.ts create mode 100644 sdk/SDKApiPlus.ts create mode 100644 sdk/SDKHttpPlus.ts create mode 100644 sdk/SDKToolsPlus.ts create mode 100644 sdk/WxHelper.ts create mode 100644 wxsdk/alipay/AlipayApi.ts create mode 100644 wxsdk/alipay/AlipayBanner.ts create mode 100644 wxsdk/alipay/AlipayInterstitial.ts create mode 100644 wxsdk/alipay/zfbPay.ts diff --git a/sdk/Analytics.ts b/sdk/Analytics.ts index 789dfca..2386d57 100644 --- a/sdk/Analytics.ts +++ b/sdk/Analytics.ts @@ -1,10 +1,12 @@ -import { LogLevel } from "../wxsdk/service/LogService"; -import WXSDK from "../wxsdk/WXSDK"; +import TAMgr from "../../framework/ta/TAMgr"; +import { SDKLogLevel } from "../../framework/wxsdk/service/LogService"; +import WXSDK from "../../framework/wxsdk/WXSDK"; + export class Analytics { private static _instance: Analytics; - private systemType: number + private systemType: number; static get I(): Analytics { return this._instance || (this._instance = new Analytics); } @@ -20,8 +22,14 @@ export class Analytics { // 游戏打点 dot(dot_type: string, data: any = {}) { - if (typeof wx == 'undefined') return - // wx.aldSendEvent(dot_type, data); //阿拉丁打点,没需求注释即可 + if (typeof wx == 'undefined'&&typeof my == 'undefined') { + console.log("dot", dot_type, data); + return + } + // 数数 + if (['receive_reward', 'button','merge_item','addToTempStore','talk','fund','mail','milktea','mail','activity_welcome','activity_raffle','activity_bp','piggy','invite','apple_tree','energy_cost','gem_cost','gold_cost','dress_cost','gem_output','gold_output','energy_output','exp_output','dress_output'].indexOf(dot_type) == -1) {// 排除部分key + TAMgr.Ins.dot(dot_type, data); + } return WXSDK.stat.dot(dot_type, data); } @@ -82,7 +90,7 @@ export class Analytics { * @param level 日志等级 * @returns */ - clientLog(content, level = LogLevel.debug) { + clientLog(content, level = SDKLogLevel.debug) { return WXSDK.stat.clientLog(content, level) } /** @@ -109,11 +117,4 @@ export class Analytics { } -} -export enum EventKey { - toggleScene = 'toggleScene', - recoverGame = 'recoverGame', - replayGame = 'replayGame', - settingClose = 'settingClose', - updateLvUI = 'updateLvUI', -} +} \ No newline at end of file diff --git a/sdk/GameServicePlus.ts b/sdk/GameServicePlus.ts new file mode 100644 index 0000000..f0e919e --- /dev/null +++ b/sdk/GameServicePlus.ts @@ -0,0 +1,377 @@ +import DataService from "../../framework/wxsdk/service/DataService"; +import GameService from "../../framework/wxsdk/service/GameService"; +import WxPay from "../../framework/wxsdk/wx/WxPay"; +import SDKApiPlus from "./SDKApiPlus"; + + + +export default class GameServicePlus extends GameService { + memberSave(content: string, params: any = {}) { + return SDKApiPlus.memberSave({ uid: DataService.I.UserId, token: DataService.I.Token, content, ...params }); + } + + memberGet() { + return SDKApiPlus.memberGet({ uid: DataService.I.UserId, token: DataService.I.Token }); + } + memberSesetAup() { + return SDKApiPlus.memberSesetAup({ uid: DataService.I.UserId, token: DataService.I.Token }); + } + + memberClear() { + return SDKApiPlus.memberClear({ uid: DataService.I.UserId, token: DataService.I.Token }); + } + + getGameNotice() { + return SDKApiPlus.notice(); + } + + mail() { + return SDKApiPlus.mail({ uid: DataService.I.UserId, token: DataService.I.Token }); + } + + /** + * 改变邮件状态 + * @param id id为0或不传id时为 一键领取、一键删除 + * @param status 1已读 2领取 3删除。如同时修改多个状态格式:1,2 + * @returns + */ + updateMailStatus(id: number, status: string) { + return SDKApiPlus.mailStatus({ id, status, uid: DataService.I.UserId, token: DataService.I.Token }); + } + + getQRcode() { + return SDKApiPlus.QRcode(); + } + + convertCDkey(cdkey: string) { + return SDKApiPlus.cdkey({ uid: DataService.I.UserId, token: DataService.I.Token, cdkey: cdkey }); + } + + clearData() { + return SDKApiPlus.clearData({ uid: DataService.I.UserId, token: DataService.I.Token }); + } + + goodsList() { + return SDKApiPlus.goodsList({ uid: DataService.I.UserId, token: DataService.I.Token }); + } + + createOrder(goodid: string) { + return SDKApiPlus.createOrder({ uid: DataService.I.UserId, token: DataService.I.Token, goodid }); + } + + queryOrder(no: string) { + return SDKApiPlus.queryOrder({ uid: DataService.I.UserId, token: DataService.I.Token, no }); + } + + confirmOrder(no: string) { + return SDKApiPlus.confirmOrder({ uid: DataService.I.UserId, token: DataService.I.Token, no }); + } + + /** + * 支付 + * @param params + * @param opts + * @returns + */ + pay(params: { payid: string, goodid: string, money: number; orderid: string }, opts: any = {}) { + return WxPay.I.pay(params, opts); + } + /** + * 订单查询 + */ + orderQuery(source) { + return SDKApiPlus.orderQuery({ + ...this.buildParams(), + source + }); + } + /** + * 订单查询 + */ + preorder(goodid: string, orderid: string) { + return SDKApiPlus.preorder({ + ...this.buildParams2(), + token: DataService.I.Token, + goodid, orderid + }); + } + + /** + * 获取玩家历史存档 + * @param uid + * @param token + */ + getUserHistory(uid: string, token: string) { + return SDKApiPlus.getUserHistory({ uid: uid, token: token }); + } + + /** + * 获取玩家历史存档 + * @param data //需要包含uid,token + */ + saveUserHistory(data: any) { + return SDKApiPlus.saveUserHistory(data); + } + + /** + * 重置GM标识 + */ + setAup(typ: number = 0) { + return SDKApiPlus.setAup({ uid: DataService.I.UserId, token: DataService.I.Token, typ }); + } + + /** + * 获取分享图片 + * @param items 2,1,0|3,1,1|3,1,1|3,1,1|3,1,1格式:2,1,0(类型,id,领取状态)领取状态:1已领取0未领取 + * @param zoom 图片缩放比例 + * @returns + */ + getShareImage(items: string, zoom: number = 1) { + return SDKApiPlus.getShareImg({ uid: DataService.I.UserId, token: DataService.I.Token, items, zoom }); + } + + /** + * 获取我的今日分享 + * @param refresh 是否刷新 + */ + getShare(refresh?: number) { + let req = { uid: DataService.I.UserId, token: DataService.I.Token }; + if (refresh) { + req['refresh'] = refresh; + } + return SDKApiPlus.getShare(req); + } + + /** + * 获取好友分享详情 + * @param id 分享id + * @param date 分享日期 格式:20220524 + */ + getShareInfo(id: number, date: string) { + return SDKApiPlus.getShareInfo({ uid: DataService.I.UserId, token: DataService.I.Token, id, date }); + } + + /** + * 领取好友分享 + * @param id 分享id + * @param date 分享日期 格式:20220524 + * @param itemid 分享选项ID + */ + getShareReward(id: number, date: string, itemid: number) { + return SDKApiPlus.receiveShare({ uid: DataService.I.UserId, token: DataService.I.Token, id, date, itemid }); + } + + /** + * 领取额外进度奖励 + * @param id 分享id + * @param date 分享日期 格式:20220524 + */ + getProgressReward(id: number, date: string) { + return SDKApiPlus.getProgressReward({ uid: DataService.I.UserId, token: DataService.I.Token, id, date }); + } + + saveStory(key: string, data: string) { + // return SDKApiPlus.saveStory({ + // id: UserManager.I.curStory.id, + // lv: UserManager.I.curStory.lv, + // fbid: UserManager.I.curStory.fbid, + // fbindex: UserManager.I.curStory.fbindex, + // data, + // uid: DataService.I.UserId, + // token: DataService.I.Token, + // }); + } + + /** + * 我的邀请详情 + * @returns + */ + getInviteInfo() { + return SDKApiPlus.getInviteInfo({ uid: DataService.I.UserId, token: DataService.I.Token }); + } + + /** + * 领取邀请奖励 + * @param id 挡位id + */ + receiveInvite(id: number) { + return SDKApiPlus.receiveInvite({ uid: DataService.I.UserId, token: DataService.I.Token, id }); + } + + /** + * 心跳 + */ + beatheart() { + return SDKApiPlus.heartbeat({ uid: DataService.I.UserId, token: DataService.I.Token }); + } + /** + * 周卡/月卡列表 + */ + recCardList() { + return SDKApiPlus.recCardList({ uid: DataService.I.UserId, token: DataService.I.Token }); + } + + /** + * 领取周卡/月卡奖励 + * @param typ 第几天 week周 month月 + */ + recCardReward(typ: string) { + return SDKApiPlus.recCardReward({ uid: DataService.I.UserId, token: DataService.I.Token, typ }); + } + + /** + * 领取基金列表 + */ + recGrowthList() { + return SDKApiPlus.recGrowthList({ uid: DataService.I.UserId, token: DataService.I.Token }); + } + + /** + * 领取基金列表 + * @param goodid 购买的基金商品ID + * @param level 等级 + */ + recGrowthReward(goodid: string, level: number) { + return SDKApiPlus.recGrowthReward({ uid: DataService.I.UserId, token: DataService.I.Token, goodid, level }); + } + + /** + * 获取无尽礼包数据 + */ + recEndlessList(groupId: string) { + return SDKApiPlus.recEndlessList({ uid: DataService.I.UserId, token: DataService.I.Token, group_id: groupId }); + } + + /** + * 领取无尽礼包 + */ + recEndlessReward(groupId: string, id: string, date: string) { + return SDKApiPlus.recEndlessReward({ uid: DataService.I.UserId, token: DataService.I.Token, group_id: groupId, id, date }); + } + + /** + * 获取新手礼包数据 + */ + getNewbieGiftData() { + return SDKApiPlus.getNewbieGiftData({ uid: DataService.I.UserId, token: DataService.I.Token }); + } + + /** + * 领取新手礼包 + * @param days 第几天 + */ + recNewbieGift(days: string) { + return SDKApiPlus.recNewbieGift({ uid: DataService.I.UserId, token: DataService.I.Token, days }); + } + + + /** + * 订阅消息 + * @param tmplId 订阅ID + * @param message 订阅内容 + * @param sendtime 订阅发送时间s二选一参数 + * @param times 订阅延迟时间s二选一参数 + * @param status 1取消以前相同模板信息,默认为0不取消 + */ + async sendSubScribe(tmplId: string, message: string, sendtime: number, times: number = 0, status: number = 1) { + let uid = +DataService.I.UserId; + let token = DataService.I.Token + ''; + let openid = DataService.I.OpenId + ''; + + let data = { + uid, + token, + openid, + status, + message: encodeURIComponent(message), + temid: tmplId + }; + if (times) { + data["times"] = times; + } else { + data["sendtime"] = Math.floor(sendtime); + } + let back = await SDKApiPlus.sendsubscribe(data) + return back; + } + + + /** + * 取消订阅消息 + * @param tmplId 订阅ID + */ + async cancelSubscribe(tmplId: string) { + let uid = +DataService.I.UserId; + let token = DataService.I.Token + ''; + let openid = DataService.I.OpenId + ''; + + let data = { + uid, + token, + openid, + temid: tmplId + }; + let back = await SDKApiPlus.cancelSubscribe(data) + return back; + } + /** + * 自定义活动 + * @param id 活动ID(后台的ID) + */ + activityCustom(id?: string) { + return SDKApiPlus.activityCustom({ id }); + } + + /** + * 添加排行榜 + * @param typ 游戏端自定义排行标识 + * @param fraction 分数 如果上报的分数小于以前上报的分数,则不会更新 + * @param rankData 扩展字段 + * @returns + */ + rankAddV2(typ: string, fraction: number, rankData?: string) { + return SDKApiPlus.rankAddV2({ typ, fraction, rankData, uid: DataService.I.UserId, token: DataService.I.Token }); + } + /** + * 排行榜列表 + * @param percent percent等于1 的时候会返回排行榜总人数和自己的当前排名 + */ + rankListV2(typ: string, percent: number = 0) { + return SDKApiPlus.rankListV2({ typ, percent, uid: DataService.I.UserId, token: DataService.I.Token }); + } + /** + * 活动排行榜配置 + * @param name 游戏端自定义排行标识 + */ + activityRankConfig(name: string) { + return SDKApiPlus.activityRankConfig({ name, uid: DataService.I.UserId, token: DataService.I.Token }); + } + /** + * 活动排行榜添加分数 + * @param name 游戏端自定义排行标识 + * @param score 分数 + * @param extend 扩展 + */ + activityRankAdd(name: string, score: number, extend: string) { + return SDKApiPlus.activityRankAdd({ name, score, extend, uid: DataService.I.UserId, token: DataService.I.Token }); + } + /** + * 活动排行榜 + * @param name 游戏端自定义排行标识 + */ + activityRankList(name: string) { + return SDKApiPlus.activityRankList({ name, uid: DataService.I.UserId, token: DataService.I.Token }); + } + /** + * 活动排行榜奖励 + * @param name 游戏端自定义排行标识 + */ + activityRankReward(name: string) { + return SDKApiPlus.activityRankReward({ name, uid: DataService.I.UserId, token: DataService.I.Token }); + } + + static instance: GameServicePlus; + static get I(): GameServicePlus { + return this.instance || (this.instance = new GameServicePlus()); + } +} \ No newline at end of file diff --git a/sdk/Ge.ts b/sdk/Ge.ts new file mode 100644 index 0000000..9781ec2 --- /dev/null +++ b/sdk/Ge.ts @@ -0,0 +1,50 @@ +import { sys } from "cc"; +import { GAMEDATA } from "../../framework/wxsdk/base/SDKConst"; +import { SDKToolsPlus } from "./SDKToolsPlus"; + + + +export class Ge { + private static _instance: GravityAnalyticsAPI; + static get I(): GravityAnalyticsAPI { + return this._instance; + } + constructor() { + } + + public static init() { + // console.log("ge初始化") + const config = { + accessToken: "ihcpiWLHTqDs5oZEGsnyxCrFXBaSeoju", // 项目通行证,在:网站后台-->管理中心-->应用列表中找到Access Token列 复制(首次使用可能需要先新增应用) + clientId: SDKToolsPlus.openId, // 用户唯一标识,如微信小程序的openid + autoTrack: { + appLaunch: true, // 自动采集 $MPLaunch + appShow: true, // 自动采集 $MPShow + appHide: true, // 自动采集 $MPHide + }, + name: "ge", // 全局变量名称 + // debugMode: "debug", // 是否开启测试模式,开启测试模式后,可以在 网站后台--管理中心--元数据--事件流中查看实时数据上报结果。(测试时使用,上线之后一定要关掉,改成none或者删除) + }; + let ge = new GravityAnalyticsAPI(config); + ge.init(); + let isFirst = sys.localStorage.getItem('tt_register'); + if (!isFirst) { + // 首次注册 + let arr = GAMEDATA.version.split("."); + let version = +(arr[0] + arr[1] + arr[2]); + ge.register({ + name: SDKToolsPlus.uid, + version, + wx_openid: SDKToolsPlus.openId, + wx_unionid: "", + }).then((success) => { + // console.log("注册成功", success); + sys.localStorage.setItem('tt_register', "1") + }).catch((fail) => { + // console.error("注册失败", fail) + }) + } + this._instance = ge; + } + +} \ No newline at end of file diff --git a/sdk/SDKApiPlus.ts b/sdk/SDKApiPlus.ts new file mode 100644 index 0000000..8a34960 --- /dev/null +++ b/sdk/SDKApiPlus.ts @@ -0,0 +1,144 @@ +import { SDKApi } from "../../framework/wxsdk/http/SDKApi"; +import DataService from "../../framework/wxsdk/service/DataService"; +import SDKHttpPlus from "./SDKHttpPlus"; + +export default class SDKApiPlus extends SDKApi { + //公告 + public static notice = (...args) => SDKHttpPlus.httpPost(DataService.I.GameApi, HostKeysPlus.notice, ...args); + //订阅 + public static sendsubscribe = (...args) => SDKHttpPlus.httpPost(DataService.I.GameApi, HostKeysPlus.sendsubscribe, ...args); + //取消订阅 + public static cancelSubscribe = (...args) => SDKHttpPlus.httpPost(DataService.I.GameApi, HostKeysPlus.cancelSubscribe, ...args); + //邮件 + public static mail = (...args) => SDKHttpPlus.httpPost(DataService.I.GameApi, HostKeysPlus.mail, ...args); + //邮件状态修改 + public static mailStatus = (...args) => SDKHttpPlus.httpPost(DataService.I.GameApi, HostKeysPlus.mailStatus, ...args); + //群二维码 + public static QRcode = (...args) => SDKHttpPlus.httpPost(DataService.I.GameApi, HostKeysPlus.QRcode, ...args); + //兑换码 + public static cdkey = (...args) => SDKHttpPlus.httpPost(DataService.I.GameApi, HostKeysPlus.cdkey, ...args); + //删除存档 + public static clearData = (...args) => SDKHttpPlus.httpPost(DataService.I.GameApi, HostKeysPlus.clearData, ...args); + //商品列表 + public static goodsList = (...args) => SDKHttpPlus.httpPost(DataService.I.GameApi, HostKeysPlus.goodsList, ...args); + //生成订单 + public static createOrder = (...args) => SDKHttpPlus.httpPost(DataService.I.GameApi, HostKeysPlus.createOrder, ...args); + //查询订单 + public static queryOrder = (...args) => SDKHttpPlus.httpPost(DataService.I.GameApi, HostKeysPlus.queryOrder, ...args); + //确认订单 + public static confirmOrder = (...args) => SDKHttpPlus.httpPost(DataService.I.GameApi, HostKeysPlus.confirmOrder, ...args); + //重置GM标识 + public static setAup = (...args) => SDKHttpPlus.httpPost(DataService.I.GameApi, HostKeysPlus.setAup, ...args); + //获取分享图片 + public static getShareImg = (...args) => SDKHttpPlus.httpPost(DataService.I.GameApi, HostKeysPlus.getShareImg, ...args); + //获取今日分享 + public static getShare = (...args) => SDKHttpPlus.httpPost(DataService.I.GameApi, HostKeysPlus.getShare, ...args); + //获取分享信息 + public static getShareInfo = (...args) => SDKHttpPlus.httpPost(DataService.I.GameApi, HostKeysPlus.getShreInfo, ...args); + //领取好友分享 + public static receiveShare = (...args) => SDKHttpPlus.httpPost(DataService.I.GameApi, HostKeysPlus.receiveShare, ...args); + //领取分享额外奖励 + public static getProgressReward = (...args) => SDKHttpPlus.httpPost(DataService.I.GameApi, HostKeysPlus.getProgressReward, ...args); + //保存副本 + public static saveStory = (...args) => SDKHttpPlus.httpPost(DataService.I.GameApi, HostKeysPlus.saveStory, ...args); + //我的邀请详情 + public static getInviteInfo = (...args) => SDKHttpPlus.httpPost(DataService.I.GameApi, HostKeysPlus.getInviteInfo, ...args); + //领取邀请奖励 + public static receiveInvite = (...args) => SDKHttpPlus.httpPost(DataService.I.GameApi, HostKeysPlus.receiveInvite, ...args); + + // 保存用户数据 + public static memberSave = (...args) => SDKHttpPlus.httpPost(DataService.I.GameApi, HostKeysPlus.memberSave, ...args); + // 获取用户数据 + public static memberGet = (...args) => SDKHttpPlus.httpPost(DataService.I.GameApi, HostKeysPlus.memberGet, ...args); + // 重置修改标识 + public static memberSesetAup = (...args) => SDKHttpPlus.httpPost(DataService.I.GameApi, HostKeysPlus.memberSesetAup, ...args); + // 清除用户数据 + public static memberClear = (...args) => SDKHttpPlus.httpPost(DataService.I.GameApi, HostKeysPlus.memberClear, ...args); + //心跳 + public static heartbeat = (...args) => SDKHttpPlus.httpPost(DataService.I.GameApi, HostKeysPlus.memberXT, ...args); + //自定义活动 + public static activityCustom = (...args) => SDKHttpPlus.httpPost(DataService.I.GameApi, HostKeysPlus.activityCustom, ...args); + public static rankAddV2 = (...args) => SDKHttpPlus.httpPost(DataService.I.GameApi, HostKeysPlus.rankAddV2, ...args); + public static rankListV2 = (...args) => SDKHttpPlus.httpPost(DataService.I.GameApi, HostKeysPlus.rankListV2, ...args); + + //周卡/月卡列表 + public static recCardList = (...args) => SDKHttpPlus.httpPost(DataService.I.GameApi, HostKeysPlus.recCardList, ...args); + //领取周卡/月卡奖励 + public static recCardReward = (...args) => SDKHttpPlus.httpPost(DataService.I.GameApi, HostKeysPlus.recCardReward, ...args); + //领取基金列表 + public static recGrowthList = (...args) => SDKHttpPlus.httpPost(DataService.I.GameApi, HostKeysPlus.recGrowthList, ...args); + //领取基金奖励 + public static recGrowthReward = (...args) => SDKHttpPlus.httpPost(DataService.I.GameApi, HostKeysPlus.recGrowthReward, ...args); + //获取无尽礼包数据 + public static recEndlessList = (...args) => SDKHttpPlus.httpPost(DataService.I.GameApi, HostKeysPlus.recEndlessList, ...args); + //领取无尽礼包 + public static recEndlessReward = (...args) => SDKHttpPlus.httpPost(DataService.I.GameApi, HostKeysPlus.recEndlessReward, ...args); + //获取新手礼包数据 + public static getNewbieGiftData = (...args) => SDKHttpPlus.httpPost(DataService.I.GameApi, HostKeysPlus.getNewbieGiftData, ...args); + //领取新手礼包 + public static recNewbieGift = (...args) => SDKHttpPlus.httpPost(DataService.I.GameApi, HostKeysPlus.recNewbieGift, ...args); + + // 活动排行榜相关 + public static activityRankConfig = (...args) => SDKHttpPlus.httpPost(DataService.I.GameApi, HostKeysPlus.activityRankConfig, ...args); + public static activityRankAdd = (...args) => SDKHttpPlus.httpPost(DataService.I.GameApi, HostKeysPlus.activityRankAdd, ...args); + public static activityRankList = (...args) => SDKHttpPlus.httpPost(DataService.I.GameApi, HostKeysPlus.activityRankList, ...args); + public static activityRankReward = (...args) => SDKHttpPlus.httpPost(DataService.I.GameApi, HostKeysPlus.activityRankReward, ...args); + + //后台 + public static getUserHistory = (...args) => SDKHttpPlus.backPost(DataService.I.GMApi, HostKeysPlus.getUserHistory, ...args); + public static saveUserHistory = (...args) => SDKHttpPlus.backPost(DataService.I.GMApi, HostKeysPlus.saveUserHistory, ...args); +} + + +export const HostKeysPlus = { + sendsubscribe: 'api/subscribe/event', //订阅 + cancelSubscribe: 'api/subscribe/event/cancel', //取消订阅 + notice: 'mods/notice/list', //公告 + mail: 'mods/mail/list', //邮件 + mailStatus: '/mods/mail/status/u', //修改邮件状态 + QRcode: 'game/merge/system', //群二维码 + cdkey: 'game/merge/cdkey', //兑换CDkey + clearData: 'game/merge/clear', //删除存档 + goodsList: 'game/merge/goodslist', //商品列表 + createOrder: 'game/merge/order/create', //生成订单 + queryOrder: 'game/merge/order/query', //查询订单 + confirmOrder: 'game/merge/order/give', //确认订单 + setAup: 'game/merge/aup', //重置GM标识 + getShareImg: 'game/merge/share/getimg', //分享图片 + getShare: 'game/merge/share/get', //获取今日分享(自己的) + getShreInfo: 'game/merge/share/info', //获取分享详情(别人的) + receiveShare: 'game/merge/share/receive', //领取分享奖励 + getProgressReward: 'game/merge/share/reward/progress', //获取分享奖励 + saveStory: 'game/merge/cp/save', //保存副本 + getInviteInfo: 'api/member/invite/info', //获取邀请信息 + receiveInvite: 'api/member/invite/receive', //领取邀请奖励 + + memberSave: 'yueliangdao/member/save', //存用户数据 + memberGet: 'yueliangdao/member/get', //取用户数据 + memberSesetAup: 'yueliangdao/member/reset/aup', //重置修改标识 + memberClear: '3ad7e4ab92ae2249/member/clear', //清除用户数据 4.11改 + memberXT: 'yueliangdao/member/xt', //心跳 + activityCustom: 'mods/activity/custom', //自定义活动 + rankListV2: 'mods/rank/permanent/list', //排行榜2023-4-24 + rankAddV2: 'mods/rank/permanent/add', //更新排行榜2023-4-24 + + + recCardList: '3ad7e4ab92ae2249/member/ship/info', //周卡/月卡列表 + recCardReward: '3ad7e4ab92ae2249/member/ship/draw', //领取周卡/月卡奖励 + recGrowthList: 'game/merge/growth/list', //领取基金列表 + recGrowthReward: 'game/merge/growth/rec', //领取基金奖励 + recEndlessList: '3ad7e4ab92ae2249/egift/show', //获取无尽礼包数据 + recEndlessReward: '3ad7e4ab92ae2249/egift/draw', //领取无尽礼包 + getNewbieGiftData: '3ad7e4ab92ae2249/novice/list', //获取新手礼包数据 + recNewbieGift: '3ad7e4ab92ae2249/novice/draw', //领取新手礼包 + + activityRankConfig: 'yueliangdao/activities/rank/config', //活动排行榜配置 + activityRankAdd: 'yueliangdao/activities/rank/add', //活动排行榜添加分数 + activityRankList: 'yueliangdao/activities/rank/top', //活动排行榜 + activityRankReward: 'yueliangdao/activities/rank/draw', //活动排行榜奖励 + + + //后台 + getUserHistory: 'index/merge/history.html', //获取用户历史存档 + saveUserHistory: 'index/merge/setdata.html', //覆盖用户数据 +} diff --git a/sdk/SDKHttpPlus.ts b/sdk/SDKHttpPlus.ts new file mode 100644 index 0000000..df35708 --- /dev/null +++ b/sdk/SDKHttpPlus.ts @@ -0,0 +1,139 @@ +import { DEBUG } from "cc/env"; +import { GAMEDATA, sdkEnv } from "../../framework/wxsdk/base/SDKConst"; +import SDKHttp from "../../framework/wxsdk/http/SDKHttp"; +import { WxHelper } from "./WxHelper"; +import LogService from "../../framework/wxsdk/service/LogService"; +import DataService from "../../framework/wxsdk/service/DataService"; + +sdkEnv.isDebug = DEBUG; +export default class SDKHttpPlus extends SDKHttp { + + public static async backRequest(url: string, method: string, data?: any, dataType: "json" | "string" = "json") { + return new Promise>((resolve, reject) => { + data = { + ...data, + gameid: GAMEDATA.game_id, + } + + if (data && typeof data === "object") { + data = JSON.stringify(data); + } + data = data || ""; + if (method == "GET" && data != "") { + data = JSON.parse(data); + let str = '' + for (let key in data) { + str = str + `${key}` + '=' + `${data[key]}&` + } + url += "?" + str; + data = ""; + } + // let info = "[url:" + url + ", data:" + data + "]"; + // console.error("info", info) + let xhr = new XMLHttpRequest(); + xhr.onreadystatechange = function () { + if (xhr.readyState == 4) { + if (xhr.status >= 200 && xhr.status < 400) { + let responseText: any = xhr.responseText; + // cc.log("responseText", responseText) + try { + responseText = JSON.parse(responseText); + // cc.log("responseText22", responseText) + if (url.indexOf('.json') > -1) { + resolve({ code: 0, data: responseText, msg: responseText.msg }); + } else { + resolve({ code: +responseText.code, data: responseText.data, msg: responseText.msg }); + } + return + } catch (ex) { + // console.error("httpRequest[parseError]:responseText=" + xhr.responseText); + resolve({ msg: "JSON parse error:" + ex.message, code: -1 }); + return; + } + } else { + console.error(xhr.status, '网络请求失败!'); + resolve({ code: -2 }); + } + } + }; + + xhr.ontimeout = function (info): void { + console.error("info1", info) + resolve({ msg: `请求超时!`, code: -3 }); + } + xhr.onerror = function (info): void { + console.error("info2", info) + resolve({ msg: `请求失败!`, code: -4 }); + } + xhr.onabort = function (info): void { + console.error("info3", info) + resolve({ msg: `请求关闭!`, code: -5 }); + } + + xhr.timeout = 30000; + xhr.open(method, url, true); + + if (method == "POST") { + xhr.setRequestHeader("Content-Type", "application/json;charset=utf-8")//application/x-www-form-urlencoded + // if (cc.sys.os === 'Android') { + // cc.error("http__uid", AppSdkData.I.uid); + // xhr.setRequestHeader('Uuid', `${AppSdkData.I.uid}`); + // } else { + // xhr.setRequestHeader('Uuid', `909`); + // } + + } + console.log("data", data) + xhr.send(data); + }); + } + + public static async backGet(baseUrl: string, url: string, data?: any, dataType: "json" | "string" = "json") { + if (this.withMock(url)) { + return this.mockData(url); + } + + url = baseUrl + url; + return this.backRequest(url, "GET", data, dataType); + } + + public static backPost(baseUrl: string, url: string, data?: any, dataType: "json" | "string" = "json") { + if (this.withMock(url)) { + return this.mockData(url); + } + + url = baseUrl + url; + return this.backRequest(url, "POST", data, dataType); + } +} + +SDKHttp.onErrorResponse = async function (data: any) { + console.log("onErrorResponse", data) + if (data.code > 0) { + LogService.I.dot("errCode", { form: data.code + "_" + DataService.I?.Data?.userId }) + } else { + LogService.I.dot("errCode", { form: data.code }) + } + if (data.code == 1008) { + let ret = await WxHelper.showModal({ + title: '登录验证失败,请重新登录', + content: data.msg, + showCancel: false, + confirmText: '重启' + }) + if (ret) { + WxHelper.restartMiniProgram(); + } + } + if (data.code == 1011000) { + let ret = await WxHelper.showModal({ + title: '数据被修改', + content: data.msg, + showCancel: false, + confirmText: '重启' + }) + if (ret) { + WxHelper.restartMiniProgram(); + } + } +}; \ No newline at end of file diff --git a/sdk/SDKTools.ts b/sdk/SDKTools.ts index 0c4bd6c..211be1a 100644 --- a/sdk/SDKTools.ts +++ b/sdk/SDKTools.ts @@ -1,6 +1,7 @@ -import { GAMEDATA } from "../wxsdk/base/SDKConst"; -import DateUtils from "../wxsdk/utils/DateUtils"; -import WXSDK from "../wxsdk/WXSDK"; +import { GAMEDATA } from "../../framework/wxsdk/base/SDKConst"; +import DateUtils from "../../framework/wxsdk/utils/DateUtils"; +import WXSDK from "../../framework/wxsdk/WXSDK"; + /* * SDK工具类库; @@ -9,6 +10,9 @@ export class SDKTools { static get isWx() { return typeof wx !== 'undefined'; } + static get isZfb() { + return typeof my !== 'undefined'; + } static get isSupported() { return typeof WXSDK === 'object'; } @@ -79,7 +83,7 @@ export class SDKTools { * isOff:是否关闭默认显示banner * } */ - static createBanner(adUnitId: string = GAMEDATA.bannerId, opts?: { type?: number; bannerWidth?: number, offsetY?: number; adIntervals?: number, isOff?: boolean }) { + static createBanner(adUnitId: string = GAMEDATA.bannerId, opts?: { type?: number; bannerWidth?: number, offsetY?: number; adIntervals?: number, isOff?: boolean ,isCreate?:boolean}) { if (!this.isWx) return return WXSDK.ad.createBanner(adUnitId, opts); } @@ -163,11 +167,12 @@ export class SDKTools { /** * 订阅 * @param template_ids 模板id eg['aaaaaaa','bbbbbbb'] - * @param ids 对应后台的id eg:['1','2'] + * @param success 成功回调 + * @param fail 失败回调 */ - static subScribe(template_ids: Array, ids: Array) { - if (!this.isWx) return - return WXSDK.game.subScribe(template_ids, ids) + static subScribe(template_ids: Array, success: Function, fail: Function) { + if (!window['wx']) return; + return WXSDK.game.subScribe(template_ids, success, fail); } /** @@ -348,6 +353,7 @@ export class SDKTools { static checkmsg(scene: number, content: string, nickname?: string, title?: string, signature?: string) { return WXSDK.game.checkmsg(scene, content, nickname, title, signature) } + /** * 修改用户头像昵称 */ @@ -355,6 +361,7 @@ export class SDKTools { return WXSDK.game.updateNickname(nickname, headurl) } + } /** diff --git a/sdk/SDKToolsPlus.ts b/sdk/SDKToolsPlus.ts new file mode 100644 index 0000000..538abd8 --- /dev/null +++ b/sdk/SDKToolsPlus.ts @@ -0,0 +1,420 @@ +import { sys } from "cc"; +import { EventCenter } from "../../framework/core/utils/EventCenter"; +import { EnvCode } from "../../framework/wxsdk/base/SDKEnum"; +import DataService from "../../framework/wxsdk/service/DataService"; +import { GameEvent } from "../../game/const/GameEvent"; +import GameServicePlus from "./GameServicePlus"; +import { SDKTools } from "./SDKTools"; + +export class ServerError { + private static _errors = { + "0": { msg: "成功", desc: "接口调用成功" }, + "1000": { msg: "操作失败", desc: "检查Hermes后台配置是否正确" }, + "1001": { msg: "未知错误", desc: "联系开发人员排查错误" }, + "1002": { msg: "参数错误", desc: "请参照接口文档对比参数和参数类型是否正确" }, + "1003": { msg: "签名错误", desc: "检查appkey跟后台是否对应" }, + "1004": { msg: "数据不存在", desc: "查询的数据不存在等" }, + "1005": { msg: "解析参数失败,请检查参数合法性", desc: "参数中是否有危险字符,比如SQL注入等" }, + "4500": { msg: "商品不存在", desc: "检查Hermes后台配置是否正确" }, + "4501": { msg: "订单未支付", desc: "" }, + "4502": { msg: "不能重复发放", desc: "" }, + "4503": { msg: "兑换码不存在", desc: " " }, + "4504": { msg: "兑换码不在有效期内", desc: " " }, + "4505": { msg: "兑换码已失效", desc: " " }, + "4506": { msg: "iv error", desc: "防止用户本地修改数据" }, + "4507": { msg: "数据被修改", desc: "用户数据被GM工具修改,需重新登录重置" }, + "4508": { msg: "此商品已达到最大购买限制", desc: "限购" }, + "4509": { msg: "没有上传文件", desc: "检查文件name属性是否正确" }, + "4510": { msg: "文件超出最大限制", desc: "最大1M" }, + "4511": { msg: "请先授权获取微信头像信息", desc: "登录接口获取" }, + "4513": { msg: "没有达到刷新条件", desc: "生成过一次且没有领取 才可刷新" }, + "4514": { msg: "刷新次数超限", desc: "刷新次数达到 配置最大项" }, + "4515": { msg: "分享失效", desc: "跨天失效等" }, + "4516": { msg: "分享不存在", desc: "分享ID不存在等" }, + "4517": { msg: "已被领取", desc: "被其他人领取" }, + "4518": { msg: "今日领取次数超限", desc: "今天领取的次数达到配置最大项" }, + "4519": { msg: "已领过其他选项", desc: "只能领取一个" }, + "4520": { msg: "没有达到领取条件", desc: "领取进度是否完成" }, + "4522": { msg: "只能领取自己的奖励", desc: "" }, + "1009": { msg: "您的账号已因数据异常而被封禁,如需申诉可以向微信客服反馈。", desc: "" }, + "3004": { msg: "活动已经结束", desc: "" }, + } + + private static _unknownError = { msg: "未知错误", desc: "联系开发人员排查错误" }; + static getError(code: string): { msg: string, desc: string } { + return this._errors[code] || this._unknownError; + } + + static this(key: string): string { + return (this._errors[key] || this._unknownError).msg; + } +} + +/* +* SDK工具类库; +*/ +export class SDKToolsPlus extends SDKTools { + static get isTT() { + return sys.platform == sys.Platform.BYTEDANCE_MINI_GAME; + } + + //提交订单 + static doPreorder(data, goodid: string, price: number, orderid: string) { + if (!data.code && data.data) { + let { config, paytype } = data.data; + // goodid = goodid + ""; + // console.log("支付方式"+paytype); + switch (paytype) { + case "1"://H5 客服消息支付,游戏内调用发片消息接口 sendMessagePath:path + var { img, title, path } = config; + wx.openCustomerServiceConversation({ + showMessageCard: true, //是否显示会话内消息卡片,设置此参数为 true,用户进入客服会话会在右下角显示"可能要发送的小程序"提示,用户点击后可以快速发送小程序消息 + sendMessageTitle: title ? title : '我要充值!',//会话内消息卡片标题 + sendMessagePath: path,//会话内消息卡片路径//channel=${SDKTools.ChannelId}&item=10&uid=${SDKTools.UserId} + sendMessageImg: img ? img : 'https://wxsdk-cdn.miso-lab.com/moon-island/share/fx_chongzhi.jpg',//会话内消息卡片图片路径 + success: (ret) => { + //记录状态 + //onshow检测状态,判断是否充值成功 + console.log("支付成功:", ret); + EventCenter.I.emit(GameEvent.PAY_POLLING, true); + }, + fail: (ret) => { + console.log("fail", ret); + EventCenter.I.emit(GameEvent.PAY_FAIL, orderid, goodid); + } + }) + break; + case "2": + + + break; + case "3"://米大师支付,游戏支付成功需要调用米大师订单上报接口 + var { payid } = config; + SDKTools.pay({ payid, goodid, money: price, orderid: orderid }).then(res => { + if (!res.code) { + console.log("支付成功", res); + EventCenter.I.emit(GameEvent.PAY_CONFIRM, orderid, goodid); + } else { + console.log("支付失败", res); + EventCenter.I.emit(GameEvent.PAY_FAIL, orderid, goodid); + } + }).catch(err => { + console.log("支付失败2:", err); + EventCenter.I.emit(GameEvent.PAY_FAIL, orderid, goodid); + }) + break; + case "4"://跳转小程序支付,游戏直接跳转返回的小程序路径 + var { appid, page } = config; + wx.navigateToMiniProgram({ + appId: appid, + path: page, + envVersion: DataService.I.EnvEnum === EnvCode.Prod ? 'release' : "trial",//opts.envVersion || 'release', + success(res: any) { + console.log("成功:", res) + // resolve(res); + EventCenter.I.emit(GameEvent.PAY_POLLING, true); + }, + fail(err: any) { + console.log("失败", err) + EventCenter.I.emit(GameEvent.PAY_FAIL, orderid, goodid); + // reject(err); + } + }); + break; + case "5"://扫码小程序支付,imgurl为二维码地址,提示用户扫码即可 + EventCenter.I.emit(GameEvent.PAY_POLLING, true); + var { imgurl } = config; + wx.previewImage({ + current: imgurl, // 当前显示图片的http链接 + urls: [imgurl] // 需要预览的图片http链接列表 + }) + + break; + case "6"://二维码支付,windows下需要调用扫码支付接口 + EventCenter.I.emit(GameEvent.PAY_POLLING, true); + var { qrcode } = config; + wx.previewImage({ + current: qrcode, // 当前显示图片的http链接 + urls: [qrcode] // 需要预览的图片http链接列表 + }) + + break; + case "7"://抖音支付 + var { payid } = config; + SDKTools.pay({ payid, goodid, money: price, orderid: orderid }).then(res => { + if (!res.code) { + console.log("支付成功", res); + EventCenter.I.emit(GameEvent.PAY_CONFIRM, orderid, goodid); + } else { + console.log("支付失败", res); + EventCenter.I.emit(GameEvent.PAY_FAIL, orderid, goodid); + } + }).catch(err => { + console.log("支付失败", err); + EventCenter.I.emit(GameEvent.PAY_FAIL, orderid, goodid); + }) + break; + case "10"://支付宝支付 + var { payid } = config; + SDKTools.pay({ payid, goodid, money: price, orderid: orderid }).then(res => { + if (!res.code) { + console.log("111tttttt"+Date.now()); + EventCenter.I.emit(GameEvent.PAY_POLLING_NOW, true); + } else { + console.log("支付失败", JSON.stringify(res)); + EventCenter.I.emit(GameEvent.PAY_FAIL, orderid, goodid); + } + }).catch(err => { + console.log("支付失败", JSON.stringify(err)); + EventCenter.I.emit(GameEvent.PAY_FAIL, orderid, goodid); + }) + break; + default: + // utils.tips("出错!") + break; + } + } else { + // utils.tips("出错!") + } + } + + /** + * 获取群二维码 + */ + static QRcode() { + return GameServicePlus.I.getQRcode(); + } + + /** + * 兑换CDK + */ + static convertCDkey(cdkey: string) { + return GameServicePlus.I.convertCDkey(cdkey); + } + + /** + * 商品列表 + */ + static goodsList() { + return GameServicePlus.I.goodsList(); + } + + /** + * 生成订单 + */ + static createOrder(goodid: string) { + return GameServicePlus.I.createOrder(goodid); + } + + /** + * 查询订单 + */ + static queryOrder(no: string) { + return GameServicePlus.I.queryOrder(no); + } + + /** + * 确认订单 + */ + static confirmOrder(no: string) { + return GameServicePlus.I.confirmOrder(no); + } + + /** + * 获取玩家历史存档 + */ + static getUserHistory(uid: string, token: string) { + return GameServicePlus.I.getUserHistory(uid, token); + } + + /** + * 获取玩家历史存档 + * @param data //需要包含uid,token + */ + static saveUserHistory(data: any) { + return GameServicePlus.I.saveUserHistory(data); + } + + /** + * 重置GM标识 + */ + static setAup(typ: number = 0) { + return GameServicePlus.I.setAup(typ); + } + + /** + * 获取分享图片 + * @param items 2,1,0|3,1,1|3,1,1|3,1,1|3,1,1格式:2,1,0(类型,id,领取状态)领取状态:1已领取0未领取 + * @param zoom 图片缩放比例 + * @returns + */ + static getShareImage(items: string, zoom = 1) { + return GameServicePlus.I.getShareImage(items, zoom); + } + + /** + * 获取今日分享 + * @param refresh 是否刷新 + */ + static getShare(refresh?: number) { + return GameServicePlus.I.getShare(refresh); + } + + /** + * 获取分享详情 + * @param id 分享id + * @param date 分享日期 格式:20220524 + */ + static getShareInfo(id: number, date: string) { + if (typeof id === "string") { + id = parseInt(id); + } + return GameServicePlus.I.getShareInfo(id, date); + } + + /** + * 领取好友分享 + * @param id 分享id + * @param date 分享日期 格式:20220524 + * @param itemid 分享选项ID + */ + static getShareReward(id: number, date: string, itemid: number) { + if (typeof id === "string") { + id = parseInt(id); + } + return GameServicePlus.I.getShareReward(id, date, itemid); + } + + /** + * 领取额外进度奖励 + * @param id 分享id + * @param date 分享日期 格式:20220524 + */ + static getProgressReward(id: number, date: string) { + if (typeof id === "string") { + id = parseInt(id); + } + return GameServicePlus.I.getProgressReward(id, date); + } + + static getInviteInfo() { + return GameServicePlus.I.getInviteInfo(); + } + + static receiveInvite(id: number) { + return GameServicePlus.I.receiveInvite(id); + } + + static heartbeat() { + return GameServicePlus.I.beatheart(); + } + + /** + * 领取列表 + * @param status 类型1周卡2月卡 + */ + static recCardList() { + return GameServicePlus.I.recCardList(); + } + + /** + * 领取列表 + * @param typ 第几天 week周 month月 + */ + static recCardReward(typ: string) { + return GameServicePlus.I.recCardReward(typ); + } + + /** + * 领取基金列表 + */ + static recGrowthList() { + return GameServicePlus.I.recGrowthList(); + } + + /** + * 领取基金列表 + * @param goodid 购买的基金商品ID + * @param level 等级 + */ + static recGrowthReward(goodid: string, level: number) { + return GameServicePlus.I.recGrowthReward(goodid, level); + } + + /** + * 获取无尽礼包数据 + */ + static recEndlessList(groupId: string) { + return GameServicePlus.I.recEndlessList(groupId); + } + + /** + * 领取无尽礼包 + * @param date 当前日期 + */ + static recEndlessReward(groupId: string, id: string, date: string) { + return GameServicePlus.I.recEndlessReward(groupId, id, date); + } + + /** + * 获取新手礼包数据 + */ + static getNewbieGiftData() { + return GameServicePlus.I.getNewbieGiftData(); + } + + /** + * 领取新手礼包 + * @param days 当前天 + */ + static recNewbieGift(days: string) { + return GameServicePlus.I.recNewbieGift(days); + } + + + /** + * 订阅消息 + * @param tmplId 订阅ID + * @param message 订阅内容 + * @param sendtime 订阅发送时间s二选一参数 + * @param times 订阅延迟时间s二选一参数 + * @param status 1取消以前相同模板信息,默认为0不取消 + */ + static async sendSubScribe(tmplId: string, message: string, sendtime: number, times: number = 0, status = 1) { + return GameServicePlus.I.sendSubScribe(tmplId, message, sendtime, times, status); + } + + /** + * 取消订阅消息 + * @param tmplId 订阅ID + */ + static async cancelSubscribe(tmplId: string) { + return GameServicePlus.I.cancelSubscribe(tmplId); + } + /** + * 自定义活动 + * @param id 活动ID(后台的ID) + */ + static activityCustom(id?: string) { + return GameServicePlus.I.activityCustom(id); + } + /** + * 添加排行榜 + * @param typ 游戏端自定义排行标识 + * @param fraction 分数 如果上报的分数小于以前上报的分数,则不会更新 + * @param rankData 扩展字段 + * @returns + */ + static rankAddV2(typ: string, fraction: number, rankData?: string) { + return GameServicePlus.I.rankAddV2(typ, fraction, rankData); + } + /** + * 排行榜列表 + * @param typ 游戏端自定义排行标识 + * @param percent percent等于1 的时候会返回排行榜总人数和自己的当前排名 + */ + static rankListV2(typ: string, percent: number = 0) { + return GameServicePlus.I.rankListV2(typ, percent); + } + +} \ No newline at end of file diff --git a/sdk/WxHelper.ts b/sdk/WxHelper.ts new file mode 100644 index 0000000..5bd12a6 --- /dev/null +++ b/sdk/WxHelper.ts @@ -0,0 +1,534 @@ + +// import UserManager from "../manager/UserManager"; + +import { Node, UITransform, game, view } from "cc"; +import { ALIPAY } from "cc/env"; + +/** WXapi */ +export class WxHelper { + + /** 手机设备信息 */ + public static SystemInfo: SystemInfoSyncReturnValue; + + /** 微信用户信息 */ + public static userInfo: WxUserInfo; + static get isWx() { + return typeof wx !== 'undefined'; + } + + /** 获取设备信息 */ + public static getSystemInfo() { + if (this.isWx) this.SystemInfo = wx.getSystemInfoSync(); + } + + /** 像开放数据域发送信息 */ + public static postMessage(eventType: string, data?: any): void { + if (!this.isWx || !this.checkVerison('1.9.92')) return; + wx.getOpenDataContext().postMessage({ + eventType: eventType, + data: data + }); + + } + + /** 更新微信开放数据榜单数据 */ + public static updateWxRank(key: string, value: number) { + if (typeof my != 'undefined') { + return; + } + if (!this.isWx || !this.checkVerison('1.9.92')) return; + let data = { + value, + } + wx.setUserCloudStorage({ + KVDataList: [{ + key, + value: JSON.stringify(data) + }] + }) + + } + + /** 创建用户反馈按钮 */ + public static createFeedbackButton(target: Node) { + + let data = this.computWxPosition(target); + return wx.createFeedbackButton({ + type: 'text', + text: ' ', + style: { + left: data.left, + top: data.top, + width: data.width, + height: data.height, + borderRadius: 5, + // backgroundColor: '#69c66d', + } + }) + + } + + + /** 获取用户信息按钮 */ + public static userInfoButton: any; + /** 创建一个获取用户信息按钮 */ + public static createUserInfoButton(target: Node) { + let data = this.computWxPosition(target); + // console.log("data", data) + return wx.createUserInfoButton({ + type: 'text', + text: ' ', + style: { + left: data.left, + top: data.top, + width: data.width, + height: data.height, + borderRadius: 5, + // color: '#ffffff', + // backgroundColor: '#69c66d', + // textAlign: 'center', + // fontSize: 20, + // lineHeight: 45, + }, + withCredentials: true + }) + + } + + /** 计算微信坐标 */ + public static computWxPosition(target: Node): { left: number, top: number, width: number, height: number } { + + let data = { left: 0, top: 0, width: 0, height: 0 } + let pos = target.worldPosition; + let width = target.getComponent(UITransform).width; + let height = target.getComponent(UITransform).height; + let ratio = view.getDevicePixelRatio(); + let scale = view.getScaleX(); + let factor = scale / ratio; + // let point = cc.v2(rect.x, rect.y); + // point.mulSelf(scale); + data.left = (pos.x - width / 2) * factor; + data.top = wx.getSystemInfoSync().screenHeight - (pos.y + height / 2) * factor; + data.width = width * factor; + data.height = height * factor; + + // let btnSize = cc.size(target.width + 10, target.height + 10); + // let frameSize = cc.view.getFrameSize(); + // let winSize = cc.director.getWinSize(); + // // cc.log("winSize: ",winSize); + // // cc.log("frameSize: ",frameSize); + // //适配不同机型来创建微信按钮 + // data.left = (winSize.width * 0.5 + target.x - btnSize.width * 0.5) / winSize.width * frameSize.width; + // data.top = (winSize.height * 0.5 - target.y - btnSize.height * 0.5) / winSize.height * frameSize.height; + // data.width = btnSize.width / winSize.width * frameSize.width; + // data.height = btnSize.height / winSize.height * frameSize.height; + // cc.log("button pos: ",cc.v2(left,top)); + // cc.log("button size: ",cc.size(width,height)); + + // cc.log(data) + return data; + + } + + + /** 兼容方式 - 版本比较 */ + public static compareVersion(versionA: any, versionB: any) { + versionA = versionA.split('.'); + versionB = versionB.split('.'); + let len = Math.max(versionA.length, versionB.length); + + while (versionA.length < len) { + versionA.push('0'); + } + while (versionB.length < len) { + versionB.push('0'); + } + + for (let i = 0; i < len; i++) { + let num1 = parseInt(versionA[i]); + let num2 = parseInt(versionB[i]); + + if (num1 > num2) { + return 1; + } else if (num1 < num2) { + return -1; + } + } + + return 0; + } + + /** 当前版本是否能使用接口 */ + public static checkVerison(version: string): boolean { + return this.compareVersion(this.SystemInfo.SDKVersion, version) >= 0; + } + + /** 显示一个对话框 */ + public static showModal(data: ShowModalType) { + if (typeof my != 'undefined') { + return new Promise((resolve, reject) => { + wx.confirm({ + ...data, + success: (res: { confirm: boolean, cancel: boolean }) => { + if (res.confirm) { + resolve(true); + } else { + resolve(false); + } + }, + fail: () => { + reject(); + } + + }); + + }); + } + + return new Promise((resolve, reject) => { + + if (typeof wx !== 'undefined') { + wx.showModal({ + ...data, + success: (res: { confirm: boolean, cancel: boolean }) => { + if (res.confirm) { + resolve(true); + } else { + resolve(false); + } + }, + fail: () => { + reject(); + } + + }); + } else { + console.log(JSON.stringify(data)); + } + + }); + + } + + /** + * 显示一个提示层 + * @param msg 显示信息 + * @param time 关闭时间 + */ + public static showToast(msg: string, time: number = 1500) { + if (!this.isWx) return; + if (typeof my != 'undefined') { + my.showToast({ + type: 'none', + content: msg, + duration: time, + }); + return; + } + wx.showToast({ + title: msg, + icon: 'none', + duration: time + }) + + } + + /** 设置系统剪贴板的内容 */ + public static copy(str: string) { + if (!this.checkVerison('1.1.0')) return Promise.reject(''); + if (typeof my != 'undefined') { + return new Promise((resolve, reject) => { + wx.setClipboard({ + text: str, + success: (res: any) => { + resolve(res); + }, + fail: () => { + resolve(''); + } + }); + }); + } + return new Promise((resolve, reject) => { + wx.setClipboardData({ + data: str, + success: (res: any) => { + resolve(res); + }, + fail: () => { + resolve(''); + } + }); + }); + } + + /** 手机发生较长时间的振动(400 ms) */ + public static vibrateLong() { + if (!this.checkVerison('1.2.0')) return Promise.reject(null); + + return new Promise((resolve, reject) => { + wx.vibrateLong({ + success: () => { + resolve(1); + }, + fail: () => { + resolve(0); + } + }); + }); + } + + /** 手机发生较短时间的振动(15 ms) */ + public static vibrateShort() { + if (!this.checkVerison('1.2.0')) return Promise.reject(null); + + return new Promise>((resolve, reject) => { + wx.vibrateShort({ + success: () => { + resolve({ code: 0 }); + }, + fail: () => { + resolve({ code: 1 }); + } + }); + }); + } + + /** + * 检测更新 + */ + public static checkUpdate(bol: boolean = true) { + if (!this.checkVerison('1.9.90')) return; + const updateManager = wx.getUpdateManager(); + updateManager.onCheckForUpdate(function (res) { + console.log('updateManager', res.hasUpdate); + }); + + updateManager.onUpdateReady(function () { + wx.showModal({ + title: '更新提示', + content: '新版本已经准备好,请重启应用!', + showCancel: bol, + success: function (res) { + if (res.confirm) { + updateManager.applyUpdate() + } + } + }); + }); + updateManager.onUpdateFailed(function () { + // 新的版本下载失败 + }); + } + + /** 发送客服信息 */ + public static openCustomerServiceConversation() { + + return new Promise>((resolve, reject) => { + if (!this.checkVerison('2.0.3')) resolve({ code: 1 }); + wx.openCustomerServiceConversation({ + showMessageCard: true, + sendMessageTitle: '我要更多好玩!', + sendMessageImg: 'http://dep.miso-lab.com/tetrischangeskin/bin/share/concat.png', + success: () => { + resolve({ code: 0 }); + }, + fail: () => { + resolve({ code: 1 }); + } + }); + }); + + } + + /** 发送客服信息 */ + public static openConversation() { + + return new Promise>((resolve, reject) => { + if (!this.checkVerison('2.0.3')) resolve({ code: 1 }); + wx.openCustomerServiceConversation({ + success: () => { + resolve({ code: 0 }); + }, + fail: () => { + resolve({ code: 1 }); + } + }); + }); + + } + + /** 回到前台 */ + public static onShow(callback: () => void) { + if (!this.isWx) return; + wx.onShow(callback); + // return new Promise>((resolve, reject) => { + // wx.onShow((res: any) => { + // resolve({ code: 1 }); + // }); + // }); + + } + + /** 切换到后台 */ + public static onHide(callback: () => void) { + + if (!this.isWx) return; + wx.onHide(callback); + + } + + public static updateShareMenu(value) { + if (!this.isWx) return; + wx.updateShareMenu({ + withShareTicket: value + }); + } + + /** + * 检查授权 + */ + public static getSetting(scope: string = 'scope.userInfo') { + if (!this.isWx) return Promise.resolve(1); + return new Promise((resolve, reject) => { + wx.getSetting({ + success(res) { + if (res.authSetting[scope]) { + resolve(1) + } else { + reject() + } + } + }) + }) + } + /** + * 打开授权设置 + */ + public static openSetting(scope: string = 'scope.userInfo') { + if (!this.isWx) return Promise.resolve(1); + return new Promise((resolve, reject) => { + wx.openSetting({ + success(res) { + if (res.authSetting[scope]) { + resolve(1) + } else { + reject() + } + } + }) + }) + } + /** + * 打开授权窗口 + */ + public static authorize(scope: string = 'scope.userInfo') { + if (!this.isWx) return; + wx.authorize({ + scope: scope, + success(suc) { + console.log("suc", suc) + }, + fail(err) { + console.log("err", err) + } + }) + } + /** + * 获取用户信息 + */ + public static getUserInfo(callback) { + wx.getUserInfo({ + success: function (res) { + // console.log(res) + callback(res) + }, + fail: function (err) { + callback(err) + } + }) + } + /** + * 获取用户信息 自动弹出 + */ + public static getUserProfile(callback) { + if (!this.isWx) { + callback({ userInfo: "" }) + return + }; + wx.getUserProfile({ + desc: '补充用户资料', + success: function (res) { + // console.log(res) + callback(res) + }, + fail: function (err) { + console.log("获取用户信息", err); + callback(err) + } + }) + } + /** 游戏圈 */ + public static createGameClubButton(target: Node) { + let data = this.computWxPosition(target); + //@ts-ignore + return wx.createGameClubButton({ + icon: 'white', + style: { + left: data.left, + top: data.top, + width: data.width, + height: data.height, + } + }) + + } + + /** 抖音创建客服按钮 */ + public static createContactButton(target: Node) { + + let data = this.computWxPosition(target); + return wx.createContactButton({ + type: "text", // image | text + // image: "../resources/prefab/loading/mask", + text: ' ', + style: { + left: data.left, + top: data.top, + width: data.width, + height: data.height, + // lineHeight: 40, + backgroundColor: "#00000000", + // textAlign: "center", + // fontSize: 16, + // borderRadius: 5, + borderColor: "#00000000", + // borderWidth: 1, + // textColor: "#ffffff", + }, + success(res) { + console.log("createContactButton success", res); + }, + fail(res) { + console.log("createContactButton fail", res); + }, + complete(res) { + console.log("createContactButton complete", res); + }, + }); + } + + public static restartMiniProgram() { + if (typeof my != 'undefined') { + game.restart(); + return; + } + if (!this.isWx) { + return + }; + if (!wx.restartMiniProgram) { + this.showToast("自动重启失败,请手动重启!", 10000); + } + wx.restartMiniProgram(); + } +} \ No newline at end of file diff --git a/sdk/shareTools.ts b/sdk/shareTools.ts index 10a8aa7..da67952 100644 --- a/sdk/shareTools.ts +++ b/sdk/shareTools.ts @@ -1,4 +1,20 @@ -import WXSDK from "../wxsdk/WXSDK"; +import { UIManager } from "../../framework/core/view/UIManager"; +import { AudioManager } from "../../framework/mananger/AudioManager"; +import TAMgr from "../../framework/ta/TAMgr"; +import WXSDK from "../../framework/wxsdk/WXSDK"; +import { EventModels, EventPool } from "../const/EventModels"; +import { GameConst } from "../const/GameConst"; +import { EActivitySubTaskType, EWindowExitCode, WindowType } from "../const/types"; +import { mapController } from "../modules/map/MapController"; +import { PayShopManager } from "../modules/server/manager/PayShopManager"; +import { shopController } from "../modules/shop/ShopController"; +import { Utils } from "../utils/Utils"; +import MaskView from "../view/common/MaskView"; +import { Analytics } from "./Analytics"; +import { Ge } from "./Ge"; +import { SDKTools } from "./SDKTools"; +import { WxHelper } from "./WxHelper"; + /* * 分享与视频工具类; */ @@ -9,43 +25,126 @@ export class ShareTools { public static onShowAd: boolean = false; public static isTest: boolean = false; + + // private static getAdCount() { + // try { + // let adCount = SDKTools.getParamsString("ad_count", '10,10'); + // let arr = adCount.split(',').map(Number); + // if (SDKTools.isnew) { + // return +arr[0]; + // } else { + // return +arr[1]; + // } + // } catch (error) { + // return 10; + // } + // } /** * 验证分享:可处理成功、失败 * @param shareKey * @param params params.fail 有就不处理,没有自动处理 - * @param opts 目前支持5个key 1,title自定义分享标题 2,img_url自定义分享图片 3,share_type(不走后台配置写死走视频or分享。1分享2视频3无视频则分享)4,closeSimulate是否关闭模拟分享 5:multiton重新创建视频实例 + * @param opts 目前支持4个key 1,title自定义分享标题 2,img_url自定义分享图片 3,share_type(不走后台配置写死走视频or分享。1分享2视频3无视频则分享)4,closeSimulate是否关闭模拟分享 */ - static share(shareKey: string, params?: { success?: Function, fail?: Function, context?: any }, opts?: any) { - if (typeof wx === 'undefined' || this.isTest) { + static async share(shareKey: string, params?: { success?: Function, fail?: Function, context?: any }, opts?: any) { + const type = this.getShareType(shareKey); + // 免广告卡、体验卡 + if ((type == 2 && (!opts || opts.share_type != 1)) || (opts && opts.share_type == 2)) { + if (PayShopManager.I.isExperienceOrNoAd()) { + Analytics.I.dot("video_no_ad", { form: shareKey }); + params && params.success && params.success(); + return; + } else { + // 非免广告卡、体验卡用户 检查是否买过体验卡 + if (PayShopManager.I.checkShowExperience()) { + if (shopController.buyExperienceTips != Utils.getDayTime(0)) { + shopController.buyExperienceTips = Utils.getDayTime(0);; + UIManager.instance.showWindow2(WindowType.ExperienceGiftWindow); + params && params.fail && params.fail(); + return; + } + } + } + } + // 广告卡 + if (((type == 2 && (!opts || opts.share_type != 1)) || (opts && opts.share_type == 2)) && mapController.getPackageItemNum(GameConst.ITEM_ADCARD_ID) > 0) { + const ret = await UIManager.instance.waitWindow2(WindowType.AdCardWindow); + if (ret == EWindowExitCode.Yes) { + Analytics.I.dot("ad_card", { ad_card: shareKey }); + params && params.success && params.success(); + return; + } + } + + if ((typeof wx == 'undefined'&&typeof my == 'undefined') || this.isTest) { params && params.success && params.success(); + // 分享 + const evt = EventPool.get(EventModels.AcitvitySubTaskEvent); + evt.type = EActivitySubTaskType.Share; + evt.centerEmit(); return } + + // // 看广告n次后处理为分享 + // let count = this.getAdCount(); + // let isClear = false; + // // console.log("改为分享前:", settingsController.videoCount, count); + // if (settingsController.videoCount >= count) { + // if (type != 1 || (opts && opts.share_type == 2)) {// 视频 or // 强制视频 + // opts = { + // ...opts, + // share_type: 1,//强制改为分享 + // }; + // isClear = true; + // // console.log("改为分享了"); + // } + // } + this.onShowAd = true; + AudioManager.I.pauseAll(); + if (!opts || !opts.closeSimulate) { + MaskView.Show() + } WXSDK.share.share(shareKey.toString(), params, opts).then(async res => { this.onShowAd = false; + // if (isClear) { + // settingsController.videoCount = 0; + // } + if (res.type == 2) { + // 视频 + // settingsController.videoCount++; + Ge.I.adShowEvent("video", shareKey.toString()); + TAMgr.Ins.userAdd({ total_ad_num: 1 }); + } else { + // 分享 + const evt = EventPool.get(EventModels.AcitvitySubTaskEvent); + evt.type = EActivitySubTaskType.Share; + evt.centerEmit(); + TAMgr.Ins.dot('share_source', { from: shareKey }); + } params && params.success && params.success(res); + AudioManager.I.resumeAll(); + MaskView.Hide(); }).catch(async err => { + AudioManager.I.resumeAll(); + MaskView.Hide(); this.onShowAd = false; if (!params || !params.fail) { - wx.showToast({ - title: err.msg, - icon: 'none', - duration: 1500 - }) + if (err && err.msg) { + WxHelper.showToast(err.msg) + } } else { params && params.fail && params.fail(err); } - })//this.buildParams(params) + }) } /** - * 重新创建视频实例 + * 必定视频 不走后台配置 * @param shareKey * @param params - * @param opts multiton重新创建视频实例 */ - static multitonShare(shareKey: string, params?: { success?: Function, fail?: Function, context?: any }, opts?: any) { - this.share(shareKey, params, { multiton: true, ...opts }); + static video(shareKey: string, params?: { success?: Function, fail?: Function, context?: any }, opts?: any) { + this.share(shareKey, params, { ...opts, share_type: 2 }); } /** * 纯净分享 不处理回调 @@ -76,4 +175,11 @@ export class ShareTools { } } + /** + * 分享到朋友圈 bate 只支持安卓 + */ + static onShareTimeline(title: string, imageUrl: string, imagePreviewUrl?: string, query?: string) { + WXSDK.share.onShareTimeline(title, imageUrl, imagePreviewUrl, query); + } + } diff --git a/wxsdk/WXSDK.ts b/wxsdk/WXSDK.ts index c7647b5..9ca5284 100644 --- a/wxsdk/WXSDK.ts +++ b/wxsdk/WXSDK.ts @@ -7,9 +7,10 @@ import LogService from "./service/LogService"; import AdService from "./service/AdService"; import OnlineService from "./service/OnlineService"; import WxInterstitial from "./wx/WxInterstitial"; +import { sys } from "cc"; export default class WXSDK { public static get isWx(): boolean { - return typeof (wx) != "undefined" + return typeof wx != "undefined" } public static get data(): SdkData { return DataService.I.Data; @@ -38,10 +39,10 @@ export default class WXSDK { public static async init() { if (this.isWx) { WxInit.I.init(); - // 视频预加载 启动预加载视频会闪屏 - if (cc.sys.platform === cc.sys.WECHAT_GAME && typeof qq == 'undefined') { + //视频预加载 启动预加载视频会闪屏 + if (typeof wx !='undefined') { setTimeout(() => { - WxInterstitial.initInterstitialAd();//插屏预加载 + // WxInterstitial.initInterstitialAd();//插屏预加载 ShareVideoService.I.preloadVideo(); }, 2000); } diff --git a/wxsdk/alipay/AlipayApi.ts b/wxsdk/alipay/AlipayApi.ts new file mode 100644 index 0000000..74ce6da --- /dev/null +++ b/wxsdk/alipay/AlipayApi.ts @@ -0,0 +1,482 @@ +import SDKUtils from "../utils/SDKUtils"; + +import { __LOG__ } from "../base/SDKConst"; +import { NetworkType } from "../base/SDKEnum"; +import DataService from "../service/DataService"; +import Version from "../wx/Version"; +import WxApi from "../wx/WxApi"; +import WxSystem from "../wx/WxSystem"; +import { SDKApi } from "../http/SDKApi"; + +export default class AlipayApi { + private getVersionError(version: string): { errMsg: string; errCode: number } { + return { errMsg: `支持最低版本:${version}`, errCode: -1 }; + } + + canIUse(version: string): boolean { + return SDKUtils.compareVersion(WxSystem.I.SDKVersion, version) >= 0; + } + + // 注意 + // Android 6.7.2 以下版本,点击取消或蒙层时,回调 fail, errMsg 为 "fail cancel"; + // Android 6.7.2 及以上版本 和 iOS 点击蒙层不会关闭模态弹窗,所以尽量避免使用「取消」分支中实现业务逻辑 + showModal(data: any) { + wx.showModal(data); + } + + subscribeMessage(tmplIds: Array) { + let version = Version.I.getVSubscribeMessage(); + if (!this.canIUse(version)) return Promise.reject(this.getVersionError(version)); + // console.log("tmplIds", tmplIds) + return new Promise((resolve, reject) => { + wx.requestSubscribeMessage({ + tmplIds, + success: (ret: { errMsg: string }) => { + resolve(ret); + }, + fail: (err: { errMsg: string; errCode: number }) => { + reject(err); + } + }); + }); + } + + /** + * 创建banner广告 + */ + createBannerAd(adUnitId: string, style: _StyleObject, adIntervals?: number) { + if (!this.canIUse(Version.I.getVBannerAd())) return null; + + adIntervals = adIntervals || 30; + return my.createBannerAd({ + adUnitId, + style + }); + } + + /** + * 创建小游戏推荐banner + */ + createGameBanner(adUnitId: string, style: _StyleGameObject) { + if (!this.canIUse(Version.I.getVGameBanner())) return null; + + return my.createGameBanner({ + adUnitId, + style + }); + } + + /** + * 创建插屏广告组件 + */ + createInterstitialAd(adUnitId: string) { + if (!this.canIUse(Version.I.getVInterstitialAd())) return null; + return my.createInterstitialAd({ + adUnitId + }); + } + + /** + * 创建小游戏推荐icon组件 + */ + createGameIcon(adUnitId: string, opts: { count: number; style: Array<_GameIconStyleItem> }) {// + if (!this.canIUse(Version.I.getVGameIcon())) return null; + + return wx.createGameIcon({ adUnitId, ...opts }); + } + + /** + * 创建小游戏推荐弹窗组件 + */ + createGamePortal(adUnitId: string) { + if (!this.canIUse(Version.I.getVGamePortal())) return null; + + return wx.createGamePortal({ + adUnitId + }); + } + + /** + * 创建激励视频广告组件 + */ + createRewardedVideoAd(adUnitId: string) { + // if (!this.canIUse(Version.I.getVRewardedVideoAd())) return null; + return my.createRewardedAd({ + adUnitId: adUnitId, + }); + } + + /** + * 创建打开意见反馈页面的按钮 + */ + createFeedbackButton(data: _FeedbackButtonObject) { + if (!this.canIUse(Version.I.getVFeedbackButton())) return null; + + return wx.createFeedbackButton(data); + } + + /** + * 创建用户信息按钮 + */ + createUserInfoButton(data: _UserInfoButtonObject): _UserInfoButton | null {// + if (!this.canIUse(Version.I.getVUserInfoButton())) return null; + return wx.createUserInfoButton(data); + } + + /** + * 进入客服会话。要求在用户发生过至少一次 touch 事件后才能调用 + */ + openCustomerServiceConversation(params: _CustomerServiceConversationObject) {// + if (!this.canIUse(Version.I.getVCustomerService())) return -1; + wx.openCustomerServiceConversation({ ...params }); + return 1; + } + + vibrateLong() { + // if (!this.canIUse(Version.I.getVVibrate())) return Promise.reject(null); + + return new Promise((resolve, reject) => { + my.vibrateLong({ + success: () => { + resolve(1); + }, + fail: () => { + resolve(0); + } + }); + }); + } + + vibrateShort() { + // if (!this.canIUse(Version.I.getVVibrate())) return Promise.reject(null); + return new Promise((resolve, reject) => { + my.vibrateShort({ + success: () => { + resolve(1); + }, + fail: () => { + resolve(0); + } + }); + }); + } + + /** + * 更新转发属性 + */ + updateShareMenu(value: boolean) { + if (!this.canIUse(Version.I.getVUpdateShareMenu())) return; + wx.updateShareMenu({ + withShareTicket: value + }); + } + + /** + * 检测更新 + */ + checkUpdate(data: _ShowModalObject): void {// + if (!this.canIUse(Version.I.getVUpdateManager())) return; + + data = data || {}; + // tslint:disable-next-line: no-this-assignment + let that = this; + // 默认参数 + let params: _ShowModalObject = {// + title: data.title || '更新提示', + content: data.content || '新版本已经准备好,是否重启应用?', + showCancel: false, + success: (res: _ShowModalSuccessObject) => {// + data.success && data.success(res); + if (res.confirm) { + updateManager.applyUpdate(); + } + }, + fail: (err: any) => data.fail && data.fail(err), + complete: () => data.complete && data.complete() + }; + // 合并参数 + let keys = ['cancelText', 'cancelColor', 'confirmText', 'confirmColor']; + keys.forEach(key => SDKUtils.hasProperty(data, key) && (params = { ...params, [key]: data[key] })); + + let updateManager = wx.getUpdateManager(); + updateManager.onCheckForUpdate((res: any) => { + __LOG__ && console.warn('====> PCSDK AlipayApi updateManager onCheckForUpdate', res.hasUpdate); + }); + updateManager.onUpdateReady(function () { + that.showModal(params); + }); + updateManager.onUpdateFailed(function () { + // 新的版本下载失败 + __LOG__ && console.warn('SDK WxApi updateManager onUpdateFailed'); + }); + } + + /** + * 显示当前页面的转发按钮 + */ + showShareMenu(shareApp: _ShareAppMessageObject, shareMenu: _UpdateShareMenuObject) { + if (!this.canIUse(Version.I.getVShowShareMenu())) return; + __LOG__ && console.error('showShareMenu shareApp'); + __LOG__ && console.error('showShareMenu shareMenu'); + my.onShareAppMessage(() => shareApp); + // my.showShareMenu(shareMenu); + } + + /** + * 主动拉起转发,进入选择通讯录界面。 + */ + shareAppMessage(data: _ShareAppMessageObject, callback: { success: Function, fail: Function, cancel: Function }) { + my.onShareAppMessage = function () { + return { + title: data.title, + bgImgUrl:'https://wxsdk-cdn.miso-lab.com/moon-island/share/zfbshare.jpeg', + // desc: , + scImgUrl: data.imageUrl, + success: function (res) { + console.log(res); + }, + fail: function (e) { + console.log(e); + }, + complete: function (e) { + + } + } + } + + return my.showSharePanel({ + success: () => { + callback.success(); + + }, + fail: () => { + callback.fail(); + }, + complete: (e) => { + + }, + }); + + } + + previewImage(imgList: Array, index: number) { + return new Promise((suc, fail) => { + if (!imgList || imgList.length === 0) { + fail(); + return; + } + wx.previewImage({ + current: imgList[index], // 当前显示图片的http链接 + urls: imgList, // 需要预览的图片http链接列表 + success(res: any) { + suc({ ...res, qrcode: 1 }); + }, + fail(err: any) { + fail(err); + } + }); + }); + } + + getNetworkType(): Promise<_NetworkTypeSuccessObject> { + return new Promise((resolve, reject) => { + wx.getNetworkType({ + success(res: _NetworkTypeSuccessObject) { + resolve(res); + }, + fail(err: any) { + reject({ networkType: NetworkType.Unknown }); + } + }); + }); + } + + navigateToMiniProgram(appId: string, path: string, opts: any = {}) { + return new Promise((resolve, reject) => { + wx.navigateToMiniProgram({ + appId, + path, + extraData: opts.extraData || {}, + envVersion: opts.envVersion || 'release', + success(res: any) { + resolve(res); + }, + fail(err: any) { + reject(err); + } + }); + }); + } + + /** + * login获取code接口 + */ + login(): Promise { + return new Promise((resolve, reject) => { + my.getAuthCode({ + scopes: 'auth_base', + success: (res) => { + resolve(res.authCode); + }, + fail: (err: any) => { + reject(err); + } + }); + }); + } + + /** + * 用户信息授权接口 + */ + getUserinfo(): Promise { + return new Promise((resolve, reject) => { + my.getAuthUserInfo({ + success: (ret: any) => { + if (!ret) { + console.log('getUserinfo success', ret) + reject(ret); + return AlipayApi.I.setAuthorize({ + errorTip: 'getUserInfo Success result is null', + ...ret + }); + } + console.log('getUserinfo success', ret) + resolve(ret); + }, + fail: (err: any) => { + console.log('getUserinfo fail', err) + reject(err); + AlipayApi.I.setAuthorize({ + errorTip: 'getUserInfo Fail', + ...err + }); + }, + complete: (res) => { + console.log('getUserinfo complete', res) + } + }); + }); + } + + /** + * 分享接口 + * @param shareTicket + */ + getShareInfo(shareTicket: string): Promise { + if (!this.canIUse(Version.I.getVShareInfo())) return Promise.reject(null); + + return new Promise((resolve, reject) => { + wx.getShareInfo({ + shareTicket, + success: (ret: _getShareInfoSuccessObject) => { + let { errMsg } = ret; + if (errMsg === 'getShareInfo:ok') { + resolve(ret); + } else { + reject(ret); + } + }, + fail: (err: any) => { + reject(err); + } + }); + }); + } + + /** + * 米大师充值 + */ + requestMidasPayment(params: { mode: string; env: number; offerId: string; currencyType: string; platform: string; buyQuantity: number; zoneId: string }): Promise { + let { mode, env, offerId, currencyType, platform, buyQuantity, zoneId } = params; + console.warn('====> PCSDK AlipayApi requestMidasPayment 支付参数', { + mode, + env, + offerId, + currencyType, + platform, + buyQuantity, + zoneId + }); + return new Promise((resolve, reject) => { + wx.requestMidasPayment({ + mode, + env, + offerId, + currencyType, + platform, + buyQuantity, + zoneId, + success: ret => { + if (ret && ret.errMsg === 'requestMidasPayment:ok') + resolve(ret); + else + reject(ret); + }, + fail: err => { + reject(err); + } + }); + }); + } + + private setAuthorize(error: any) { + DataService.I.setAuthorize(false); + } + + canIncrementGameaction(): boolean { + if (window['my'] == undefined) return false; + return true; + } + /** + * 玩一玩增量行为 + */ + incrementGameaction(action_code: string) { + return new Promise((resolve, reject) => { + if (window['my'] == undefined) return reject(null); + let channel = 'other'; + let info = my.getLaunchOptionsSync(); + if (info.query.channel == undefined) { + channel = 'other'; + } else { + if (info.query.channel.length <= 0 || info.query.channel == null) { + channel = 'other'; + } else { + channel = info.query.channel; + } + } + // my.alert({ + // title: '增加量行为', + // content:`${action_code}` + // }); + let uid = DataService.I.UserId; + let token = DataService.I.Token; + let openid = DataService.I.OpenId; + let action_finish_channel = channel + let params = { + uid, + token, + openid, + action_code, + action_finish_channel + }; + return SDKApi.incrementGameaction(params).then(() => { + // my.confirm({ + // title: '增加量行为', + // content: `${action_code}`, + // confirmButtonText: ``, + // cancelButtonText: '暂不需要', + // success: (result) => { + // }, + // }); + resolve(null) + }) + }) + } + + + private static _instance: AlipayApi; + static get I(): AlipayApi { + return this._instance || (this._instance = new AlipayApi); + } + +} diff --git a/wxsdk/alipay/AlipayBanner.ts b/wxsdk/alipay/AlipayBanner.ts new file mode 100644 index 0000000..30bf26e --- /dev/null +++ b/wxsdk/alipay/AlipayBanner.ts @@ -0,0 +1,238 @@ + +// import SDKUtils from "../utils/SDKUtils"; +// import { BannerError, __LOG__ } from "../base/SDKConst"; +// import LogService from "../service/LogService"; +// import { DOT_AD_STATUS, DOT_AD_TYPE } from "../base/SDKEnum"; +// import WxSystem from "../wx/WxSystem"; +// import AlipayApi from "./AlipayApi"; + + +// /* +// * banner +// */ +// export default class AlipayBanner { +// private static instance: AlipayBanner; +// static get I(): AlipayBanner { +// return this.instance || (this.instance = new AlipayBanner(750, 750)); +// } +// private designWidth: number; +// private bannerWidth: number; +// private bannerHeight: number; +// private bannerScale: number; +// private bannerParams: any; +// private _isErrored: boolean; +// private adUnitId: string; +// private bannerAd: any; +// private resolve: any; +// private reject: any; + +// constructor(designWidth: number, bannerWidth: number) { +// designWidth = designWidth || 750; +// bannerWidth = bannerWidth || 750; + +// this.adUnitId = ''; +// this._isErrored = false; +// this.designWidth = designWidth; +// this.bannerScale = WxSystem.I.winWidth / this.designWidth; +// this.bannerWidth = Math.max(this.bannerScale * bannerWidth, 300); +// this.bannerHeight = WxSystem.I.winHeight / this.bannerScale; +// } + +// get isErrored() { +// return this._isErrored; +// } + +// private queue: Function[] = []; +// private isEnd: boolean = false; + +// create(adUnitId: string, opts?: { type?: number; bannerWidth?: number, offsetY?: number; adIntervals?: number, isOff?: boolean }) { +// // console.log('wxbanner can not') +// if (SDKUtils.compareVersion(my.env.clientVersion, '10.3.66') < 0) return null; +// // if (!WxApi.I.canIUse(Version.I.getVBannerAd())) +// // console.log('wxbanner can', adUnitId) + +// this.bannerParams = opts || {}; +// if (opts && opts.bannerWidth) { +// this.bannerWidth = opts.bannerWidth; +// } +// this.isEnd = true; +// this.bannerParams.type = this.bannerParams.type || 1; +// this.bannerParams.offsetY = -this.bannerParams.offsetY || 0; +// this.bannerParams.adIntervals = this.bannerParams.adIntervals || 120; +// return new Promise((resolve, reject) => { +// this.resolve = resolve; +// this.reject = reject; +// this._isErrored = false; +// this.adUnitId = adUnitId; + +// if (SDKUtils.isEmpty(adUnitId)) { +// AlipayBanner.I.handleQueue(); +// return this.reject({ ...BannerError.BannerInvalid, adUnitId: this.adUnitId }); +// } + +// // 设置样式(hack:修复qq版本) +// this.bannerParams.type === 2 && (this.bannerWidth = WxSystem.I.winWidth); +// let style = { top: 0, left: (WxSystem.I.winWidth - this.bannerWidth) / 2, width: this.bannerWidth }; +// style = { +// ...style, +// top: WxSystem.I.winHeight - 100, +// }; +// // 创建并判断是否存在 +// // if (this.bannerParams.type === 2) +// // this.bannerAd = wx.createGameBanner({ adUnitId, style: { left: style.left, top: this.bannerHeight } }); +// // else +// if (this.bannerAd) { +// if (!opts || (opts && !opts.isOff)) { +// this.show(false); +// } +// return +// } +// this.bannerAd = AlipayApi.I.createBannerAd(adUnitId, style); +// LogService.I.adStat('banner', this.adUnitId, DOT_AD_TYPE.banner, DOT_AD_STATUS.request) +// if (!this.bannerAd) { +// AlipayBanner.I.handleQueue(); +// return this.reject({ ...BannerError.BannerNotOpen, adUnitId: this.adUnitId }); +// } +// this.bannerAd.onLoad(this.onLoad); +// this.bannerAd.onError(this.onError); +// //支付宝无这个方法!!! +// // this.bannerAd.onResize(this.onResize); +// if (!opts || (opts && !opts.isOff)) { +// this.show(false); +// } +// }); +// } + +// /** +// * +// * @param bol +// */ +// show(bol: boolean = true): boolean { +// if (AlipayBanner.I.isEnd && bol) { +// AlipayBanner.I.queue.push(AlipayBanner.I.show.bind(AlipayBanner.I)) +// return +// } +// AlipayBanner.I.isEnd = true +// if (this.bannerAd) { +// if (this.bannerAd.style.realHeight) +// this.bannerAd.style.top = WxSystem.I.winHeight - this.bannerAd.style.realHeight + this.bannerParams.offsetY; +// if (this.bannerParams.type === 2) { +// if (this.bannerAd.style.width) +// this.bannerAd.style.left = (WxSystem.I.winWidth - this.bannerAd.style.width) / 2; +// else +// this.bannerAd.style.left = (WxSystem.I.winWidth - this.bannerWidth) / 2; +// } else +// this.bannerAd.style.left = (WxSystem.I.winWidth - this.bannerWidth) / 2; + +// LogService.I.adStat('banner', this.adUnitId, DOT_AD_TYPE.banner, DOT_AD_STATUS.show) +// this.bannerAd.show().catch((err: any) => this.handleShowError(err)); +// __LOG__ && console.error('wxBanner - show: ' + this.adUnitId, this.bannerAd.style); +// AlipayBanner.I.handleQueue() +// return true; +// } +// AlipayBanner.I.handleQueue() +// return false; +// } + +// hide() { +// let that = AlipayBanner.I; +// if (that.isEnd) { +// that.queue.push(that.hide.bind(that)) +// return +// } +// that.isEnd = true +// if (this.bannerAd) { +// this.bannerAd.style.left = -9999; +// this.bannerAd.hide(); +// LogService.I.adStat('banner', that.adUnitId, DOT_AD_TYPE.banner, DOT_AD_STATUS.interrupt) +// __LOG__ && console.error('wxBanner - hide: ' + this.adUnitId); +// } +// that.handleQueue() +// } + +// toggle(isshow: boolean) { +// isshow ? this.show() : this.hide(); +// } + +// destory() { +// if (this.bannerAd) { +// this.bannerAd.style.left = -9999; +// this.bannerAd.destroy(); +// this.bannerAd = null; +// LogService.I.adStat('banner', this.adUnitId, DOT_AD_TYPE.banner, DOT_AD_STATUS.interrupt) +// __LOG__ && console.error('wxBanner - destory: ' + this.adUnitId); +// } +// } + +// private onLoad() { +// let that = AlipayBanner.I; +// let bannerAd = that.bannerAd; +// if (!bannerAd) return; +// // Platform.IsQQ && that.show(); +// __LOG__ && console.error('wxBanner - onLoad: ' + that.adUnitId); +// if (bannerAd.style.realHeight) +// bannerAd.style.top = WxSystem.I.winHeight - bannerAd.style.realHeight + that.bannerParams.offsetY; +// that.unbind(); +// that.handleQueue(); +// that.resolve && that.resolve({ +// adUnitId: that.adUnitId, +// scale: that.bannerScale, +// width: bannerAd.style.realWidth / that.bannerScale, +// height: bannerAd.style.realHeight / that.bannerScale +// }); +// } + +// private onError(err: any, ...params) { +// __LOG__ && console.error('wxBanner - onError', err, JSON.stringify(err), params); +// let that = AlipayBanner.I; +// !that._isErrored && that.handleError(err, { ...BannerError.BannerFail, adUnitId: that.adUnitId }); +// } + +// private onResize() { +// let that = AlipayBanner.I; +// let bannerAd = that.bannerAd; +// if (!bannerAd) return; +// bannerAd.style.top = WxSystem.I.winHeight - bannerAd.style.realHeight + that.bannerParams.offsetY; +// bannerAd.style.left = (WxSystem.I.winWidth - bannerAd.style.realWidth) / 2; +// } + +// private handleShowError(ret: { errCode: number; errMsg: string }) { +// __LOG__ && console.error('wxBanner - handleShowError', ret); +// let that = AlipayBanner.I; +// let { errCode, errMsg } = ret; +// !that.isErrored && that.handleError(ret, { code: errCode, msg: errMsg }); +// } + +// private handleError(ret: any, err: any) { +// let that = AlipayBanner.I; +// that.unbind(); +// that._isErrored = true; +// that.bannerAd = null; +// that.handleQueue() +// LogService.I.adStat('banner', that.adUnitId, DOT_AD_TYPE.banner, DOT_AD_STATUS.fail) +// that.reject && that.reject({ ...err, adUnitId: that.adUnitId }); +// __LOG__ && console.error('wxBanner - onError: ' + that.adUnitId, ret, err); +// } + +// private unbind() { +// if (this.bannerAd) { +// // this.bannerAd.offLoad(this.onLoad); +// // this.bannerAd.offError(this.onError); +// // this.bannerAd.offResize(this.onResize); +// } +// } + +// /** +// * 处队列 +// */ +// handleQueue() { +// let that = AlipayBanner.I; +// if (that.queue.length > 0) { +// that.isEnd = false; +// let fn = that.queue.shift(); +// fn(); +// } else { +// that.isEnd = false; +// } +// } +// } \ No newline at end of file diff --git a/wxsdk/alipay/AlipayInterstitial.ts b/wxsdk/alipay/AlipayInterstitial.ts new file mode 100644 index 0000000..5027a98 --- /dev/null +++ b/wxsdk/alipay/AlipayInterstitial.ts @@ -0,0 +1,68 @@ +// import { GAMEDATA } from "../base/SDKConst"; +// import { DOT_AD_STATUS, DOT_AD_TYPE } from "../base/SDKEnum"; +// import LogService from "../service/LogService"; +// import AlipayApi from "./AlipayApi"; + +// export default class AlipayInterstitial { +// /** 插屏广告ID */ +// private static interstitialAdId: string = GAMEDATA.interstitialAdId; +// /** 插屏广告实例 */ +// public static interstitialAd: any; +// /** 插屏广告是否加载完成 */ +// private static interstitialSuccell: boolean = false; +// /** 初始化插屏广告 */ +// public static initInterstitialAd(adUnitId: string = GAMEDATA.interstitialAdId) { +// this.interstitialAdId = adUnitId; +// this.createInterstitial(); +// } + +// /** 显示插屏广告 */ +// public static showInterstitialAd(adUnitId: string = GAMEDATA.interstitialAdId) { +// return new Promise(async (resolve, reject) => { +// this.interstitialAdId = adUnitId; +// if (!this.interstitialSuccell) { +// this.createInterstitial(true, resolve); +// return; +// } +// this.interstitialAd.show().then(suc => { +// resolve && resolve({ code: 0, msg: "展示成功!" }); +// LogService.I.adStat('InterstitialAd', this.interstitialAdId, DOT_AD_TYPE.interstitial, DOT_AD_STATUS.show) +// }).catch((err) => { +// LogService.I.adStat('InterstitialAd', this.interstitialAdId, DOT_AD_TYPE.interstitial, DOT_AD_STATUS.fail) +// resolve && resolve({ code: err.errCode, msg: err.errMsg }); +// }) +// }) +// } + +// /** 创建插屏广告 */ +// private static createInterstitial(isShow: boolean = false, resolve?) { +// LogService.I.adStat('InterstitialAd', this.interstitialAdId, DOT_AD_TYPE.interstitial, DOT_AD_STATUS.request) +// this.interstitialAd = AlipayApi.I.createInterstitialAd(this.interstitialAdId); +// this.interstitialAd.onLoad(async () => { +// AlipayInterstitial.interstitialSuccell = true; +// LogService.I.adStat('InterstitialAd', this.interstitialAdId, DOT_AD_TYPE.interstitial, DOT_AD_STATUS.rt) +// if (isShow) { +// this.interstitialAd.show().then(suc => { +// resolve && resolve({ code: 0, msg: "展示成功!" }); +// LogService.I.adStat('InterstitialAd', this.interstitialAdId, DOT_AD_TYPE.interstitial, DOT_AD_STATUS.show) +// }).catch((err) => { +// AlipayInterstitial.interstitialSuccell = false; +// LogService.I.adStat('InterstitialAd', this.interstitialAdId, DOT_AD_TYPE.interstitial, DOT_AD_STATUS.fail) +// resolve && resolve({ code: err.errCode, msg: err.errMsg }); +// }) +// } +// }) +// this.interstitialAd.onError(err => { +// LogService.I.adStat('InterstitialAd', this.interstitialAdId, DOT_AD_TYPE.interstitial, DOT_AD_STATUS.fail) +// AlipayInterstitial.interstitialSuccell = false; +// resolve && resolve({ code: err.errCode, msg: err.errMsg }); +// }) + +// this.interstitialAd.onClose(call => { +// this.createInterstitial(false); +// }) +// // }).bind(this), 200); + + +// } +// } \ No newline at end of file diff --git a/wxsdk/alipay/zfbPay.ts b/wxsdk/alipay/zfbPay.ts new file mode 100644 index 0000000..e9e4e87 --- /dev/null +++ b/wxsdk/alipay/zfbPay.ts @@ -0,0 +1,183 @@ +import { WxHelper } from '../../../game/sdk/WxHelper'; +import { GAMEDATA } from '../base/SDKConst'; +import { EnvCode } from '../base/SDKEnum'; +import { SDKApi } from '../http/SDKApi'; +import DataService from '../service/DataService'; +import WxSystem from '../wx/WxSystem'; + +export default class ZfbPay { + /** + * 发起支付 + */ + pay(params: { payid: string, goodid: string, money: number; orderid: string }, opts: any = {}): Promise { + return new Promise((resolve, reject) => { + let { Mode, OfferId, ZoneId, CurrencyType, Platform } = GAMEDATA.MidasPay; + // 环境配置,0:米大师正式环境 1:米大师沙箱环境 + let env = DataService.I.EnvEnum === EnvCode.Prod ? 0 : 1; + // 平台类型,android or ios,config.js有配置走配置,否则判断系统id + let platform = DataService.I.Platform; + let pms = { + mode: Mode, + env, + platform, + offerId: OfferId, + currencyType: CurrencyType, + buyQuantity: params.money / 10, + zoneId: ZoneId + }; + let extend = ""; + for (let key in opts) { + extend += (`${key}=${opts[key]}&`) + } + extend = extend.substring(0, extend.length - 1); + extend = encodeURIComponent(extend); + + let payParams = { + ...this.buildParams(), + extend, + orderid: params.orderid, + // payid: params.payid, + goodid: params.goodid, + money: params.money, + platform + }; + SDKApi.zfbOrderReport(payParams).then(res => { + console.log("res:" + JSON.stringify(res)); + console.log("调用函数成功00"); + if (!res.code) { + let { customId, buyQuantity, extraInfo } = res.data; + my.requestGamePayment({ + customId, + buyQuantity, + extraInfo, + success(res) { + console.log("调用函数成功"); + resolve({ code: 0, msg: '支付成功!' }) + }, + fail(err) { + console.log("调用函数失败"); + if (err && err.error) { + if ("" + err.error == '15215') { + my.alert({ + title: '您好,基于国家新闻出版署《关于防止未成年人沉迷网络游戏的通知》的规定,支付宝限制未成年人游戏充值哦', + }); + } else if ("" + err.error == '15204') { + my.alert({ + title: '非常抱歉,充值功能暂不可用,请稍后再试', + }); + } + } + resolve({ code: err.errCode, msg: '支付失败' }); + }, + complete(res) { + try { + console.log(JSON.stringify(res)); + } catch (error) { + + } + console.log(res) + console.log("调用完成"); + }, + }) + } else { + console.log("调用函数成功222"); + reject(res); + } + }) + }); + } + + private async handlePaySuccess(data: { payid: string, goodid: string, money: number; orderid: string, platform: string }, opts: any, resolve: any, reject: any, t = 1000) { + let extend = ""; + for (let key in opts) { + extend += (`${key}=${opts[key]}&`) + } + extend = extend.substring(0, extend.length - 1); + extend = encodeURIComponent(extend); + let params = { + ...this.buildParams(), + extend, + midasenv: DataService.I.EnvEnum === EnvCode.Prod ? 0 : 1, + orderid: data.orderid, + payid: data.payid, goodid: data.goodid, + type: 1, + money: data.money, + platform: data.platform + }; + var that = this; + SDKApi.zfbOrderReport(params) + .then(res => { + if (!res.code) { + resolve(res); + } else { + t = Math.min(t * 2, 60000) + setTimeout(() => { + that.handlePaySuccess(data, opts, resolve, reject, t) + }, t); + } + }) + } + + private handlePayError(data: { payid: string, goodid: string, money: number; orderid: string, platform: string }, opts, err: any, reject: any) { + console.log("支付失败", JSON.stringify(err)); + let type = 2; + if (err.errCode + '' == '1') { + type = 3; + } + let extend = ""; + for (let key in opts) { + extend += (`${key}=${opts[key]}&`) + } + extend = extend.substring(0, extend.length - 1); + extend = encodeURIComponent(extend); + let params = { + ...this.buildParams(), + extend, + midasenv: DataService.I.EnvEnum === EnvCode.Prod ? 0 : 1, + orderid: data.orderid, + payid: data.payid, goodid: data.goodid, + type, + money: data.money, + platform: data.platform + }; + SDKApi.zfbOrderReport(params) + reject(err); + } + + /** + * 构建支付公用参数 + */ + private buildParams() { + let gameid = GAMEDATA.game_id; + let channel = DataService.I.ChannelId; + let openid = DataService.I.OpenId; + let brand = WxSystem.I.brand; + let model = WxSystem.I.model; + let version = WxSystem.I.version; + let system = WxSystem.I.system; + let sdkversion = WxSystem.I.SDKVersion; + let scene = DataService.I.Scene + ''; + let uid = DataService.I.UserId; + let token = DataService.I.Token; + let env = DataService.I.EnvEnum === 1 ? 'pre' : 'prod'; + return { + gameid, + openid, + channel, + brand, + model, + version, + system, + sdkversion, + scene, + uid, + token, + env + }; + } + + private static _instance: ZfbPay; + static get I(): ZfbPay { + return this._instance || (this._instance = new ZfbPay); + } +} \ No newline at end of file diff --git a/wxsdk/base/SDKBaseData.ts b/wxsdk/base/SDKBaseData.ts index f40a00b..33a4336 100644 --- a/wxsdk/base/SDKBaseData.ts +++ b/wxsdk/base/SDKBaseData.ts @@ -1,3 +1,3 @@ export default class SDKBaseData{ - public static SimulateShareTime:number = 3000; + public static SimulateShareTime:number = 1000; } \ No newline at end of file diff --git a/wxsdk/base/SDKConst.ts b/wxsdk/base/SDKConst.ts index f6dfa62..c372009 100644 --- a/wxsdk/base/SDKConst.ts +++ b/wxsdk/base/SDKConst.ts @@ -1,31 +1,30 @@ // 游戏配置数据 只需要改动这里的配置信息 -// 游戏配置数据 只需要改动这里的配置信息 - export const GAMEDATA = { - game_id: '10001',//游戏id - channel_id: '10001',//渠道id 暂时和游戏id一致 - version: '1.0.1', //版本号 中台控制正式还是测试服,尽量保持和小游戏版本一致 - appkey: 'd959274a83ea3b95bd1d9b765683e777',//中台appkey + game_id: '10110',//游戏id + isDebug: false, + channel_id: '10110',//渠道id 暂时和游戏id一致 + version: '1.0.0', //版本号 中台控制正式还是测试服,尽量保持和小游戏版本一致 + appkey: '48ef655c48f53f1e75f2108cf65d394e',//中台appkey interstitialAdId: 'adunit-4bd19de3c351233e',//插屏ID - bannerId: 'adunit-25341fff11681315',//banner + bannerId: 'adunit-6145b17777e308a8',//banner customId: 'adunit-193590de82ede6a4',//原生模板单个 - videoAd: 'adunit-638f9158bce2c31e',//初始化视频广告id + videoAd: 'adunit-59404ef14e6c32ed',//初始化视频广告id shareMessageToFriend: { // 暂时只支持一个场景值 scene: 0, //定向分享场景值1-50 配>0的会初始化 sharekey: 'shareMessageToFriendScene',//定向分享对应后台的分享key share_id: 26,//定向分享对应后台的分享key }, default_share: { //默认分享数据在拉取不到中台分享数据的时候用 - content: '全新版本的连连消,等你来玩!',//分享标题 *找运营提供 - icon: 'xxxx',//分享图链接 *找运营提供 + content: '惊喜世界合不停',//分享标题 *找运营提供 + icon: 'https://cdn-wxsdk.miso-lab.com/7d/da1ed3fb6073ddd43f156f98c625e3.jpg',//分享图链接 *找运营提供 id: '9999',//默认id 写死9999 key: 'default',//默认分享key 写死default title: '默认',//无需修改 typ: 1,//分享类型 写死1 videoid: '',//默认的视频广告id 填空就行 }, - MidasPay: { // 米大师虚拟支付配置 - OfferId: "xxxx", // 在米大师申请的应用id + MidasPay: { // 米大师虚拟支付配置 *找运营提供 + OfferId: "1450051274", // 在米大师申请的应用id *找运营提供 ZoneId: "1", // 分区ID,默认:1 Mode: "game", // 默认:game CurrencyType: "CNY", // 默认:CNY @@ -33,9 +32,8 @@ export const GAMEDATA = { } } - // sdk版本 -export const SDKVersion = 'v1.0.16'; +export const SDKVersion = 'v1.0.15'; // 是否打印 export const __LOG__ = false; // 是否mock @@ -43,8 +41,6 @@ export var sdkEnv = { isDebug: false }; - - //游戏基础信息 export const VersionHost = 'https://wxsdk-ver.d3games.com/version'; @@ -106,7 +102,7 @@ export const HostKeys = { rankAdd: 'api/rank/add', //排行榜添加分数 517废弃 rankList: 'api/rank/list', //世界排行榜 517废弃 totalrankAdd: 'game/totalrank/add', //排行榜添加分数 - totalrankList: 'game/totalrank/list', //世界排行榜 + totalrankList: 'game/totalrank/list', //世界排行榜 adList: 'api/adplan/list', //广告计划列表 behavior: 'api/douyin/behavior', //抖音投放关键行为 attribute: 'api/member/attribute/set', //修改用户属性 @@ -120,8 +116,13 @@ export const HostKeys = { preorder: 'api/order/v2/preorder', //获取支付方式 bytedanceOrderReport: 'api/order/v2/bytedance', //字节订单信息上报 qqOrderReport: 'api/order/v2/qq', //qq订单信息上报 + zfbOrderReport:'api/order/v2/zfb/add', //支付宝小游戏订单上报 // goodslist: 'api/v2/goodslist', //商品列表 + + + //支付宝 + AlipayIncrementGameaction: 'api/ali/action/submit' ,//玩一玩:增量游戏行为完成上报 }; // 本地存储keys diff --git a/wxsdk/base/wx.d.ts b/wxsdk/base/wx.d.ts index 4202dbd..1b142d5 100644 --- a/wxsdk/base/wx.d.ts +++ b/wxsdk/base/wx.d.ts @@ -1,3 +1,4 @@ declare const wx; -declare const qq; \ No newline at end of file +declare const qq; +declare const my; \ No newline at end of file diff --git a/wxsdk/http/SDKApi.ts b/wxsdk/http/SDKApi.ts index 8f2334e..0899e7b 100644 --- a/wxsdk/http/SDKApi.ts +++ b/wxsdk/http/SDKApi.ts @@ -84,6 +84,16 @@ export class SDKApi { public static qqOrderReport = (...args) => SDKHttp.httpPost(DataService.I.OrderApi, HostKeys.qqOrderReport, ...args); public static orderQuery = (...args) => SDKHttp.httpPost(DataService.I.OrderApi, HostKeys.orderQuery, ...args); public static preorder = (...args) => SDKHttp.httpPost(DataService.I.OrderApi, HostKeys.preorder, ...args); + public static zfbOrderReport = (...args) => SDKHttp.httpPost(DataService.I.OrderApi, HostKeys.zfbOrderReport, ...args); public static goodslist = (...args) => SDKHttp.httpPost(DataService.I.OrderApi, HostKeys.goodslist, ...args); + + + //支付宝 + /** + * 玩一玩增量行为 + * @param args + * @returns + */ + public static incrementGameaction = (...args) => SDKHttp.httpPost(DataService.I.GameApi, HostKeys.AlipayIncrementGameaction, ...args); } diff --git a/wxsdk/http/SDKHttp.ts b/wxsdk/http/SDKHttp.ts index 2934c98..f7fad29 100644 --- a/wxsdk/http/SDKHttp.ts +++ b/wxsdk/http/SDKHttp.ts @@ -43,9 +43,9 @@ export default class SDKHttp { responseText = JSON.parse(responseText); // cc.log("responseText22", responseText) if (url.indexOf('.json') > -1) { - resolve({ code: 0, data: responseText, msg: responseText.msg , servertime: responseText.servertime}); + resolve({ code: 0, data: responseText, msg: responseText.msg, servertime: responseText.servertime }); } else { - resolve({ code: +responseText.code, data: responseText.data, msg: responseText.msg , servertime: responseText.servertime}); + resolve({ code: +responseText.code, data: responseText.data, msg: responseText.msg, servertime: responseText.servertime }); } return } catch (ex) { @@ -55,37 +55,30 @@ export default class SDKHttp { } } else { console.error(xhr.status, '网络请求失败!'); - resolve({ code: -1 }); + resolve({ code: -2 }); } } }; xhr.ontimeout = function (info): void { // cc.error("info1", info) - resolve({ msg: `请求超时!`, code: -1 }); + resolve({ msg: `请求超时!`, code: -3 }); } xhr.onerror = function (info): void { // cc.error("info2", info) - resolve({ msg: `请求失败!`, code: -1 }); + resolve({ msg: `请求失败!`, code: -4 }); } xhr.onabort = function (info): void { // cc.error("info3", info) - resolve({ msg: `请求失败!`, code: -1 }); + resolve({ msg: `请求失败!`, code: -5 }); } xhr.open(method, url, true); if (method == "POST") { xhr.setRequestHeader("Content-Type", "application/json;charset=utf-8")//application/x-www-form-urlencoded - // if (cc.sys.os === 'Android') { - // cc.error("http__uid", AppSdkData.I.uid); - // xhr.setRequestHeader('Uuid', `${AppSdkData.I.uid}`); - // } else { - // xhr.setRequestHeader('Uuid', `909`); - // } - } - xhr.timeout = 3000; + xhr.timeout = 10000; xhr.send(data); }); } diff --git a/wxsdk/platform/wx/WxStorage.ts.meta b/wxsdk/platform/wx/WxStorage.ts.meta index e76a04b..e2f3294 100644 --- a/wxsdk/platform/wx/WxStorage.ts.meta +++ b/wxsdk/platform/wx/WxStorage.ts.meta @@ -1,9 +1,9 @@ { - "ver": "1.0.8", + "ver": "4.0.23", + "importer": "typescript", + "imported": true, "uuid": "6013014c-7aa3-4eb4-b818-583d937a9f05", - "isPlugin": false, - "loadPluginInWeb": true, - "loadPluginInNative": true, - "loadPluginInEditor": false, - "subMetas": {} -} \ No newline at end of file + "files": [], + "subMetas": {}, + "userData": {} +} diff --git a/wxsdk/service/AdService.ts b/wxsdk/service/AdService.ts index 656e421..362782d 100644 --- a/wxsdk/service/AdService.ts +++ b/wxsdk/service/AdService.ts @@ -5,6 +5,7 @@ import WxInterstitial from "../wx/WxInterstitial"; import { GAMEDATA } from "../base/SDKConst"; import LogService from "./LogService"; import DouyinInterstitial from "../douyin/DouyinInterstitial"; +import { sys } from "cc"; @@ -16,7 +17,7 @@ export default class AdService { * @param adUnitId * @param opts */ - createBanner(adUnitId: string, opts?: { type?: number; bannerWidth?: number, offsetY?: number; adIntervals?: number, isOff?: boolean }) { + createBanner(adUnitId: string, opts?: { type?: number; bannerWidth?: number, offsetY?: number; adIntervals?: number, isOff?: boolean,isCreate?:boolean }) { return WxBanner.I.create(adUnitId, opts); } /** @@ -44,7 +45,7 @@ export default class AdService { * @param adUnitId */ createInterstitialAd(adUnitId: string) { - if (cc.sys.platform === cc.sys.BYTEDANCE_GAME) { + if (sys.platform === sys.Platform.BYTEDANCE_MINI_GAME) { return DouyinInterstitial.showInterstitialAd(adUnitId); } else { return WxInterstitial.showInterstitialAd(adUnitId) diff --git a/wxsdk/service/DataService.ts b/wxsdk/service/DataService.ts index ba44e5d..8e22dab 100644 --- a/wxsdk/service/DataService.ts +++ b/wxsdk/service/DataService.ts @@ -17,7 +17,7 @@ export default class DataService { // 0点数据变动 let expiration = +((this.nextDay() - Date.now()) / 1000).toFixed(0); setTimeout(this.resetData.bind(this), expiration * 1000); - if (typeof wx != 'undefined') { + if (typeof wx != 'undefined' || typeof my != 'undefined') { wx.onShow(this.onShow.bind(this)); wx.onHide(this.onHide.bind(this)); } diff --git a/wxsdk/service/GameService.ts b/wxsdk/service/GameService.ts index 8d9b047..bf7535d 100644 --- a/wxsdk/service/GameService.ts +++ b/wxsdk/service/GameService.ts @@ -1,12 +1,14 @@ -import DataService from "./DataService"; -import { SDKApi } from "../http/SDKApi"; +import { sys } from "cc"; import { GAMEDATA, SDKVersion, __LOG__ } from "../base/SDKConst"; -import WxLogin from "../wx/WxLogin"; +import DouyinPay from "../douyin/DouyinPay"; +import { SDKApi } from "../http/SDKApi"; +import QQPay from "../qq/QQPay"; import WxApi from "../wx/WxApi"; +import WxLogin from "../wx/WxLogin"; import WxPay from "../wx/WxPay"; import WxSystem from "../wx/WxSystem"; -import DouyinPay from "../douyin/DouyinPay"; -import QQPay from "../qq/QQPay"; +import DataService from "./DataService"; +import ZfbPay from "../alipay/zfbPay"; export default class GameService { @@ -69,31 +71,22 @@ export default class GameService { } - subScribe(tmplIds: Array, ids: Array): Promise { + subScribe(tmplIds: Array, success: Function, fail: Function): Promise { return new Promise((resolve, reject) => { WxApi.I.subscribeMessage(tmplIds) .then((ret: any) => { ret = ret || {}; let acceptKeys = tmplIds.filter((idKey: string) => ret[idKey] && ret[idKey] === 'accept'); if (!acceptKeys.length) { - reject({ errCode: 0, errMsg: '点击取消订阅' }); + fail() + resolve({ errCode: 0, errMsg: '点击取消订阅' }); } else { - let uid = +DataService.I.UserId; - let token = DataService.I.Token + ''; - let openid = DataService.I.OpenId + ''; - let id = ids//JSON.stringify() - SDKApi.subscribe({ - uid, - token, - openid, - status: 1, - id, - }) - resolve({ code: 0, msg: '订阅成功!' }) + success(acceptKeys) + console.log('订阅成功', ret, acceptKeys) + resolve(ret); } - }) - .catch(err => reject(err)); + .catch(err => resolve(err)); }); } @@ -104,10 +97,12 @@ export default class GameService { * @returns */ pay(params: { payid: string, goodid: string, money: number; orderid: string }, opts: any = {}) { - if (cc.sys.platform === cc.sys.BYTEDANCE_GAME) { + if (sys.platform === sys.Platform.BYTEDANCE_MINI_GAME) { return DouyinPay.I.pay(params, opts); } else { - if (typeof qq != 'undefined') { + if (typeof my != 'undefined') { + return ZfbPay.I.pay(params, opts); + } else if (typeof qq != 'undefined') { console.log("QQ支付") return QQPay.I.pay(params, opts); } else { @@ -161,19 +156,18 @@ export default class GameService { /** * 更换昵称和头像 */ - updateNickname(nickname: string, headurl: string) { + updateNickname(nickname: string, headurl: string) { let gameid = GAMEDATA.game_id; let uid = DataService.I.UserId; let token = DataService.I.Token; let pkv = SDKVersion; return SDKApi.updateNickname({ - gameid,uid,token,pkv, + gameid, uid, token, pkv, nickname, headurl }) } - /** * 构建登录/弱登录公用参数 */ diff --git a/wxsdk/service/LogService.ts b/wxsdk/service/LogService.ts index 3cdeb6e..e238bb8 100644 --- a/wxsdk/service/LogService.ts +++ b/wxsdk/service/LogService.ts @@ -458,25 +458,25 @@ export default class LogService { /** * 客户端日志 */ - clientLog(content, level = LogLevel.debug) { + clientLog(content, level = SDKLogLevel.debug) { SDKApi.client_log({ APIVersion: '0.6.0', gameid: GAMEDATA.game_id, cacheUserId: StorageUtils.I.get("userId") || "0", - level: LogLevel[level], + level: SDKLogLevel[level], content }) switch (level) { - case LogLevel.error: + case SDKLogLevel.error: console.error(content); break; - case LogLevel.debug: + case SDKLogLevel.debug: console.log(content); break; - case LogLevel.info: + case SDKLogLevel.info: console.info(content); break; - case LogLevel.warning: + case SDKLogLevel.warning: console.warn(content); break; default: @@ -586,7 +586,7 @@ export default class LogService { error:更严重的问题,软件没能执行一些功能 critical:一个严重的错误,这表明程序本身可能无法继续运行 */ -export enum LogLevel { +export enum SDKLogLevel { debug, info, warning, diff --git a/wxsdk/service/ShareVideoService.ts b/wxsdk/service/ShareVideoService.ts index 91f3fa5..63ea6fe 100644 --- a/wxsdk/service/ShareVideoService.ts +++ b/wxsdk/service/ShareVideoService.ts @@ -1,11 +1,12 @@ -import { GAMEDATA } from "../base/SDKConst"; -import { ShareVideoType } from "../base/SDKEnum"; -import { SDKApi } from "../http/SDKApi"; -import SDKShare from "../share/SDKShare"; -import SDKVideo from "../share/SDKVideo"; +import { ShareVideoType, ShareVideoFrom } from "../base/SDKEnum"; import RandomUtils from "../utils/RandomUtils"; -import DataService from "./DataService"; import ShareData from "./entity/ShareData"; +import SDKShare from "../share/SDKShare"; +import { __LOG__, GAMEDATA } from "../base/SDKConst"; +import { SDKApi } from "../http/SDKApi"; +import DataService from "./DataService"; +import SDKVideo from "../share/SDKVideo"; +import { sys } from "cc"; export default class ShareVideoService { private forwardKey?: string; @@ -27,19 +28,28 @@ export default class ShareVideoService { this.forward(this.forwardKey); } - async init() { + private cnt: number = 1 + async initList() { //初始化List let data = await SDKApi.ShareList(); + if (data.code) { + console.log('拉取ShareList失败!') + setTimeout(this.initList.bind(this), 200 * this.cnt) + this.cnt++; + return + } + console.log('拉取ShareList成功!') + console.log('拉取ShareList成功!',JSON.stringify(data)); this.setShareVideoData(data); - // console.log(JSON.stringify(data)) + if (this.forwardKey) this.forward(this.forwardKey); + } + async init() { + this.initList(); SDKShare.I.updateShareMenu(true);//打开群分享 - - if (cc.sys.platform === cc.sys.WECHAT_GAME) { + if (sys.platform === sys.Platform.WECHAT_GAME) { if (GAMEDATA.shareMessageToFriend.scene > 0) { wx.setMessageToFriendQuery({ shareMessageToFriendScene: GAMEDATA.shareMessageToFriend.scene }) } } - - if (this.forwardKey) this.forward(this.forwardKey); } preload = true; @@ -62,26 +72,22 @@ export default class ShareVideoService { share_id: id, query: this.createQuery({ share_key: key, share_id: id, query: opts.query }), }; - let multiton = false; if (opts) { if (opts.title) _params.title = opts.title; if (opts.img_url) _params.imageUrl = opts.img_url; if (opts.share_type) typ = opts.share_type; - if (opts.hasOwnProperty('multiton')) { - multiton = opts.multiton; - }; } // console.log("share_query",JSON.stringify(_params), _params.query); switch (+typ) { case ShareVideoType.Video: - SDKVideo.I.show(shareKey, videoid, multiton).then(success => { + SDKVideo.I.show(shareKey, videoid).then(success => { resolve(success) }).catch(err => { reject(err); }) break; case ShareVideoType.VideoToShare: - SDKVideo.I.show(shareKey, videoid, multiton).then(success => { + SDKVideo.I.show(shareKey, videoid).then(success => { resolve(success) }).catch(err => { if (err.code !== 1000 && err.code !== 1003) {//1000关闭1003正在播放 @@ -107,6 +113,46 @@ export default class ShareVideoService { resolve({}) break; } + // share_desc = opts.shareTitle || share_desc; + // share_desc = StringUtils.stringFormat(share_desc, opts.formater); + // let shareMsg = { + // title: share_desc, + // imageUrl: opts.shareImg || share_icon, + // query + // }; + // // __LOG__ && console.error(`SDK ShareVideoService ${opts.shareForward ? 'forward 右上角分享:' : 'share 主动拉起分享:'}`); + // // __LOG__ && console.error(`SDK ShareVideoService 分享参数对象shareMsg: ${JSON.stringify(shareMsg)}`); + // // __LOG__ && console.error('SDK ShareVideoService 分享扩展参数', opts); + // DebugUtils.I.dynamic(`====> PCSDK ShareVideoService share 分享query: ${query}`); + // let success = (ret: any) => { + // // __LOG__ && console.error(`SDK ShareVideoService ${opts.shareForward ? 'forward 右上角分享:' : 'share 主动拉起分享:'} 成功回调: ${share_id}`); + // if (!opts.__GROUP) { + // // 不是群分享的情况下,进行统计,群分享需要验证 + // TempService.I.add(TempDataKeys.ShareSuccess, 1); + // share_id && LogService.I.tacticShare(share_id, share_key, TacticType.ShareSuccess); + // } + // resolve({ ...ret, share_id, share_key: shareKey }); + // }; + // let fail = (err: any) => { + // // __LOG__ && console.error(`SDK ShareVideoService ${opts.shareForward ? 'forward 右上角分享:' : 'share 主动拉起分享:'} 失败回调: ${share_id}`); + // if (!opts.__GROUP) { + // share_id && LogService.I.tacticShare(share_id, share_key, TacticType.ShareInterrupt); + // } + // reject({ ...err, share_id, share_key: shareKey }); + // }; + // if (opts.shareForward) + // // 右上角转发 + // Platform.I.forward(shareMsg, { + // ...opts, + // success, + // fail, + // context: this + // }); + // else + // // 普通分享 + // Platform.I.share(shareMsg, opts) + // .then((ret: any) => success(ret)) + // .catch((err: any) => fail(err)); }); } @@ -123,6 +169,129 @@ export default class ShareVideoService { // console.log("forward", JSON.stringify(params)); SDKShare.I.forward(params); } + + /** + * 分享自动入口 + * @param shareKey + * @param opts { + * type: 当shareType为VideoAndShare时候,该参数有用,0:分享 1:视频 + * context: 函数执行上下文 + * fail: Function 失败函数 + * success: Function 成功函数 + * } + */ + // dispatch(shareKey: string, opts: any = {}, queryObj: { [key: string]: number | string } = {}) { + // let shareData = this.getShareVideoData(shareKey); + // let { share_open, share_wxad_id } = shareData; + // opts = { + // ...opts, + // share_wxad_id, + // __ShareData__: shareData + // }; + // this.dispatchType(+share_open, shareKey, opts, queryObj); + // } + + shareDispatch(shareKey: string, opts: any = {}, queryObj: { [key: string]: number | string } = {}) { + // this.dispatch(shareKey, opts, queryObj); + } + + /** + * 根据分享类型进行处理 + * @param shareType + * @param shareKey + * @param opts { + * type: 当shareType为VideoAndShare时候,该参数有用,0:分享 1:视频 + * context: 函数执行上下文 + * fail: Function 失败函数 + * success: Function 成功函数 + * } + */ + dispatchType(shareType: ShareVideoType, shareKey: string, opts: any = {}, queryObj: { [key: string]: number | string } = {}) { + // if (Platform.IsWx && OnlineService.I.getParamsInt(OnlineKeys.ShareUnlock, 1) !== 1) + // shareType = ShareVideoType.None; + + // let share_wxad_id = opts.share_wxad_id || (opts.__ShareData__ || this.getShareVideoData(shareKey) || {}).share_wxad_id; + // switch (shareType) { + // case ShareVideoType.None: // 无分享 + // this.handleSuccess(opts, shareType, ShareVideoFrom.None, null); + // break; + + // case ShareVideoType.Share: // 同步分享 + // // 同步分享点:是否开启后台配置中如果存在视频ID,则自动切换为视频点 + // if (opts.shareAutoVideo && share_wxad_id) { + // this.dispatchType(ShareVideoType.VideoToShare, shareKey, opts, queryObj); + // break; + // } + // this.group(shareKey, queryObj, opts) + // .then(ret => this.handleSuccess(opts, shareType, ShareVideoFrom.Share, ret)) + // .catch(err => this.handleFail(opts, shareType, ShareVideoFrom.Share, err)); + // break; + + // case ShareVideoType.ShareAysnc: // 异步分享 + // break; + + // case ShareVideoType.ShareIntegral: // 分享积分 + // // 是否开启分享积分,且配置为分享积分 + // if (IntegralService.I.IsOpen) { + // let data = IntegralService.I.convert(); + // if (data) { + // opts.shareIntegralData = data; + // this.dispatchType(data.shareType, shareKey, opts, queryObj); + // } else { + // // 超过了现在,直接执行失败:今日已达分享上限次数,请明日再来 + // this.handleFail(opts, shareType, ShareVideoFrom.Share, { ...ShareVideoError.ShareOverLimit }); + // } + // } else { + // // 如果配置了分享积分,但是未开启开关,则推:无视频则分享 + // this.dispatchType(ShareVideoType.VideoToShare, shareKey, opts, queryObj); + // } + // break; + + // case ShareVideoType.Video: // 看视频 + // Platform.I.video(shareKey, share_wxad_id) + // .then(ret => this.handleSuccess(opts, shareType, ShareVideoFrom.Video, ret)) + // .catch((err: any) => this.handleFail(opts, shareType, ShareVideoFrom.Video, err)); + // break; + + // case ShareVideoType.VideoToShare: // 无视频则分享 + // if (!share_wxad_id) { + // this.group(shareKey, queryObj, opts) + // .then(ret => this.handleSuccess(opts, shareType, ShareVideoFrom.Share, ret)) + // .catch(err => this.handleFail(opts, shareType, ShareVideoFrom.Share, err)); + // return; + // } + // Platform.I.video(shareKey, share_wxad_id) + // .then((ret) => this.handleSuccess(opts, shareType, ShareVideoFrom.Video, ret)) + // .catch((err: any) => { + // // 拉取视频失败/视频UID不存在/微信版本过低,暂不支持看视频,自动切换到分享 + // let { VideoFail, VideoInvalid, VideoNotOpen } = ShareVideoError; + // if (err && (err.code === VideoFail.code || err.code === VideoInvalid.code || err.code === VideoNotOpen.code)) + // this.group(shareKey, queryObj, opts) + // .then(ret => this.handleSuccess(opts, shareType, ShareVideoFrom.Share, ret)) + // .catch(err => this.handleFail(opts, shareType, ShareVideoFrom.Share, err)); + // else + // this.handleFail(opts, shareType, ShareVideoFrom.Video, err); + // }); + // break; + + // case ShareVideoType.VideoAndShare: // 看视频 + // if (share_wxad_id && opts.type === 1) { + // Platform.I.video(shareKey, share_wxad_id) + // .then(ret => this.handleSuccess(opts, shareType, ShareVideoFrom.Video, ret)) + // .catch((err: any) => this.handleFail(opts, shareType, ShareVideoFrom.Video, err)); + // } else { + // this.group(shareKey, queryObj, opts) + // .then(ret => this.handleSuccess(opts, shareType, ShareVideoFrom.Share, ret)) + // .catch(err => this.handleFail(opts, shareType, ShareVideoFrom.Share, err)); + // } + // break; + // } + } + + shareWithType(shareType: ShareVideoType, shareKey: string, opts: any = {}, queryObj: { [key: string]: number | string } = {}) { + this.dispatchType(shareType, shareKey, opts, queryObj); + } + /** * 分享id * @param shareKey @@ -143,6 +312,25 @@ export default class ShareVideoService { getShareVideoType(shareKey: string): ShareVideoType { let shareData = this.getShareVideoData(shareKey); let shareType: ShareVideoType = +shareData.typ; + // // 木有开启分享,直接返回None + // if (Platform.IsWx && OnlineService.I.getParamsInt(OnlineKeys.ShareUnlock, 1) !== 1) + // return ShareVideoType.None; + + // // 后台配置视频,判断是否加载出错过,出错返回分享,否则直接返回 + // if (shareType === ShareVideoType.Video || shareType === ShareVideoType.VideoAndShare || shareType === ShareVideoType.VideoToShare) { + // // 检测视频加载失败 + // if (Platform.I.isVideoErrored()) + // return ShareVideoType.Share; + // else + // return shareType; + // } + + // // 是否开启分享积分,且配置为分享积分 + // if (shareType === ShareVideoType.ShareIntegral && IntegralService.I.IsOpen) { + // let data = IntegralService.I.convert(); + // if (data) + // return data.shareType; + // } return shareType; } @@ -154,6 +342,55 @@ export default class ShareVideoService { return this.getShareVideoType(shareKey); } + private handleSuccess(opts: any, shareType: ShareVideoType, from: ShareVideoFrom, ret: any) { + // // 判断分享规则 + // if (IntegralService.I.IsOpen && opts.shareIntegralData && from === ShareVideoFrom.Share) { + // let shareNum = IntegralService.I.IntegralShareNum; + // if (shareNum === 0) { + // // 第1次分享 + // IntegralService.I.setIntegralShareNum(); + // IntegralService.I.resetShareRatio(); + // __LOG__ && console.error(`SDK ShareVideoService 分享积分 第1次分享: 初始来源:${shareType}, 类型:${from}, 分享次数:${shareNum}`); + // // 设定:第一次强制失败 + // // return this.handleFail(opts, shareType, from, { ...ShareVideoError.ShareRuleFail }, true); + // } else { + // // 第n次分享 + // IntegralService.I.setIntegralShareNum(); + // IntegralService.I.addShareRatio(); + + // let shareRatio = IntegralService.I.ShareRatio; + // let radomRatio = +Math.random().toFixed(2); + // __LOG__ && console.error(`SDK ShareVideoService 分享积分 第${shareNum}次分享: 初始来源:${shareType}, 类型:${from}, 分享次数:${shareNum}, 随机概率:${radomRatio}, 失败概率:${shareRatio}`); + // if (radomRatio <= shareRatio) { + // __LOG__ && console.error(`SDK ShareVideoService 分享积分 触发失败规则:分享强制失败, radomRatio <= shareRatio: ${radomRatio} <= ${shareRatio}`); + // return this.handleFail(opts, shareType, from, { ...ShareVideoError.ShareRuleFail }, true); + // } + // } + + // // 是否同步分享积分数据 + // let { intergral, isAsyncNum } = opts.shareIntegralData; + // isAsyncNum && LocalService.I.saveVideoOverShareNum(intergral); + // __LOG__ && isAsyncNum && console.error(`SDK ShareVideoService 分享积分 触发视频看完后,再次分享次数限制更新成功,成功后数量:${LocalService.I.getVideoOverShareNum(intergral)}`); + // } + + // let success = opts.success || function () { }; + // let context = opts.context || this; + // typeof success === 'function' && success.call(context, from, ret); + // (from === ShareVideoFrom.Share) && TempService.I.add(TempDataKeys.ShareSuccess, 1); + } + + private handleFail(opts: any, shareType: ShareVideoType, from: ShareVideoFrom, err: any, isFromIntegral?: boolean) { + // if (err instanceof Error) return; + // // 判断来自分享积分规则,则重置分享概率 + // if (IntegralService.I.IsOpen && opts.shareIntegralData && from === ShareVideoFrom.Share) { + // __LOG__ && console.error(`SDK ShareVideoService 强制失败分享,回滚到: ${IntegralService.I.ShareRatioInit}`); + // IntegralService.I.resetShareRatio(); + // } + // let fail = opts.fail || function () { }; + // let context = opts.context || this; + // fail && fail.call(context, from, err); + } + private setShareVideoData(data: any) { (data.data || []).forEach((item: any) => { this.shareObjs[item.key] = this.shareObjs[item.key] || []; @@ -165,11 +402,19 @@ export default class ShareVideoService { let list: Array = this.shareObjs[shareKey]; if (!list) { list = this.shareObjs.default; + // let shareData: ShareData = CfgManager.I.config.ShareData; + // if (!shareData) throw new TypeError('SDK ShareVideoService - 请在config.js中配置ShareData'); + // let share_open = shareData.share_wxad_id ? ShareVideoType.Video : ShareVideoType.Share; + // return { ...shareData, share_id: 99999 + '', share_key: shareKey, share_open }; } let index = RandomUtils.rand(0, list.length); return list[index]; } + onShareTimeline(title?: string, imageUrl?: string, imagePreviewUrl?: string, query?: string) { + return SDKShare.I.onShareTimeline(title, imageUrl, imagePreviewUrl, query); + } + private createQuery(params = {}): string { let q = params["query"]; delete params["query"]; diff --git a/wxsdk/service/entity/SdkData.ts.meta b/wxsdk/service/entity/SdkData.ts.meta index 9e6fe1a..2f1044d 100644 --- a/wxsdk/service/entity/SdkData.ts.meta +++ b/wxsdk/service/entity/SdkData.ts.meta @@ -1,9 +1,9 @@ { - "ver": "1.0.8", + "ver": "4.0.23", + "importer": "typescript", + "imported": true, "uuid": "f09e38ff-4d68-417e-8904-949127e4d321", - "isPlugin": false, - "loadPluginInWeb": true, - "loadPluginInNative": true, - "loadPluginInEditor": false, - "subMetas": {} -} \ No newline at end of file + "files": [], + "subMetas": {}, + "userData": {} +} diff --git a/wxsdk/service/entity/ShareData.ts.meta b/wxsdk/service/entity/ShareData.ts.meta index f510aaa..50c2b54 100644 --- a/wxsdk/service/entity/ShareData.ts.meta +++ b/wxsdk/service/entity/ShareData.ts.meta @@ -1,9 +1,9 @@ { - "ver": "1.0.8", + "ver": "4.0.23", + "importer": "typescript", + "imported": true, "uuid": "d9db9b13-470b-456d-95ff-75354ec23ca0", - "isPlugin": false, - "loadPluginInWeb": true, - "loadPluginInNative": true, - "loadPluginInEditor": false, - "subMetas": {} -} \ No newline at end of file + "files": [], + "subMetas": {}, + "userData": {} +} diff --git a/wxsdk/share/SDKShare.ts b/wxsdk/share/SDKShare.ts index 950bf0b..956baa9 100644 --- a/wxsdk/share/SDKShare.ts +++ b/wxsdk/share/SDKShare.ts @@ -2,6 +2,7 @@ import SimulateShare from "./SimulateShare"; import { __LOG__, ShareVideoError } from "../base/SDKConst"; import LogService from "../service/LogService"; import { DOT_SHARE_TYPE } from "../base/SDKEnum"; +import AlipayApi from "../alipay/AlipayApi"; export default class SDKShare { private shareSimulate: boolean @@ -47,14 +48,19 @@ export default class SDKShare { reject(null); } }; - // 是否模拟分享 - this.shareSimulate && !opts.closeSimulate && this.simulate({ ...callbackObj }); - - if(this.shareSimulate && opts.closeSimulate){ + + if (this.shareSimulate && opts.closeSimulate) { LogService.I.share(shareKey, share_id, DOT_SHARE_TYPE.share) } // 主动拉起转发 - wx.shareAppMessage(commonObj); + if (typeof my != 'undefined') { + //模拟分享支付宝上面会失败 + return AlipayApi.I.shareAppMessage(commonObj, callbackObj) + } else { + // 是否模拟分享 + this.shareSimulate && !opts.closeSimulate && this.simulate({ ...callbackObj }); + wx.shareAppMessage(commonObj); + } }); } /** @@ -75,6 +81,27 @@ export default class SDKShare { forward(params: any, opts: any = {}) { let me = this; let { title, imageUrl, query, imageUrlId } = params; + if (typeof my != 'undefined') { + my.onShareAppMessage = function () { + return { + title: title, + scImgUrl: imageUrl, + bgImgUrl: 'https://wxsdk-cdn.miso-lab.com/moon-island/share/zfbshare.jpeg', + success: (ret?: any) => { + __LOG__ && console.error('WxShare forward success'); + opts.success && opts.success.call(opts.context, ret); + }, + fail: (err?: any) => { + __LOG__ && console.error('WxShare forward fail'); + opts.fail && opts.fail.call(opts.context, err); + }, + complete: function (e) { + + } + } + } + return; + } wx.onShareAppMessage(function () { let obj = { title, @@ -98,8 +125,12 @@ export default class SDKShare { me.shareSimulate && !opts.closeSimulate && me.simulate({ ...obj }); return obj; }); - // 显示当前页面的转发按钮 - wx.showShareMenu({}); + // 显示当前页面的转发按钮 "shareAppMessage"表示“发送给朋友”按钮,"shareTimeline"表示“分享到朋友圈”按钮 + wx.showShareMenu({ + withShareTicket: true, + menus: ['shareAppMessage', 'shareTimeline'] + }) + } private createQuery(params = {}): string { @@ -120,4 +151,18 @@ export default class SDKShare { SimulateShare.I.bind(data); } + onShareTimeline(title?: string, imageUrl?: string, imagePreviewUrl?: string, query?: string) { + if (wx?.onShareTimeline) { + wx.onShareTimeline(() => { + return { + title,//朋友圈标题 + imageUrl, // 朋友圈 小图 + imagePreviewUrl,//朋友圈 预览大图 + query, + } + }) + } + + } + } \ No newline at end of file diff --git a/wxsdk/share/SDKVideo.ts b/wxsdk/share/SDKVideo.ts index 29ca22d..943b86d 100644 --- a/wxsdk/share/SDKVideo.ts +++ b/wxsdk/share/SDKVideo.ts @@ -1,6 +1,9 @@ +import { sys } from "cc"; import { ShareVideoError, __LOG__ } from "../base/SDKConst"; import { DOT_AD_TYPE, DOT_AD_STATUS } from "../base/SDKEnum"; import LogService from "../service/LogService"; +import TAMgr from "../../ta/TAMgr"; +import AlipayApi from "../alipay/AlipayApi"; /* * 激烈视频 @@ -8,7 +11,6 @@ import LogService from "../service/LogService"; export default class SDKVideo { private _isPlaying: boolean; private _isErrored: boolean; - private _isMultiton: boolean; private resolve: any; private reject: any; private videoAd: any; @@ -20,7 +22,6 @@ export default class SDKVideo { this.videoKey = ''; this._isPlaying = false; this._isErrored = false; - this._isMultiton = false; } get isErrored() { @@ -36,41 +37,57 @@ export default class SDKVideo { preloadVideo(adUnitId: string) { if (this.preloadVideoAd || this.isPreload) return this.isPreload = true; - let ad = wx.createRewardedVideoAd({ - adUnitId, - }); + let ad; + if (typeof my != 'undefined') { + ad = AlipayApi.I.createRewardedVideoAd(adUnitId); + } else { + ad = wx.createRewardedVideoAd({ + adUnitId, + }); + } ad.onError(this.preError); - ad.load().then(this.handleLoaded2).catch(() => { - this.isPreload = false - }) - this.videoAd2 = ad; + //支付宝同时调用create 和load 需要间隔时间 + if (typeof my != 'undefined') { + let self = this; + setTimeout(() => { + self.videoAd2 = ad; + ad.load().then(self.handleLoaded2).catch(() => { + self.isPreload = false + }) + }, 300) + } else { + ad.load().then(this.handleLoaded2).catch(() => { + this.isPreload = false + }) + this.videoAd2 = ad; + } } private preError() { let that = SDKVideo.I; - that.isPreload = false + that.isPreload = false; + __LOG__ && console.warn("视频预加载失败") } private handleLoaded2() { let that = SDKVideo.I; that.preloadVideoAd = that.videoAd2; that.isPreload = false - __LOG__ && console.warn("视频预加载成功", that.preloadVideoAd) + __LOG__ && console.warn("视频预加载成功") + // that.preloadVideoAd.ttttttt = '111111' + // console.warn(that.preloadVideoAd.isReady()); } offPreload() { let that = SDKVideo.I; - that.preloadVideoAd.offError(that.preError); + if (typeof my != 'undefined') { + that.preloadVideoAd = null; + } else { + that.preloadVideoAd.offError(that.preError); + } } - /** - * - * @param videoKey - * @param adUnitId - * @param multiton 多例 - * @returns - */ - async show(videoKey: string, adUnitId: string, multiton: boolean = false): Promise { + async show(videoKey: string, adUnitId: string): Promise { return new Promise(async (resolve, reject) => { if (this.isPlaying) return reject({ ...ShareVideoError.VideoPlaying }); @@ -79,25 +96,40 @@ export default class SDKVideo { return reject({ ...ShareVideoError.VideoInvalid }); LogService.I.adStat(videoKey, this.adUnitId, DOT_AD_TYPE.video, DOT_AD_STATUS.request); - let videoAd; - let hasVideo; - if (this.preloadVideoAd && !multiton) { - __LOG__ && console.log("使用预加载视频", this.preloadVideoAd) + TAMgr.Ins.dot('video', { + ad_key: videoKey, + type: DOT_AD_STATUS.request + }) + let videoAd + let hasVideo + if (this.preloadVideoAd) { + __LOG__ && console.log("使用预加载视频") hasVideo = true - this.offPreload(); videoAd = this.preloadVideoAd; + this.offPreload() + // this.preloadVideo(adUnitId); } else { __LOG__ && console.log("不使用预加载视频") hasVideo = false; - videoAd = wx.createRewardedVideoAd({ - adUnitId, - multiton: true - }); + if (typeof my != 'undefined') { + try { + videoAd = AlipayApi.I.createRewardedVideoAd(adUnitId); + } catch (error) { + __LOG__ && console.log("不使用预加载视频23:", JSON.stringify(error)) + } + } else { + videoAd = wx.createRewardedVideoAd({ + adUnitId, + }); + } // this.preloadVideo(adUnitId); } - this._isMultiton = !hasVideo; - if (!videoAd) + // let videoAd = wx.createRewardedVideoAd({ + // adUnitId + // }); + if (!videoAd) { return reject({ ...ShareVideoError.VideoNotOpen }); + } this._isPlaying = true; this._isErrored = false; @@ -105,6 +137,7 @@ export default class SDKVideo { this.adUnitId = adUnitId; this.resolve = resolve; this.reject = reject; + this.videoAd = videoAd; videoAd.onClose(this.handleClose); videoAd.onError(this.onError); @@ -119,6 +152,14 @@ export default class SDKVideo { } } else { try { + if (typeof my != 'undefined') { + await new Promise(resolve => { + setTimeout(() => { + resolve(null) + }, 300); + + }); + } await videoAd.load() await this.handleLoaded() } catch (error) { @@ -126,6 +167,7 @@ export default class SDKVideo { } } + this.preloadVideo(adUnitId); __LOG__ && console.warn('====> PCSDK WxVideo 请求视频adUnitId', adUnitId); }); } @@ -139,11 +181,14 @@ export default class SDKVideo { private async handleLoaded() { let that = SDKVideo.I; try { - // __LOG__ && console.warn("handleLoaded2", that.videoAd, that.videoAd.isReady()); + __LOG__ && console.warn("handleLoaded2"); LogService.I.adStat(this.videoKey, this.adUnitId, DOT_AD_TYPE.video, DOT_AD_STATUS.show) - - if (cc.sys.platform === cc.sys.WECHAT_GAME) { - if (that.videoAd.isReady()) {//抖音没有 isReady + TAMgr.Ins.dot('video', { + ad_key: this.videoKey, + type: DOT_AD_STATUS.show + }) + if (sys.platform === sys.Platform.WECHAT_GAME && typeof qq == 'undefined') { + if (that.videoAd.isReady()) {//抖音、qq 没有 isReady that.show_time = Date.now(); await that.videoAd.show(); } else { @@ -173,22 +218,26 @@ export default class SDKVideo { if (res && res.isEnded || res === undefined) { // 统计看视频成功 LogService.I.adStat(that.videoKey, that.adUnitId, DOT_AD_TYPE.video, DOT_AD_STATUS.complete) + TAMgr.Ins.dot('video', { + ad_key: that.videoKey, + type: DOT_AD_STATUS.complete + }) that.resolve && that.resolve({ type: 2 }); } else { // console.log("视频关闭时间:", t) LogService.I.adStat(that.videoKey, that.adUnitId, DOT_AD_TYPE.video, DOT_AD_STATUS.interrupt, t) + TAMgr.Ins.dot('video', { + ad_key: that.videoKey, + type: DOT_AD_STATUS.interrupt + }) that.reject && that.reject({ ...ShareVideoError.VideoQuit }); } - that.videoAd.offClose(that.handleClose); - if (that._isMultiton) { - that.videoAd.destroy(); + if (typeof my != 'undefined') { that.videoAd = null; + } else { + that.videoAd.offClose(that.handleClose); } - // if (that.preloadVideoAd) { - // that.preloadVideoAd.destroy(); - // that.preloadVideoAd = null; - // } - that.preloadVideo(that.adUnitId); + that._isPlaying = false; that._isErrored = false; } @@ -197,8 +246,16 @@ export default class SDKVideo { __LOG__ && console.warn('====> PCSDK WxVideo 加载视频广告失败', err); let that = SDKVideo.I; LogService.I.adStat(that.videoKey, that.adUnitId, DOT_AD_TYPE.video, DOT_AD_STATUS.fail) + TAMgr.Ins.dot('video', { + ad_key: that.videoKey, + type: DOT_AD_STATUS.fail + }) that.reject && that.reject({ ...ShareVideoError.VideoFail }); - that.videoAd && that.videoAd.offClose && that.videoAd.offClose(that.handleClose); + if (typeof my != 'undefined') { + + } else { + that.videoAd && that.videoAd.offClose && that.videoAd.offClose(that.handleClose); + } that._isPlaying = false; that._isErrored = true; } diff --git a/wxsdk/utils/RandomUtils.ts b/wxsdk/utils/RandomUtils.ts index d3d8d24..48e6730 100644 --- a/wxsdk/utils/RandomUtils.ts +++ b/wxsdk/utils/RandomUtils.ts @@ -20,7 +20,7 @@ export default class RandomUtils { static rand(min: number, max: number) { min = min || 0; max = max || 10000; - return Math.floor(Math.random() * 10000) % (max - min) + min; + return Math.floor(Math.random() * 10000) % (max - min) + min; } static rang(min: number, max: number) { @@ -30,4 +30,5 @@ export default class RandomUtils { static randFloat(min: number, max: number) { return parseFloat((Math.random() * (max - min) + min).toFixed(2)); } + } diff --git a/wxsdk/wx/WxApi.ts b/wxsdk/wx/WxApi.ts index beb0f7a..cec8d00 100644 --- a/wxsdk/wx/WxApi.ts +++ b/wxsdk/wx/WxApi.ts @@ -371,8 +371,8 @@ export default class WxApi { /** * 米大师充值 */ - requestMidasPayment(params: { mode: string; env: number; offerId: string; currencyType: string; platform: string; buyQuantity: number; zoneId: string }): Promise { - let { mode, env, offerId, currencyType, platform, buyQuantity, zoneId } = params; + requestMidasPayment(params: { mode: string; env: number; offerId: string; currencyType: string; platform: string; buyQuantity: number; zoneId: string,outTradeNo:string }): Promise { + let { mode, env, offerId, currencyType, platform, buyQuantity, zoneId,outTradeNo } = params; console.warn('====> PCSDK WxApi requestMidasPayment 支付参数', { mode, env, @@ -380,7 +380,8 @@ export default class WxApi { currencyType, platform, buyQuantity, - zoneId + zoneId, + outTradeNo }); return new Promise((resolve, reject) => { wx.requestMidasPayment({ @@ -391,6 +392,7 @@ export default class WxApi { platform, buyQuantity, zoneId, + outTradeNo, success: ret => { if (ret && ret.errMsg === 'requestMidasPayment:ok') resolve(ret); diff --git a/wxsdk/wx/WxBanner.ts b/wxsdk/wx/WxBanner.ts index 7d9f3c0..24fda0e 100644 --- a/wxsdk/wx/WxBanner.ts +++ b/wxsdk/wx/WxBanner.ts @@ -42,7 +42,7 @@ export default class WxBanner { private queue: Function[] = []; private isEnd: boolean = false; - create(adUnitId: string, opts?: { type?: number; bannerWidth?: number, offsetY?: number; adIntervals?: number, isOff?: boolean }) { + create(adUnitId: string, opts?: { type?: number; bannerWidth?: number, offsetY?: number; adIntervals?: number, isOff?: boolean ,isCreate?:boolean}) { this.bannerParams = opts || {}; if (opts && opts.bannerWidth) { this.bannerWidth = opts.bannerWidth; @@ -74,10 +74,15 @@ export default class WxBanner { // this.bannerAd = wx.createGameBanner({ adUnitId, style: { left: style.left, top: this.bannerHeight } }); // else if (this.bannerAd) { - if (!opts || (opts && !opts.isOff)) { - this.show(false); + if(opts && opts.isCreate){ + //重新创建 + console.log("重新创建banner") + }else{ + if (!opts || (opts && !opts.isOff)) { + this.show(false); + } + return } - return } this.bannerAd = wx.createBannerAd({ adUnitId, style, adIntervals: this.bannerParams.adIntervals }); LogService.I.adStat('banner', this.adUnitId, DOT_AD_TYPE.banner, DOT_AD_STATUS.request) diff --git a/wxsdk/wx/WxInit.ts b/wxsdk/wx/WxInit.ts index 8618ae5..9cc94a7 100644 --- a/wxsdk/wx/WxInit.ts +++ b/wxsdk/wx/WxInit.ts @@ -23,7 +23,7 @@ export default class WxInit { init() { let { platform } = WxSystem.I.SystemData; let launchData = WxLaunch.I.LaunchData; - console.log("启动信息", launchData); + console.log("启动信息", JSON.stringify(launchData)); let { query, scene, referrerInfo } = launchData; let { invite_type, @@ -41,6 +41,7 @@ export default class WxInit { // 抖音投放相关信息 clue_token, ad_id, + promotion_id, creative_id, advertister_id, request_id @@ -58,6 +59,10 @@ export default class WxInit { if (ad_id) { fromChannel = ad_id; } + // 设置抖音投放转化跟踪 v2 + if(promotion_id){ + fromChannel = promotion_id; + } //定向分享统计 if (shareMessageToFriendScene && shareMessageToFriendScene >= 0 && shareMessageToFriendScene <= 50) { diff --git a/wxsdk/wx/WxLogin.ts b/wxsdk/wx/WxLogin.ts index db79da2..ed857e5 100644 --- a/wxsdk/wx/WxLogin.ts +++ b/wxsdk/wx/WxLogin.ts @@ -8,6 +8,7 @@ import LogService from "../service/LogService"; import { DOT_SHARE_TYPE } from "../base/SDKEnum"; import ShareVideoService from "../service/ShareVideoService"; import OnlineService from "../service/OnlineService"; +import AlipayApi from "../alipay/AlipayApi"; export default class WxLogin { /** @@ -17,16 +18,32 @@ export default class WxLogin { * tip2:必须先调用wxLogin才能使用getUserInfo */ async login(isAuthorize: boolean): Promise { - return new Promise(async (resolve, reject) => { - let code = await WxApi.I.login(); - if (isAuthorize) { - WxApi.I.getUserinfo() - .then((ret: any) => this.authedlogin(ret, code, resolve, reject)) - .catch((err: any) => this.weakLogin(err, code, resolve, reject)); - } else { - this.weakLogin({ errCode: 1, msg: '默认未授权登录' }, code, resolve, reject) - } - }); + if (typeof my !== 'undefined') { + return new Promise(async (resolve, reject) => { + console.log("-----login4-------") + let code = await AlipayApi.I.login(); + console.log("-----login5-------") + console.log(code) + if (isAuthorize) { + AlipayApi.I.getUserinfo() + .then((ret: any) => this.authedlogin(ret, code, resolve, reject)) + .catch((err: any) => this.weakLogin(err, code, resolve, reject)); + } else { + this.weakLogin({ errCode: 1, msg: '默认未授权登录' }, code, resolve, reject) + } + }); + } else { + return new Promise(async (resolve, reject) => { + let code = await WxApi.I.login(); + if (isAuthorize) { + WxApi.I.getUserinfo() + .then((ret: any) => this.authedlogin(ret, code, resolve, reject)) + .catch((err: any) => this.weakLogin(err, code, resolve, reject)); + } else { + this.weakLogin({ errCode: 1, msg: '默认未授权登录' }, code, resolve, reject) + } + }); + } } private isFirst: boolean @@ -91,6 +108,8 @@ export default class WxLogin { */ private handleLogin(data: any, resolve: any, isAuthorize: boolean) { // console.log("登录请求结果data", data) + + console.log("-----login5-------") if (data) { // 设置登录信息 if (data.data) { @@ -119,7 +138,10 @@ export default class WxLogin { } catch (error) { console.log("handleExpire_error", error) } - ShareVideoService.I.forward() + // 支付宝没有 + if(typeof my == 'undefined'){ + ShareVideoService.I.forward() + } } } resolve(data) diff --git a/wxsdk/wx/WxPay.ts b/wxsdk/wx/WxPay.ts index b22e40a..12cd525 100644 --- a/wxsdk/wx/WxPay.ts +++ b/wxsdk/wx/WxPay.ts @@ -23,7 +23,8 @@ export default class WxPay { offerId: OfferId, currencyType: CurrencyType, buyQuantity: params.money / 10, - zoneId: ZoneId + zoneId: ZoneId, + outTradeNo:params.orderid }; let extend = ""; for (let key in opts) { @@ -90,7 +91,7 @@ export default class WxPay { } private handlePayError(data: { payid: string, goodid: string, money: number; orderid: string, platform: string }, opts, err: any, reject: any) { - console.log("支付失败", JSON.stringify(err)); + console.log("handlePayError支付失败", JSON.stringify(err)); let type = 2; if (err.errCode + '' == '1') { type = 3; diff --git a/wxsdk/wx/WxSystem.ts b/wxsdk/wx/WxSystem.ts index 8dce24c..c128f16 100644 --- a/wxsdk/wx/WxSystem.ts +++ b/wxsdk/wx/WxSystem.ts @@ -42,14 +42,14 @@ export default class WxSystem { } get SDKVersion() { - return this.data.SDKVersion; + return this.data.SDKVersion || this.data.version; } - get brand(){ + get brand() { return this.data.brand; } - get model(){ + get model() { return this.data.model; } -- libgit2 0.21.0