const LoginApi = require('./LoginApi'); const ShareAction = require('../utils/ShareAction'); class WeChat { constructor() { this.wxWidth = 0;//微信小程序可用屏幕宽度 this.wxHeight = 0;//微信小程序可用屏幕高度 this.js_code = null; } /** * 检查登录态是否已失效 * 回调函数会回传flag值(true:未失效, false:已失效) * @param {Function} cb 回调方法 */ checkLogin(cb) { CC_WECHATGAME && wx.checkSession({ success() { //session_key 未失效 cb && cb(true) }, fail() { //session_key 已失效 cb && cb(false) } }) } /** * 使用存在localStorage中的登录信息进行静默登录 * 不刷新 uid 和 token * @param {Function} cb 回调方法 */ loginStatic(cb) { let userStorage = cc.sys.localStorage.getItem('GlobalUser') if (userStorage) { Global.user = userStorage; cb && cb() } else { this.login(cb) } } /** * 调起一个新的微信登录 * 刷新 token * @param {Function} cb 回调方法 */ login(cb) { this.cb = cb || function () { } if (!CC_WECHATGAME) { Global.showLoginPage = false; Global.user = { uid: 1, token: 'lucifer_test_token', nick: 'lucifer', avatarUrl: 'http://mpic.tiankong.com/f94/72b/f9472be4691ab43e3f6132bb8b63d00a/640.jpg', gender: 1 } Global.channel = 'LuciferChannel'; Global.os = 1; Global.ver = 1; this.cb(); return; } this.isSupportInfoBtn = window.wx.createUserInfoButton ? true : false; window.wx.login({ success: ({ code }) => { // console.log(code); this.js_code = code; //如果支持用户信息按钮 if (this.isSupportInfoBtn) { window.wx.getSetting({ success: (res) => { // 已经授权,可以直接调用 getUserInfo 获取头像昵称 if (res.authSetting['scope.userInfo']) { this._getUserInfo() } else { this._createBtn(); } } }) } else { this._getUserInfo() } } }) window.wx.getSystemInfo({ success: (res) => { Global.os = res.platform == "android" ? 2 : 1; this.wxWidth = res.windowWidth; this.wxHeight = res.windowHeight; } }); } _getUserInfo() { wx.getUserInfo({ withCredentials: true, success: (res) => { this._login(res); } }) } _login(res) { // let loginApi = new LoginApi(); LoginApi.login(this.js_code, res, this.cb); } /** * 创建一个微信环境下,获取登录信息的原生按钮 */ _createBtn() { let width = 160; let height = 80; let left = (this.wxWidth - width) / 2; let top = (this.wxHeight - height) / 2; let button = window.wx.createUserInfoButton({ type: 'text', text: '点击授权', style: { left: left, top: top, width: width, height: height, backgroundColor: '#B6ABAB', color: '#000000', textAlign: 'center', fontSize: 16, lineHeight: 80, borderRadius: 5 } }) button.onTap((res) => { // console.log('res'); // console.log(res); if (res.errMsg == 'getUserInfo:ok') { button.destroy(); this._login(res); } }) return button; } inviteFriend(action, success, fail) { if (!CC_WECHATGAME) { return; } window.wx.shareAppMessage({ title: '偷偷分享给你一个小程序,福利满满,你懂的', imageUrl: 'http://t2.hddhhn.com/uploads/tu/201806/9999/eae9e74ec8.jpg', query: 'uid=' + Global.user.uid + '&shareType=' + action, success: success && function () {}, fail: fail && function () {} }); } } module.exports = new WeChat();