app.js 7.41 KB
import wx from './utils/wx';
import udid from './common/udid';
import event from './common/event';
import {verify} from './common/api';
import config from './common/config';
import commonModel from './models/common';
import Promise from './vendors/es6-promise';
import { MD5 } from './vendors/crypto';
import { wechatAuthLogin, verifySessionKey } from './common/login';
import { stringify } from './vendors/query-stringify';
import './router/index';
import Yas from './common/yas';

let yas;

// app.js
App({
  globalData: {
    userInfo: {},
    unionID: '',
    sessionKey: '',
    thirdSession: '',
    systemInfo: {},
    appShopId: 0,
    appUnionType: 0,
  },
  reportData: {
    awakeReported: false
  },
  onLaunch(options) {
    this.globalData.udid = udid.get(); // 生成 UDID

    verify.gen(); // 此处返回是是 Promise,需要调用接口的业务,最好在 then 里边执行

    let sysInfo = wx.getSystemInfoSync();

    if (!sysInfo.screenHeight) {
      sysInfo.screenHeight = sysInfo.windowHeight;
    }
    if (!sysInfo.screenWidth) {
      sysInfo.screenWidth = sysInfo.windowWidth;
    }
    this.globalData.systemInfo = sysInfo;

    wx.checkSession()
      .then(() => { // 微信登录未过期
        this.getWechatThirdSession();
        this.getUserInfo();
        this.getUnionID();
        this.doLogin();
      })
      .catch(() => { // 微信登录过期
        wx.setStorage({
          key: 'thirdSession',
          data: ''
        });
        wx.setStorage({
          key: 'userInfo',
          data: {}
        });

        wx.setStorage({
          key: 'unionID',
          data: ''
        });
        this.setUserInfo({});
        this.setSessionKey('');

        this.doLogin();
      });

    this.globalData.sid = MD5(`${new Date().getTime()}`).toString();

    wx.getSystemInfo().then(res => {
      this.globalData.systemInfo = res;
    });

    // 获取关联店铺
    this.getUnionShop();

    // 设置渠道来源
    if (options && options.query && options.query.union_type) {
      this.globalData.union_type = options.query.union_type;
    }

    // 设置微信场景
    this.globalData.ch = options.scene;

    yas = new Yas(this);
    yas.report('YB_LAUNCH_APP');
  },
  onShow(options) {
    // 设置微信场景
    this.globalData.ch = options.scene;

    yas.report('YB_ENTER_FOREGROUND');

    if (this.reportData.awakeReported === false) {
      let path = options.path;

      if (Object.keys(options.query).length) {
        path = `${path}?${stringify(options.query)}`;
      }

      yas.report('YB_AWAKE_MP', {PAGE_PATH: path});
      this.reportData.awakeReported = true;
    }
  },
  onHide() {
    yas.report('YB_ENTER_BACKGROUND');
  },
  doLogin() {
    this.getSessionKey();
    event.on('login-type-report', params => {
      yas.report('YB_MY_LOGIN', params);
    });
    setTimeout(() => {
      this.wechatAuthLogin();
    }, 1000);
  },
  getUnionShop() {
    return commonModel.getBindShop({ app_id: config.appid})
      .then(res => {
        if (res.code === 200) {
          if (res.data && res.data.shopId) {
            this.globalData.appShopId = res.data.shopId;
            this.globalData.appUnionType = res.data.unionType;
            this._setSync('app_bind_shop_id', res.data.shopId);
            this._setSync('app_bind_union_type', res.data.unionType);
            event.emit('app_shop_id_update');
          }
        }
      })
      .catch(() => {});
  },
  _getSync(key) {
    try {
      return wx.getStorageSync(key);
    } catch (e) {
      console.log(`wx.getStorageSync get ${key} failed.`);
      return {};
    }
  },
  _setSync(key, value) {
    try {
      wx.setStorageSync(key, value);
    } catch (e) {
      console.log(`wx.setStorageSync set ${key} failed.`);
    }
  },
  getWechatThirdSession() {
    this.globalData.thirdSession = this._getSync('thirdSession');
    return this.globalData.thirdSession;
  },
  setWechatThirdSession(session) {
    this.globalData.thirdSession = session;
    wx.setStorage({
      key: 'thirdSession',
      data: this.globalData.thirdSession
    });
  },
  isLogin() {
    return !!this.globalData.userInfo.uid;
  },
  getUid() {
    return this.globalData.userInfo.uid || '';
  },
  getReportUid() {
    return this.globalData.userInfo.uid || this._getSync('userInfo').uid || '';
  },
  getUserInfo() {
    this.globalData.userInfo = this._getSync('userInfo');
  },
  getUnionID() {
    this.globalData.unionID = this._getSync('unionID');
    return this.globalData.unionID;
  },
  getSessionKey() {
    this.globalData.sessionKey = this._getSync('sessionKey');
  },
  getOpenID() {
    let openid;

    if (this.globalData.openID) {
      return this.globalData.openID;
    }

    openid = wx.getStorageSync('openID');
    this.globalData.openID = openid;
    return openid;
  },
  setOpenID(openID) {
    if (openID) {
      this.globalData.openID = openID;
      wx.setStorage({
        key: 'openID',
        data: openID
      });
    }
  },
  setUnionID(unionID) {
    this.globalData.unionID = unionID;
    wx.setStorage({
      key: 'unionID',
      data: unionID
    });
    event.emit('wx-union-id-update');
  },
  setUserInfo(user) {
    this.globalData.userInfo = user;
    wx.setStorage({
      key: 'userInfo',
      data: this.globalData.userInfo
    });
  },
  setSessionKey(sessionKey) {
    this.globalData.sessionKey = sessionKey;
    this._setSync('sessionKey', sessionKey);
  },
  resumeUserInfo() {
    this.globalData.userInfo = this._getSync('userInfo');
  },
  resumeSessionKey() {
    this.globalData.sessionKey = this._getSync('sessionKey');
  },
  wechatAuthLogin() {
    if (!this.globalData.userInfo.uid || !this.globalData.sessionKey) {
      return wechatAuthLogin()
        .then(res => {
          if (res.code === 10003) { // 微信号已绑定手机号
            this.setUserInfo(res.data);
            this.setSessionKey(res.data.sessionKey);
            event.emit('user-login-success');
            event.emit('login-type-report', {LOGIN_TYPE: 4});
          }

          if (res.code === 10004) { // 微信号未绑定手机号
            // 自动登录未绑定静默处理、不强制绑定
          }
        })
        .catch(() => {});
    }

    verifySessionKey().then(ves => {
      if (ves.code !== 200) { // sessionKey已过期

        // 清理原存储的用户信息
        this.clearUserSession();
        return wechatAuthLogin();
      } else {
        this.resumeUserInfo();
        this.resumeSessionKey();
        event.emit('user-login-success');
        return Promise.resolve({});
      }
    })
      .then(res => {
        if (res.code === 10003) { // 微信号已绑定手机号
          this.setUserInfo(res.data);
          this.setSessionKey(res.data.sessionKey);

          event.emit('user-login-success');
          event.emit('login-type-report', {LOGIN_TYPE: 4});
        }

        if (res.code === 10004) { // 微信号未绑定手机号
          // 自动登录未绑定静默处理、不强制绑定
        }
      })
      .catch(() => {});
  },
  clearUserSession() {
    this.setUserInfo({});
    this.setSessionKey('');
  },
  getMiniappType() {
    return config.mini_app_type;
  },
  getUnionType() {
    return config.unionType;
  },
  getShopId() {
    return this.globalData.appShopId || this._getSync('app_bind_shop_id');
  },
  getAppId() {
    return config.appid;
  },
  getSystemInfo() {
    return this.globalData.systemInfo;
  },
  getPvid() {
    return MD5(`${new Date().getTime()}${udid.get()}`).toString();
  }
});