WXSDK.ts 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275
  1. // wxAPI: https://developers.weixin.qq.com/minigame/dev/api/
  2. import { VibrateType, uploadType } from "./SDK";
  3. export class WechatManager {
  4. private static _instance: WechatManager = null;
  5. // 用户信息: 昵称,头像,语言等
  6. private _userInfo: wx.types.UserInfo;
  7. // 头像成功失败回调
  8. private _avatarCallBack: Function = null;
  9. private _Fail: Function = null;
  10. private systemInfo: wx.types.SystemInfo = null;
  11. static get instance() {
  12. if (this._instance) {
  13. return this._instance;
  14. }
  15. this._instance = new WechatManager();
  16. this._instance.init()
  17. return this._instance;
  18. }
  19. private videoAd: RewardedVideoAd = null;
  20. public OpenId: string = '';
  21. init() {
  22. if (cc.sys.platform === cc.sys.WECHAT_GAME) {
  23. this.systemInfo = wx.getSystemInfoSync();
  24. //显示转发按钮
  25. wx.showShareMenu({
  26. withShareTicket: true,
  27. menus: ['shareAppMessage', 'shareTimeline']
  28. });
  29. //视频广告
  30. if (compareVersions(this.systemInfo.SDKVersion, "2.0.4") == 2) {
  31. //self.refreshBannerAd();
  32. this.videoAd = wx.createRewardedVideoAd({
  33. adUnitId: ''
  34. });
  35. this.videoAd.onClose((res) => {
  36. if (!res) return console.error("Error:video ad closed with no res!");
  37. res.isEnded ? () => { cc.log('成功') }
  38. : () => { cc.log('失败') };
  39. });
  40. this.videoAd.onError((errMsg) => {
  41. console.error("errCode:", errMsg);
  42. })
  43. }
  44. }
  45. }
  46. // 获取标记权限
  47. public initAutoSetting(Succeed, Fail, btnNode: cc.Node) {
  48. this._avatarCallBack = Succeed;
  49. this._Fail = Fail;
  50. // 避开ts语法检测
  51. // const wx = window['wx'];
  52. // 获取请求过的权限标记
  53. let object: any = {
  54. // 成功回调
  55. success: (res) => {
  56. // 是否授权用户信息
  57. const autoSetting = res.authSetting;
  58. console.error('已经授权的权限');
  59. console.error(autoSetting);
  60. if (autoSetting["scope.userInfo"]) {
  61. // 已授权
  62. this.getUserInfo();
  63. } else {
  64. // 未授权
  65. this.creatUserInfoButton(btnNode);
  66. }
  67. },
  68. // 失败回调
  69. fail() {
  70. console.log("wx.getSetting获取用户配置失败");
  71. },
  72. // 结束回调(调用成功,失败都会执行)
  73. complete() {
  74. console.log("wx.getSetting获取用户配置结束");
  75. }
  76. }
  77. wx.getSetting(object);
  78. }
  79. // 创建用户授权按钮(仅用于登录页面, 如果用户拒绝授权,则一直显示)
  80. private creatUserInfoButton(btnNode: cc.Node) {
  81. let btnSize = cc.size(btnNode.width + 10, btnNode.height + 10);
  82. let frameSize = cc.view.getFrameSize();
  83. let winSize = cc.director.getWinSize();
  84. //适配不同机型来创建微信授权按钮
  85. let left = (winSize.width * 0.5 + btnNode.x - btnSize.width * 0.5) / winSize.width * frameSize.width;
  86. let top = (winSize.height * 0.5 - btnNode.y - btnSize.height * 0.5) / winSize.height * frameSize.height;
  87. let width = btnSize.width / winSize.width * frameSize.width;
  88. let height = btnSize.height / winSize.height * frameSize.height;
  89. // const wx = window['wx'];
  90. let object: any = {
  91. // 按钮类型: text可设置背景色和文本 image仅能设置背景贴图
  92. type: "text",
  93. // 按钮文本,仅对type为text有效
  94. text: "授----权",
  95. // 按钮样式
  96. style: {
  97. left: left,
  98. top: top,
  99. width: width,
  100. height: height,
  101. backgroundColor: '',
  102. color: "#FFFFFF",
  103. textAlign: 'center',
  104. lineHeight: 40,
  105. fontSize: 20,
  106. borderRadius: 4
  107. },
  108. };
  109. const button = wx.createUserInfoButton(object);
  110. // 监听用户信息按钮点击事件
  111. button.onTap((res) => {
  112. if (res && res.userInfo) {
  113. console.log("用户同意授权");
  114. this._userInfo = res.userInfo;
  115. if (this._avatarCallBack) {
  116. this._avatarCallBack(this._userInfo);
  117. }
  118. // 授权成功后,才销毁按钮
  119. button.destroy();
  120. } else {
  121. if (this._Fail) {
  122. this._Fail();
  123. }
  124. console.log("用户拒绝授权");
  125. button.destroy();
  126. }
  127. });
  128. }
  129. // 获取用户信息,需要获取scope.userInfo的授权,也就是getSettings的接口调用
  130. private getUserInfo() {
  131. // const wx = window['wx'];
  132. let object: any = {
  133. success: (res) => {
  134. console.log("通过 getUserInfo 获取的数据:", res);
  135. if (res) {
  136. this._userInfo = res.userInfo;
  137. if (this._avatarCallBack) {
  138. this._avatarCallBack(this._userInfo);
  139. }
  140. }
  141. },
  142. fail: () => {
  143. console.log("getUserInfo获取信息失败");
  144. },
  145. complete: () => { },
  146. };
  147. wx.getUserInfo(object);
  148. }
  149. public Login(Cb: Function) {
  150. wx.login({
  151. success(res) {
  152. if (res.code) {
  153. console.error('登陆成功-得到的数据');
  154. console.error(res);
  155. Cb?.(res)
  156. // 发起网络请求
  157. } else {
  158. console.log('登录失败!' + res.errMsg)
  159. }
  160. }
  161. })
  162. }
  163. //分享
  164. share() {
  165. if (typeof (wx) == "undefined") return console.error("需要微信环境");
  166. var title = ["要来和我一起玩吗?", "是兄弟就来上班!"];
  167. var Uuurl = [
  168. "https://mmocgame.qpic.cn/wechatgame/IDZiaFvyAB0KnCXhS0wjES2ic9HIHWYqoA6kibQ1R9XPCINOAhYZRha0zHz7XibliaoIm/0",
  169. "https://mmocgame.qpic.cn/wechatgame/zK99jwpnFZJLNrv5icNa8Bg7PzGvVicv9A1L7HvCvxTHyCWFpof4GXXUfsJZBZYyiab/0"];
  170. let randomMMM = function getRandomTitle(titles: string[]): string {
  171. const randomIndex = Math.floor(Math.random() * titles.length);
  172. return titles[randomIndex];
  173. }
  174. return new Promise((resolve, reject) => {
  175. wx.shareAppMessage({
  176. title: randomMMM(title),
  177. imageUrl: randomMMM(Uuurl),
  178. // query: 'inviteID=66666&key2=val2'
  179. query: `inviteID=${WechatManager.instance.OpenId}`
  180. });
  181. resolve(0);
  182. })
  183. }
  184. uploadUserData(_value1, _value2) {
  185. if (typeof (wx) == "undefined") return console.error("需要微信环境");
  186. var KVList = [];
  187. var KVData: any = {};
  188. KVData.key = uploadType.上班次数;
  189. KVData.value = _value1
  190. KVList.push(KVData);
  191. var KVData1: any = {};
  192. KVData1.key = uploadType.职位等级;
  193. KVData1.value = _value1
  194. KVList.push(KVData1);
  195. console.log("uploadData:", JSON.stringify(KVData));
  196. console.log("uploadData:", JSON.stringify(KVData1));
  197. wx.setUserCloudStorage({
  198. KVDataList: KVList,
  199. success: function () {
  200. console.log("upload success!");
  201. }
  202. });
  203. }
  204. //震动
  205. vibrate(t: VibrateType, a: wx.types.Callbacks) {
  206. switch (t) {
  207. case VibrateType.Long:
  208. wx.vibrateLong(a)
  209. break;
  210. case VibrateType.Short:
  211. wx.vibrateShort(a)
  212. break;
  213. default:
  214. break;
  215. }
  216. }
  217. }
  218. //比较版本号1和版本号2的大小
  219. //返回值:0:等于,1:小于,2:大于
  220. export function compareVersions(v1: string, v2: string): number {
  221. if (v1 == v2) return 0;
  222. var grp1 = v1.split('.');
  223. var grp2 = v2.split('.');
  224. for (let i = 0; i < Math.max(grp1.length, grp2.length); i++) {
  225. var num1 = parseInt(grp1[i] || '0');
  226. var num2 = parseInt(grp2[i] || '0');
  227. if (num1 > num2) {
  228. return 2;
  229. } else if (num1 < num2) {
  230. return 1;
  231. }
  232. }
  233. return 0;
  234. }