login.js 11.1 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431
import wx from '../utils/wx';
import event from '../common/event';
import Promise from '../vendors/es6-promise';
import accountModel from '../models/account/index';
import config from '../common/config';

/**
 * 用户未授权-发送验证码
 * @param mobile 手机号
 * @param area 国家码
 * @param degrees 验证码
 */
function sendVerifyCode(area, mobile, degrees) {
  return accountModel.sendSms(area, mobile, degrees);
}

/**
 * 用户已授权-发送验证码`
 * @param mobile 手机号
 * @param area 国家码
 * @param degrees 验证码
 */
function sendVerifyCodeWithUnionId(area, mobile, degrees) {
  return accountModel.sendCodeByMiniApp(area, mobile, getApp().getOpenID(), degrees);
}

/**
 * 是否需要验证码
 */
function isNeedImgCheck() {
  return accountModel.isNeedImgCheck();
}

/**
 * 获取验证码按钮
 * @param area
 * @param mobile
 * @param degrees 验证码
 * @returns {*}
 */
function getVerifyCode(area, mobile, degrees) {
  let app = getApp();

  // disableAutoLogin为用户退出,则直接走手机验证码登录接口
  if (!app.globalData.unionID || app._getSync('disableAutoLogin')) {
    return sendVerifyCode(area, mobile, degrees);
  }

  return sendVerifyCodeWithUnionId(area, mobile, degrees);
}

/**
 * 用户未授权-直接登录
 * @param area 国家码
 * @param mobile 手机号
 * @param verifyCode 验证码
 */
function autoSignin(area, mobile, verifyCode) {
  return accountModel.autoSignIn(mobile, verifyCode, area);
}

/**
 * 用户已授权-校验验证码
 * @param area 国家码
 * @param mobile 手机号
 * @param verifyCode 验证码
 */
function checkVerifyCode(area, mobile, verifyCode) {
  return accountModel.bindMiniapp(getApp().globalData.unionID, mobile, verifyCode, area);
}

/**
 * 验证手机号
 * @param area
 * @param mobile
 * @param verifyCode
 */
function bindMobileAction(area, mobile, verifyCode) {
  let app = getApp();

  // disableAutoLogin为用户退出,则直接走手机验证码登录接口
  if (!app.globalData.unionID || app._getSync('disableAutoLogin')) {
    return autoSignin(area, mobile, verifyCode);
  }

  return checkVerifyCode(area, mobile, verifyCode);
}

/**
 * 判断微信用户是否绑定
 * @param unionID
 * @param nickName
 * @returns {Promise.<TResult>|*}
 */
function wechatUserIsBind(unionID, nickName) {
  let app = getApp();

  return accountModel.wechatUserIsBind(unionID, nickName).then(data => {
    wx.hideLoading();
    if (data.data &&
      data.data.is_bind &&
      data.data.is_bind === 'Y') { // 已经绑定
      let userInfo = {};

      userInfo.is_bind = data.data.is_bind;
      userInfo.mobile = data.data.mobile;
      userInfo.ssouid = data.data.ssouid;
      userInfo.uid = data.data.uid;
      userInfo.sessionKey = data.data.session_key;
      userInfo.wechat = app.globalData.userInfo.wechat || '';
      console.log('wechatUserIsBind=>', userInfo);

      app._removeSync('disableAutoLogin');
      app.setSessionKey(userInfo.sessionKey);
      app.setUserInfo(userInfo);

      // 登录成功回调
      event.emit('yas-login-type-report', {LOGIN_TYPE: 4});

      return Promise.resolve({
        code: 10003,
        data: userInfo,
        message: '微信用户已绑定手机号'
      });
    } else {
      return Promise.resolve({
        code: 10004,
        message: '微信用户未绑定手机号'
      });
    }
  });
}

/**
 * 获取unionID、如果用户拒绝授权则无法获得unionID<废弃>
 * @param srd_session
 * @param showMsg
 * @returns {Promise.<T>}
 */
