PlatformTaoBao.ts 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511
  1. /**
  2. 游戏名称:逍遥仙(淘宝)
  3. 小程序ID:
  4. */
  5. import { gameMethod } from "../common/gameMethod";
  6. import { PlayerLogin, PlayerLoginPram } from "../common/Xyc";
  7. import { SevBack } from "../common/Xys";
  8. import Config from "../Config";
  9. import { GameEvent, LoadEvent, PlatEvent } from "../data/const/EventConst";
  10. import { AD_VIDEO_KEY, GameErrCode, PayProductParam, PlatFormDevType } from "../data/const/TypeConst";
  11. import GameDataCenter from "../data/GameDataCenter";
  12. import GameController from "../GameController";
  13. import UIHelp from "../logic/ui/UIHelp";
  14. import EventMng from "../manager/EventMng";
  15. import PlatformBase from "./PlatformBase";
  16. export default class PlatformTaoBao extends PlatformBase {
  17. sdk: any;
  18. gameActivityController: any;
  19. RewardedVideoAd: any;
  20. constructor() {
  21. super()
  22. this.AdXiaDanSuc = false;//初始化
  23. // 切换到前台
  24. const listener = function (res) {
  25. // console.log("-----tb.onShow 回调触发111:", res)
  26. console.log("-----tb.onShow 回调触发222:", this.AdXiaDanSuc)
  27. // if (this.AdXiaDanSuc) {
  28. this.AdXiaDanSuc = false
  29. console.log("有广告任务,发起奖励请求")
  30. // GameDataCenter.adVideo.onTaoBaoXiadanSucc() // 向服务端请求奖励
  31. // }
  32. this.dealQuery(res)
  33. GameDataCenter.audio.resumeMusic()
  34. // IOS系统,在后台切回时似乎回失去常亮功能,这里再调用一次
  35. my.setKeepScreenOn({
  36. keepScreenOn: true
  37. })
  38. EventMng.emit(GameEvent.ON_SHOW_APP)
  39. }
  40. my.onShow((res) => {
  41. console.log("-----tb.onShow 回调触发:", res)
  42. // if (this.AdXiaDanSuc) {
  43. // this.AdXiaDanSuc = false
  44. // console.log("有广告任务,发起奖励请求")
  45. // //连续请求5次
  46. // if (Config.paySuccAdokId != null) {
  47. // clearInterval(Config.paySuccAdokId)
  48. // Config.paySuccAdokId = null
  49. // }
  50. // Config.paySuccAdokIndex = 0
  51. // Config.paySuccAdokId = setInterval(() => {
  52. // Config.paySuccAdokIndex++
  53. // if (Config.paySuccAdokIndex >= 5) {
  54. // clearInterval(Config.paySuccAdokId)
  55. // Config.paySuccAdokId = null
  56. // }
  57. // GameDataCenter.adVideo.onTaoBaoXiadanSucc() // 向服务端请求奖励
  58. // }, 1000)
  59. // }
  60. this.dealQuery(res)
  61. GameDataCenter.audio.resumeMusic()
  62. // IOS系统,在后台切回时似乎回失去常亮功能,这里再调用一次
  63. my.setKeepScreenOn({
  64. keepScreenOn: true
  65. })
  66. EventMng.emit(GameEvent.ON_SHOW_APP)
  67. });
  68. // my.offShow(listener)
  69. const hideListener = function (res) {
  70. console.log("-----tb.onHide 回调触发:", res)
  71. // GameDataCenter.plat.instance.reportRole(ReportRoleType.offline)
  72. // this.dealQuery(res)
  73. GameDataCenter.audio.stopAllEffects()
  74. GameDataCenter.audio.pauseMusic()
  75. }
  76. my.onHide((res) => {
  77. console.log("-----tb.onHide 回调触发:", res)
  78. // GameDataCenter.plat.instance.reportRole(ReportRoleType.offline)
  79. // this.dealQuery(res)
  80. GameDataCenter.audio.stopAllEffects()
  81. GameDataCenter.audio.pauseMusic()
  82. });
  83. // my.offHide(hideListener);
  84. //该方法不支持ide
  85. // my.setPreferredFramesPerSecond(30);
  86. my.setKeepScreenOn({
  87. keepScreenOn: true
  88. })
  89. if (my.getUpdateManager) {
  90. const updateManager = my.getUpdateManager()
  91. updateManager.onCheckForUpdate(function (res) {
  92. //请求完新版本信息的回调
  93. console.log(res.hasUpdate)
  94. })
  95. updateManager.onUpdateReady(function () {
  96. my.confirm({
  97. title: '更新提示',
  98. content: '新版本已经准备好,是否重启应用?',
  99. success: function (res) {
  100. if (res.confirm) {
  101. // 新的版本已经下载好,调用 applyUpdate 应用新版本并重启
  102. updateManager.applyUpdate()
  103. }
  104. }
  105. })
  106. })
  107. }
  108. // 初始化并获取sdk实例
  109. if (my.tb.getInteractiveSDK) {
  110. this.sdk = my.tb.getInteractiveSDK(); //调用此函数即可初始化SDK
  111. // 获取运营活动控制器
  112. this.gameActivityController = this.sdk.getGameActivityController({
  113. bizCode: 'xiaoyaoxiannew1',//请申请
  114. });
  115. }
  116. }
  117. showLoginView(): void {
  118. console.log("淘宝小游戏平台静默登录")
  119. EventMng.emit(LoadEvent.LOAD_PROGRESS, 0.25, "login")
  120. my.getSystemInfo({
  121. success: (res) => {
  122. console.log(`systemInfo: ${JSON.stringify(res)}`);
  123. if (res["platform"] == "Android") {
  124. GameDataCenter.plat.instance.deviceOS = PlatFormDevType.android;
  125. } else {
  126. GameDataCenter.plat.instance.deviceOS = PlatFormDevType.ios;
  127. }
  128. }
  129. });
  130. // async function GetOpenId() {
  131. // let result
  132. // try {
  133. // result = await window['cloud'].application.httpRequest({
  134. // //不需要完整域名,只需要接口访问路径即可
  135. // 'path': '/welcome',
  136. // 'method': 'GET',
  137. // 'headers': {},
  138. // 'params': {},
  139. // 'body':{},
  140. // //cloudAppId填写开启本地调试的云应用ID,否则会调到云端
  141. // 'exts': { "cloudAppId": "55088", "timeout": 4000 }
  142. // });
  143. // } catch (error) {
  144. // console.log(error)
  145. // }
  146. // }
  147. my.authorize({
  148. scopes: 'scope.userInfo',
  149. success: (res: any) => {
  150. console.log("淘宝授权:" + JSON.stringify(res))
  151. EventMng.emit(LoadEvent.LOAD_PROGRESS, 0.75, "login")
  152. // GetOpenId().then(res => {
  153. // console.log("openId == ",res)
  154. let code = res.accessToken.accessToken;
  155. console.log("淘宝静默登录成功")
  156. let tagInfo = this.sdk.getChannelTag();
  157. console.log('ChannelTag', tagInfo);
  158. let params: PlayerLoginPram = {
  159. pid: Config.pid,
  160. param: [code]
  161. }
  162. GameController.network.send(PlayerLogin.url, params, (result: SevBack) => {
  163. console.log("后段验证返回")
  164. EventMng.emit(LoadEvent.LOAD_PROGRESS, 1, "login")
  165. if (result.type == 1 && result.platBack) {
  166. this.openId = result.platBack.openid
  167. this.loginParams = [result.platBack.token, JSON.stringify(tagInfo)]
  168. console.log("后端验证成功", this.openId)
  169. // 获取邀请者uuid
  170. let inviter = ""
  171. // if (wx.getEnterOptionsSync) {
  172. // let obj = wx.getEnterOptionsSync()
  173. // if (obj.query && obj.query['inviter']) {
  174. // inviter = obj.query['inviter']
  175. // }
  176. // }
  177. this.login(inviter)
  178. } else {
  179. console.log("PlayerLogin.url 返回数据异常")
  180. if (gameMethod.isEmpty(result.win) || gameMethod.isEmpty(result.win.msgOut)) {
  181. GameDataCenter.plat.showErrDialog(GameErrCode.errGamePlatLogin)
  182. }
  183. }
  184. // 获取用户设置信息
  185. console.log("获取用户设置信息")
  186. my.getSetting({
  187. withSubscriptions: true,
  188. success(res) {
  189. console.log("获取用户设置信息 回调:", res)
  190. if (res.authSetting && res.authSetting["scope.userInfo"]) {
  191. // 已授权
  192. console.log("已授权")
  193. GameDataCenter.plat.instance.hasAuthUserInfo = true
  194. }
  195. }
  196. })
  197. })
  198. // })
  199. },
  200. fail: (res: any) => {
  201. // UIHelp.ShowTips("授权失败,请点击右上角的三个点,开启授权后重新登录")
  202. EventMng.emit(LoadEvent.LOAD_PROGRESS, 0.75, "login")
  203. // GetOpenId().then(res => {
  204. // console.log("openId == ",res)
  205. // let code = res.accessToken.accessToken;
  206. console.log("淘宝静默登录成功")
  207. let tagInfo = this.sdk.getChannelTag();
  208. console.log('ChannelTag', tagInfo);
  209. let params: PlayerLoginPram = {
  210. pid: Config.pid,
  211. param: []
  212. }
  213. GameController.network.send(PlayerLogin.url, params, (result: SevBack) => {
  214. console.log("后段验证返回")
  215. EventMng.emit(LoadEvent.LOAD_PROGRESS, 1, "login")
  216. if (result.type == 1 && result.platBack) {
  217. this.openId = result.platBack.openid
  218. this.loginParams = [result.platBack.token, JSON.stringify(tagInfo)]
  219. console.log("后端验证成功", this.openId)
  220. // 获取邀请者uuid
  221. let inviter = ""
  222. // if (wx.getEnterOptionsSync) {
  223. // let obj = wx.getEnterOptionsSync()
  224. // if (obj.query && obj.query['inviter']) {
  225. // inviter = obj.query['inviter']
  226. // }
  227. // }
  228. this.login(inviter)
  229. } else {
  230. console.log("PlayerLogin.url 返回数据异常")
  231. if (gameMethod.isEmpty(result.win) || gameMethod.isEmpty(result.win.msgOut)) {
  232. GameDataCenter.plat.showErrDialog(GameErrCode.errGamePlatLogin)
  233. }
  234. }
  235. // 获取用户设置信息
  236. console.log("获取用户设置信息")
  237. my.getSetting({
  238. withSubscriptions: true,
  239. success(res) {
  240. console.log("获取用户设置信息 回调:", res)
  241. if (res.authSetting && res.authSetting["scope.userInfo"]) {
  242. // 已授权
  243. console.log("已授权")
  244. GameDataCenter.plat.instance.hasAuthUserInfo = true
  245. }
  246. }
  247. })
  248. })
  249. // })
  250. }
  251. });
  252. }
  253. private dealQuery(res) {
  254. if (res.scene) {
  255. GameDataCenter.plat.queryparams.scene = res.scene
  256. }
  257. let shareInfo = this.sdk.getShareInfo();
  258. if (shareInfo['inviter']) {
  259. GameDataCenter.plat.queryparams.inviter = shareInfo['inviter']
  260. }
  261. if (shareInfo['sharer']) {
  262. GameDataCenter.plat.queryparams.sharer = shareInfo['sharer']
  263. }
  264. EventMng.emit(PlatEvent.ON_SCENE_CHANGED)
  265. }
  266. pay(orderId: string, order10cs: string, param: PayProductParam): void {
  267. my.tb.virtualTrade({
  268. itemId: param.productId,
  269. outOrderId: orderId,
  270. success(res) {
  271. // do something
  272. console.log("====== :", res)
  273. if (Config.paySuccAdokId != null) {
  274. clearInterval(Config.paySuccAdokId)
  275. Config.paySuccAdokId = null
  276. }
  277. Config.paySuccAdokIndex = 0
  278. Config.paySuccAdokId = setInterval(() => {
  279. Config.paySuccAdokIndex++
  280. if (Config.paySuccAdokIndex >= 5) {
  281. clearInterval(Config.paySuccAdokId)
  282. Config.paySuccAdokId = null
  283. }
  284. GameDataCenter.time.sendAdok()
  285. }, 1000)
  286. },
  287. fail(errData) {
  288. // do something
  289. console.log("======支付失败:", errData)
  290. UIHelp.ShowTips("支付失败")
  291. }
  292. })
  293. }
  294. // 打开客服窗口
  295. openService() {
  296. // 打开客服窗口
  297. if (my.tb.openMessage) {
  298. my.tb.openMessage({ sellerNick: "摩西游戏化旗舰店" })
  299. }
  300. }
  301. // showRewardAd(adId: string, kid: string, order11Id: string): void {
  302. // if (gameMethod.isEmpty(adId)) {
  303. // UIHelp.ShowTips("暂无广告配置")
  304. // return
  305. // }
  306. // // 获取任务控制器
  307. // let taskController = this.sdk.getTaskController({
  308. // materialId: '33002', //请找淘宝PD协助申请
  309. // materialCode: '6dZEr8Pk2xOTdGGIeUlUQUb' //请找淘宝PD协助申请
  310. // });
  311. // taskController.getTaskList()
  312. // .then(res => {
  313. // console.log("taskList:"+JSON.stringify(res))
  314. // let taskList = res.main
  315. // //找到对应的任务类型,直接触发
  316. // let targetTask = null;
  317. // for (let key in taskList) {
  318. // if (Object.prototype.hasOwnProperty.call(taskList, key)) {
  319. // let taskInfo = taskList[key];
  320. // if (taskInfo.consumeType == adId) {
  321. // targetTask = taskInfo
  322. // break;
  323. // }
  324. // }
  325. // }
  326. // if (targetTask != null) {
  327. // if (targetTask.count >= targetTask.maxCount) {
  328. // UIHelp.ShowTips("当前任务奖励已达领取上限")
  329. // return
  330. // }
  331. // taskController.executeTask(targetTask.id)
  332. // .then(res => {
  333. // this.AdXiaDanSuc = true;
  334. // console.log("executeTask succ:"+JSON.stringify(res))
  335. // })
  336. // .catch(err => {
  337. // UIHelp.ShowTips("淘宝任务执行异常")
  338. // console.log(err)
  339. // });
  340. // } else {
  341. // UIHelp.ShowTips("找不到对应的广告类型")
  342. // }
  343. // })
  344. // .catch(err => {
  345. // UIHelp.ShowTips("淘宝任务获取列表异常")
  346. // console.log(err)
  347. // });
  348. // }
  349. showRewardAd(adId: string, kid: string, order11Id: string): void {
  350. if (gameMethod.isEmpty(adId)) {
  351. UIHelp.ShowTips(`${kid}暂无广告配置`)
  352. return
  353. }
  354. // 小游戏
  355. if (gameMethod.isEmpty(this.RewardedVideoAd)) {
  356. this.RewardedVideoAd = my.createRewardedAd({ adUnitId: adId });
  357. }
  358. let isLoaded = true;
  359. // 按钮或者自定义事件触发
  360. const invoke = () => {
  361. if (isLoaded) {
  362. this.RewardedVideoAd
  363. .show()
  364. .then(() => {
  365. console.log("广告显示成功");
  366. // 展示成功清除
  367. isLoaded = false
  368. // this.RewardedVideoAd.offLoad(loadCallback)
  369. })
  370. .catch((err) => {
  371. console.log("广告组件出现问题", err);
  372. // 再次重试加载一次
  373. this.RewardedVideoAd
  374. .load()
  375. .then(() => {
  376. console.log("手动加载成功");
  377. invoke()
  378. });
  379. })
  380. } else {
  381. console.log('广告没加载完成');
  382. }
  383. }
  384. invoke();
  385. // const loadCallback = (res) => {
  386. // console.log('loadCallback:', res);
  387. // isLoaded = true;
  388. // invoke();
  389. // }
  390. // 完成广告回回调
  391. const completeCallback = (res) => {
  392. console.log('completeCallback', res);
  393. // this.AdXiaDanSuc = true;
  394. GameDataCenter.adVideo.onTaoBaoXiadanSucc();
  395. // 在合适的时机去释放监听
  396. // RewardedVideoAd.offLoad(loadCallback)
  397. // this.RewardedVideoAd.offComplete(completeCallback)
  398. // this.RewardedVideoAd.offClose(closeCallback)
  399. // this.RewardedVideoAd.offError(errorCallback)
  400. }
  401. // 完成广告或者未完成广告,关闭广告会回调
  402. const closeCallback = (res) => {
  403. console.warn('closeCallbak', res)
  404. }
  405. // 广告接口报错的回调
  406. const errorCallback = (e) => {
  407. console.error('errorCallback', e)
  408. }
  409. // 监听广告的事件
  410. // this.RewardedVideoAd.onLoad(loadCallback)
  411. this.RewardedVideoAd.onClose(closeCallback)
  412. this.RewardedVideoAd.onComplete(completeCallback)
  413. this.RewardedVideoAd.onError(errorCallback)
  414. }
  415. reportRoleData(actionName: string, type: Number = 1) {
  416. if (type == 1) {
  417. try {
  418. this.sdk.reportExposure({ actionName: actionName });
  419. } catch (e) {
  420. console.error(e);
  421. }
  422. } else {
  423. try {
  424. this.sdk.reportClick({ actionName: actionName });
  425. } catch (e) {
  426. console.error(e);
  427. }
  428. }
  429. }
  430. //检测新人组件是否开启
  431. checkGameActivityController(cb: (isOpen: boolean) => {}) {
  432. if (gameMethod.isEmpty(this.gameActivityController)) {
  433. cb(false)
  434. }
  435. this.gameActivityController.getInfo().then((res) => {
  436. console.log("checkGameActivityController res=>", res)
  437. // if (res.showModule) {
  438. // let params: UserSetZjPram = {
  439. // }
  440. // GameController.network.send(UserSetZj.url, params, (result: SevBack) => {
  441. // })
  442. // }
  443. cb(res.showModule)
  444. }).catch((err) => {
  445. console.error("checkGameActivityController err:", err);
  446. });
  447. }
  448. //淘宝新人组件
  449. openGameActivityController() {
  450. if (gameMethod.isEmpty(this.gameActivityController)) {
  451. UIHelp.ShowTips("淘宝新人组件初始化失败")
  452. return
  453. }
  454. // 释放监听
  455. this.gameActivityController.offViewClose(() => {
  456. });
  457. this.gameActivityController.getInfo().then((res) => {
  458. console.log("getInfo=>", res);
  459. if (!gameMethod.isEmpty(this.gameActivityController) && res.showModule) {
  460. this.gameActivityController.openView().then((res) => {
  461. console.log("openView=>", res);
  462. // 增加监听
  463. this.gameActivityController.onViewClose(() => {
  464. });
  465. }).catch((err) => {
  466. console.error("openGameActivityController err:", err);
  467. });
  468. } else {
  469. UIHelp.ShowTips("无法打开新人组件")
  470. }
  471. }).catch((err) => {
  472. console.error(err);
  473. });
  474. }
  475. //淘宝用户关键行为上报
  476. reportUserAction(actionId: number) {
  477. console.log("reportUserAction actionId=>", actionId);
  478. this.sdk.reportScene({
  479. sceneId: 401,
  480. timestamp: Date.now(),
  481. costTime: 2000,
  482. extra: {
  483. raw: actionId
  484. }
  485. });
  486. }
  487. }