function getUnionID(srd_session, showMsg) {
  let app = getApp();
  let nickName;

  return wx.getSetting().then(rset => {
    if (rset.authSetting['scope.userInfo']) {
      return wx.getUserInfo().then(res => {
        let userInfo = res.userInfo;

        nickName = userInfo.nickName;
        event.emit('enable-tap-login');
        return accountModel.decodeUserInfo(srd_session, res.encryptedData, res.iv);
      });
    }
    return rset;
  }).then(data => {
    if (data && data.data && data.data.union_id) {
      app.setUnionID(data.data.union_id);
      return wechatUserIsBind(data.data.union_id, nickName);
    }
  }).catch(() => {
    let msg = {
      succeed: false,
      message: '使用微信小程序登录需要微信授权,您已经拒绝了该请求,请删除小程序重新进入。'
    };

    if (showMsg) {
      msg.code = 10001;
    }

    event.emit('enable-tap-login');
    return Promise.reject(msg);
  });
}

/**
 * 微信授权登录
 * @param showMsg
 * @returns {Promise.<T>}
 */
function wechatAuthLogin() {
  let app = getApp();

  return wx.login().then(res => {
    console.log('wechatAuthLogin:', res);
    if (res.code) {
      return accountModel.wechatMiniAppLogin(res.code);
    }
  }).then(data => {
    console.log('wechatAuthLogin.then=>', data);
    if (data.code !== 200) {
      return Promise.reject({
        succeed: false,
        message: data.message
      });
    } else {
      data = data.data;
      app.setOpenID(data.openid);
      app.setWechatThirdSession(data.srd_session);

      if (data.unionid) {
        app.setUnionID(data.unionid);
        event.emit('enable-tap-login');
        return wechatUserIsBind(data.unionid, '');
      } else {
        // 如果没有返回unionID,则把原来的清空
        wx.setStorage({
          key: 'unionID',
          data: ''
        });
      }

      // return getUnionID(data.srd_session, showMsg);
    }
  }).catch(err => {
    event.emit('enable-tap-login');
    return Promise.reject(err);
  });
}

/**
 * [跳转手动登录页面]
 * @return {[type]} [description]
 */
function tapGoLogin() {
  return wx.navigateTo({
    url: '/pages/account/bindMobile',
  });
}

/**
 * 验证sessionKey是否过期
 * @returns {*}
 */
function verifySessionKey() {
  return accountModel.verify();
}

/**
 * 自动绑定微信小程序
 * @param mobile
 * @param areaCode
 * @constructor
 */
function _bindMiniAppByAuto(mobile, areaCode) {
  return accountModel.bindMiniAppByAuto(getApp().globalData.unionID, mobile, areaCode);
}

/**
 * 解密获取微信用户绑定的手机号
 * @param iv
 * @param encryptedData
 */
function decodePhoneNumber(iv, encryptedData) {
  return accountModel.decodeUserInfo(getApp().globalData.thirdSession, encryptedData, iv);
}

/**
 * 获取微信手机号码
 * @param e
 */
function getPhoneNumber(e) {
  let app = getApp();
  let router = global.router;

  if (e.detail.errMsg === 'getPhoneNumber:ok') {
    let phoneNumber;
    let countryCode;

    wx.showLoading();
    decodePhoneNumber(e.detail.iv, e.detail.encryptedData).then(res => {
      phoneNumber = res.data.phoneNumber;
      countryCode = res.data.countryCode;

      if (res.data.phoneNumber && res.data.countryCode) {
        return _bindMiniAppByAuto(res.data.phoneNumber, res.data.countryCode);
      }
      return {};
    }).then(res => {
      wx.hideLoading();
      if (res.code === 200) {
        let userInfo = {};

        userInfo.uid = res.data.uid;
        userInfo.is_bind = res.data.is_bind || '';
        userInfo.mobile = res.data.profile;
        userInfo.ssouid = res.data.ssouid;
        userInfo.sessionKey = res.data.session_key;
        userInfo.wechat = app.globalData.userInfo.wechat || '';
        console.log('getPhoneNumber => ', userInfo);

        app._removeSync('disableAutoLogin');
        app.setSessionKey(userInfo.sessionKey);
        app.setUserInfo(userInfo);

        if (e.currentTarget && !e.currentTarget.dataset.notJump) {
          wx.navigateBack(); // 先执行这个,然后在执行event
        }

        event.emit('user-login-success');
        event.emit('yas-user-register-success', {REG_TYPE: 5});// 注册成功调用埋点事件
        wx.showToast({
          icon: 'none',
          title: '手机号授权成功!\r\n为享受更多权益,已为您注册有货会员!',
          duration: 3000
        });
      } else {
        return wx.showModal({
          title: '提示',
          content: res.message || '该手机已是yoho账户,请使用手机号动态登录'
        });
      }
    }).then(res => {
      if (res && res.confirm) {
        router.goUrl(`${config.MINI_APP_DOMAIN}/pages/account/bindMobile?phone=${phoneNumber}&area=${countryCode}`);
      }
    }).catch(() => {
      router.goUrl(`${config.MINI_APP_DOMAIN}/pages/account/bindMobile?phone=${phoneNumber}&area=${countryCode}`);
    });
  } else {
    // wx.navigateTo({
    //   url: '/pages/account/bindMobile'
    // });
  }
}

function getUserInfo(e) {
  let app = getApp();

  if (e.detail.errMsg !== 'getUserInfo:ok') {
    return Promise.reject({
      code: 500,
      message: 'getUserInfo authorize fail'
    });
  } else {
    console.log(e.detail);
    let userInfo = Object.assign(app.globalData.userInfo || {}, { wechat: e.detail.userInfo});

    app.setUserInfo(userInfo);
  }



  wx.showLoading();
  event.emit('enable-tap-login');

  return accountModel.decodeUserInfo(
    app.getWechatThirdSession(),
    e.detail.encryptedData,
    e.detail.iv
  ).then(res => {
    if (res.data && res.data.union_id) {
      app.setUnionID(res.data.union_id);
      return wechatUserIsBind(res.data.union_id, e.detail.userInfo.nickName);
    }
    return res;
  }).then(res => {
    wx.hideLoading();
    if (res.code === 10003) { // 微信号已绑定手机号
      event.emit('user-login-success');
      wx.showToast({
        icon: 'none',
        title: '登录成功!',
        duration: 3000
      });
    } else if (res.code === 10004) { // 微信用户未绑定手机号
      event.emit('change-login-status', {
        text: '绑定手机号',
        tips: '还差一步,绑定手机号码,加入Yoho!Family'
      });
      wx.showToast({
        icon: 'none',
        title: '该微信号未绑定yoho手机账号,请再次单击绑定手机号',
        duration: 3000
      });
    }

    // 登录成功或者失败回调
    event.emit('user-login-callback', res);
    return res;
  }).catch(err => {
    console.log(err, 'err:getUserInfo--');
    wx.hideLoading();
  });
}

/**
 * [获取登录按钮类型]
 * @return {[type]} [description]
 */
function getLoginButtonType() {
  let app = getApp() || {};

  if (app && app.getUid() && app.globalData.userInfo.wechat) {
    return ''; // 已经是登录状态,合法用户
  }

  let isUnionID = app && app.globalData.unionID && app.globalData.userInfo.wechat;// 如果有unionID情况
  let isPhoneNumber = isUnionID ? !(app && app.getUid()) : false; // 如果有unionID且没有uid,可以获取手机号自动绑定登录

  if (app._getSync('disableAutoLogin')) { // 手动退出,走手机号登录页面
    return 'tapGoLogin';
  } else if (!isUnionID) {
    event.emit('change-login-status', {
      text: '微信登录',
      tips: ''
    });
    return 'getUserInfo';
  } else if (isPhoneNumber) {
    event.emit('change-login-status', {
      text: '绑定手机号',
      tips: '还差一步,绑定手机号码,加入Yoho!Family'
    });
    return 'getPhoneNumber';
  }

  return ''; // 已经是登录状态,合法用户
}

module.exports = {
  wechatAuthLogin,
  isNeedImgCheck,
  getVerifyCode,
  bindMobileAction,

  // tapToLogin, // <废弃>
  tapGoLogin,
  verifySessionKey,
  getPhoneNumber,
  getUserInfo,
  getLoginButtonType
};