login.js 20.7 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 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752
//login.js
import {GET, POST} from '../libs/request/request';
import {API_HOST, SERVICE_HOST} from '../libs/config';
import {Encrypt} from '../libs/aes'
import {isStringEmpty} from './util'
import event from '../utils/event';
import {  logEvent,
          YB_MY_LOGIN,
          YB_PAGE_OPEN_L,
          YB_REGISTER_SUCCESS,
        } from '../libs/analytics.js'

//获取应用实例
var app = getApp()
let PV_ID = new Date().getTime() + '';

let listenerList = [];//存放订阅者回调函数


/*****************************************/
/**获取用户UnionID相关逻辑**/
/*****************************************/

/*
  调用wx.login后,用获取到的jscode调用该接口,返回openid/unionid/srdSession。
(注:如果是全新的用户,不会返回unionid,需要申请用户授权后再调用getUnionID函数。
*/
function wechatLoginAction(callbackFunc) {
  var app = getApp()
    wx.login({
    success: function(res) {
      // console.log(res);
      if (res.code) {
        let param = {
          method: 'wechat.smallProgram.onLogin',
          jsCode: res.code,
          miniapp_type: app.globalData.miniapp_type,
        }
        GET(SERVICE_HOST+'/wechat/', param)
        .then(data => {
          if (data.code != 200) {
            callbackFunc({
              succeed: false,
              message: data.message
            });
          } else {
            let responseData = data.data
            //上报接口返回的结果,线上debug用
            checkUnionIDExist(responseData.openid + "", responseData.unionid + "", responseData.srd_session+"", param.method)

            //保存srdSession
            app.setWechatThirdSession(responseData.srd_session);
            //保存openid
            app.setOpenID(responseData.openid);
            //如果unionID不存在(未使用过任何有货微信产品的全新用户),调用getUnionID函数,再次获取unionID
            //对于已经授权过的用户,拿到unionid之后获取一次userinfo更新个人信息.
            let params = { LOGIN_TYPE: 4, PV_ID: PV_ID, };
            // logEvent(YB_MY_LOGIN, params);

            //当unionId为空或者头像为空时,调用微信接口获取用户信息
            if (!isStringEmpty(responseData.unionid)) {
              getUnionID(responseData.srd_session, callbackFunc);
              app.setWXUnionID(data.data.unionid);
              sendWeChatUserDataWithUnionId(data.data.unionid, app.globalData.userInfo.nickName, app.globalData.userInfo.avatarUrl)
              wechatUserIsBind(data.data.unionid, "", "", callbackFunc);
            }
          }
        })
        .catch(error => {
          callbackFunc({
            succeed: false,
            message: error.message
          });
        });

      } else {
        callbackFunc({
          succeed: false,
          message: '获取用户登录态失败!'
        });
      }
    }
  });
}

/*
申请获取用户个人信息授权后,调用接口解码,返回unionID.
*/
function getUnionID(srd_session, callbackFunc) {
  let app = getApp()
  wx.hideToast()
    wx.getUserInfo({
      success: function(res) {
        let userInfo = res.userInfo;
        let nickName = userInfo.nickName;

        //保存用户信息
        app.setUserInfo(res.userInfo)

        let param = {
          method: 'wechat.smallProgram.decodeUserInfo',
          srdSession: srd_session,
          encryptedData: res.encryptedData,
          iv: res.iv,
        }
        GET(API_HOST+'/wechat/', param)
        .then(data => {
          let responseData = data.data
          checkUnionIDExist(responseData.openid + '', responseData.union_id + '', responseData.srd_session+'', param.method)
          if (!isStringEmpty(responseData.union_id)){
            //保存并查询该unionID是否有uid
            app.setWXUnionID(responseData.union_id);
            callbackFunc({
              isHaveUnionID: true,
            });
            sendWeChatUserDataWithUnionId(responseData.union_id, userInfo.nickName, userInfo.avatarUrl)
            wechatUserIsBind(responseData.union_id, nickName, userInfo.avatarUrl,callbackFunc);
          }
        })
        .catch(error => {
          callbackFunc({
            succeed: false,
            message: error.message
          });
        });
      },
      fail:function(res) {
        // console.log("getUserInfoFailed:", res)
        callbackFunc({
          succeed: false,
          message: res.errMsg
        });
      }
    })
}

/*
根据uid上传微信头像昵称.
*/
function sendWeChatUserData(uid,nickName,userAvatarUrl) {
  if (!uid || !nickName || !userAvatarUrl || userAvatarUrl == "images/mine_default_head.png") return
      let param = {
        method: 'app.wechat.addUpdUser',
        uid,
        headIco: userAvatarUrl,
        nickname: nickName,
      }
      GET(API_HOST, param)
        .then(data => {
          // console.log(data)
        })
        .catch(error => {
          // console.log(error)
        });
}

/*
根据unionId上传微信头像昵称.
*/
function sendWeChatUserDataWithUnionId(unionId,nickName,userAvatarUrl) {
  if (!unionId || !nickName || !userAvatarUrl || userAvatarUrl == "images/mine_default_head.png") return
      let param = {
        method: 'app.wechat.addUnionUpdUser',
        unionId,
        headIco: userAvatarUrl,
        nickname: nickName,
      }
      GET(API_HOST, param)
        .then(data => {
          // console.log(data)
        })
        .catch(error => {
          // console.log(error)
        });
}


/*
  判断该微信用户是否已经绑定了有货账号,如果已绑定则返回uid等用户信息
*/
function wechatUserIsBind(unionID, nickName,userAvatarUrl, callbackFunc) {
  let app = getApp()
  let param = {
    method: 'app.passport.signinByOpenID',
    openId: unionID,
    nickname: nickName,
  }
  POST(API_HOST, param)
    .then(data => {
      let responseData = data.data
      // console.log("responseData:", responseData)
      if (!isStringEmpty(responseData.is_bind) && responseData.is_bind === "Y"){ //已经绑定

        let userInfo={};
        userInfo.is_bind = responseData.is_bind;
        userInfo.mobile = responseData.mobile;
        userInfo.ssouid = responseData.ssouid;
        userInfo.uid = responseData.uid;
        app.setUserInfo(userInfo);

        if (!app.globalData.userInfo.avatarUrl){
          getUnionID(responseData.srd_session, callbackFunc);
        }

        app.setSessionkey(responseData.session_key);
        trigger(true)
        sendWeChatUserData(userInfo.uid,nickName,userAvatarUrl);
        callbackFunc({
            succeed: true,
            message: "UID存在"
        });
      }else{
        trigger(false)
        callbackFunc({
          succeed: false,
          message: "UID不存在"
        });
      }

  })
  .catch(error => {
    trigger(false)
    callbackFunc({
      succeed: false,
      message: error.message
    });
  });
}



/*******************************************************************/
/**
 *发送验证码相关逻辑

 根据用户是否授权,分别走两套发送、校验验证码的接口:
 已授权:app.bind.sendThridBindCode、app.passport.bindMiniapp
 未授权:app.message.sendSms、app.passport.autoSignin

**/
/*******************************************************************/

/*
  点击获取验证码按钮

  mobile: 手机号
  vierifycode:验证码
  areaCode:国家码
*/
function getVerifyKey(phoneNumb, areaCode, fromPage,degrees,callbackFunc) {
  let app = getApp()
  if (isStringEmpty(phoneNumb) || isStringEmpty(areaCode)) {
    // console.log("获取验证码失败,手机号码或者区号不能为空")
    return;
  }

  if (isStringEmpty(app.globalData.WXUnion_ID)) {
    sendVerifyCode(phoneNumb, areaCode, fromPage,degrees,callbackFunc);
  }else{
    sendVerifyCodeWithUnionId(phoneNumb, areaCode, fromPage,degrees,callbackFunc);
  }
}

/*
  点击完成按钮

  phoneNumb: 手机号
  vierifycode:验证码
  areaCode:国家码
*/
function bindAction(phoneNumb, verifyCode, areaCode, inviteCode, callbackFunc) {
  let app = getApp()
  if (isStringEmpty(phoneNumb) || isStringEmpty(areaCode)) {
    // console.log("获取验证码失败,手机号码或者区号不能为空")
    return;
  }

  if (isStringEmpty(app.globalData.WXUnion_ID)) {
    autoSignin(phoneNumb, verifyCode,areaCode, inviteCode, callbackFunc);
  } else {
    checkVerifyCode(phoneNumb, verifyCode, areaCode, inviteCode, callbackFunc);
  }
}

/*
  用户已授权-
  1.发送验证码

  phoneNumb:手机号
  areaCode:国家码
*/
function sendVerifyCodeWithUnionId(phoneNumb, areaCode, fromPage,degrees,callbackFunc) {
  let app = getApp()
  let param = {
    method: 'app.bind.sendThirdBindMobileCodeOnlyImg',
    area: areaCode,
    mobile: phoneNumb,
    open_id: app.getOpenID(),
    fromPage,
    degrees,
  }
  // console.log("param:", param)
  GET(API_HOST, param)
  .then(data => {
    if (data.code != 200) {
      callbackFunc({
        succeed: false,
        message: data.message
      });
    } else {
      callbackFunc({
        succeed: true,
        message: '发送成功'
      });
    }
  })
  .catch(error => {
    callbackFunc({
      succeed: false,
      message: error.message
    });
  });
}

/*
  用户已授权-
  2.校验验证码

  mobile:手机号
  vierifycode:验证码
  areaCode:国家码
*/

function checkVerifyCode(phoneNumb, verifyCode, areaCode, inviteCode, callbackFunc){
  var app = getApp()
  let that = this;
  //用户信息信息
  let param = {
    method: 'app.passport.bindMiniapp',
    code: verifyCode,
    mobile: phoneNumb,
    area: areaCode,
    open_id: app.globalData.WXUnion_ID,
    inviteCode,
    wechatHeadIco: app.globalData.userInfo.avatarUrl,
    wechatNickName: app.globalData.userInfo.nickName,
  }
  GET(API_HOST, param)
    .then(data => {
      wx.hideToast()
      if (data.code === 200 && (data.data.uid !== null) && data.data.uid > 0 && data.data.uid !== undefined) {//验证正确
        if(data.data.nFlag === 'Y') {
          event.emit('report-new-user-created');
          event.emit('store-new-user-created', data.data.uid);
        }
        let userInfo = {}
        userInfo.ssouid = data.data.ssouid;
        userInfo.uid = data.data.uid;
        userInfo.profile = data.data.profile;
        userInfo.mobile = phoneNumb;
        app.setSessionkey(data.data.session_key);
        app.setUserInfo(userInfo);
        sendWeChatUserData(userInfo.uid, app.globalData.userInfo.nickName, app.globalData.userInfo.avatarUrl);
        // console.log("登录成功:", userInfo)
        if (data.data.is_register !== undefined && data.data.is_register !== null && data.data.is_register === 0 ) {
          let logParams = {
            YB_REGISTER_SUCCESS: 5,
          };
          // logEvent(YB_REGISTER_SUCCESS, logParams);
          callbackFunc({
            succeed: true,
            message: "登录成功",
            code: 200,
            is_register: true,
          });
        }else{
          callbackFunc({
            succeed: true,
            code: data.code,
            message: data.message,
          });
        }
      } else {//验证错误
        callbackFunc({
          succeed: false,
          message: data.message
        });
      }
    })
    .catch(error => {
      callbackFunc({
        succeed: false,
        message: error.message
      });
    });
}

/*
  用户未授权-
  1.发送验证码

  mobile:手机号
  areaCode:国家码
*/
function sendVerifyCode(phoneNumb, areaCode, fromPage ,degrees ,callbackFunc) {
  let app = getApp()
  let param = {
    method: 'app.message.sendSms',
    area: areaCode,
    mobile: phoneNumb,
    fromPage ,
    degrees,
  }
  // console.log("param:", param)
  GET(API_HOST, param)
    .then(data => {
      if (data.code != 200) {
        callbackFunc({
          succeed: false,
          message: data.message
        });
      } else {
        callbackFunc({
          succeed: true,
          message: '发送成功'
        });
      }
    })
    .catch(error => {
      callbackFunc({
        succeed: false,
        message: error.message
      });
    });
}

/*
  用户未授权-
  2.直接登录

  mobile:手机号
  vierifycode:验证码
  areaCode:国家码
*/
function autoSignin(mobile, verifyCode, areaCode, inviteCode, callbackFunc) {
  let app = getApp()
  //用户信息信息
  let param = {
    method: 'app.passport.autoSignin',
    profile: mobile,
    area: areaCode,
    code: verifyCode,
    inviteCode,
  }

  GET(API_HOST, param)
    .then(data => {
      if (data.code ===200 && data.data&& data.data.uid>0){

        if(data.data.nFlag === 'Y') {
          event.emit('report-new-user-created');
          event.emit('store-new-user-created', data.data.uid);
        }

        let userInfo = {}
        userInfo.ssouid = data.data.ssouid;
        userInfo.uid = data.data.uid;
        userInfo.profile = data.data.profile;
        app.setSessionkey(data.data.session_key);
        app.setUserInfo(userInfo);
        if (data.data.is_register !== undefined && data.data.is_register !== null && data.data.is_register === 0) {
          let logParams = {
            YB_REGISTER_SUCCESS: 5,
          };
          // logEvent(YB_REGISTER_SUCCESS, logParams);
        }
        callbackFunc({
          succeed: true,
          code: data.code,
          message:data.message,
        });
      }else{
        callbackFunc({
          succeed: false,
          code: data.code,
          message: data.message,
        });
      }
    })
    .catch(error => {
      callbackFunc({
        succeed: false,
        message: error.message
      });
    });
}


/*******************************************************************/
/**
 *解密通过微信授权获取到的手机号

 首先调用wechat.smallProgram.decodeUserInfo解码获得手机号
  再调用app.passport.miniAppBindByAuto接口,
  此接口会在后台做判断:
    如果该手机号【已存在】,则提示用户手动验证手机号,
    如果手机号【不存在】,则自动创建账号,并返回uid.
**/
/*******************************************************************/
function decodePhoneNumber(iv, encryptedData, inviteCode, callbackFunc){
  var app= getApp()
  // console.log(app.globalData)
  let param = {
    method: 'wechat.smallProgram.decodeUserInfo',
    srdSession: app.globalData.WXThird_session,
    encryptedData: encryptedData,
    iv: iv,
  }
  GET(SERVICE_HOST + '/wechat/', param)
    .then(data => {
      if(data.data.phoneNumber!==''&&data.data.countryCode!=''){
        BindMiniAppByAuto(data.data.phoneNumber, data.data.countryCode, inviteCode,
callbackFunc)
      }
    })
    .catch(error => {
      callbackFunc({
        succeed: false,
        message: error.message
      });
    });
}

function BindMiniAppByAuto(mobile, countryCode, inviteCode, callbackFunc){
  var app = getApp()
  if (isStringEmpty(mobile)){
    // console.log("手机号不能为空")
    callbackFunc({
      succeed: false,
      message: "手机号为空或格式不正确",
      code: -1,
    });
  }

  let param = {
    method: 'app.passport.miniAppBindByAuto',
    area: countryCode,
    mobile: mobile,
    open_id: app.globalData.WXUnion_ID,
    wechatHeadIco: app.globalData.userInfo.avatarUrl,
    wechatNickName: app.globalData.userInfo.nickName,
    inviteCode,
  }
  GET(API_HOST, param)
    .then(data => {
      if(data.code===200){
        //暂时不需要
        // let userInfo = {};
        // userInfo.mobile = mobile;
        // userInfo.uid = data.data.uid;
        // userInfo.is_bind = data.data.is_bind;
        // userInfo.ssouid = data.data.ssouid;
        // app.setUserInfo(userInfo);
        app.setSessionkey(data.data.session_key)
        app.updateUid(data.data.uid)
        sendWeChatUserData(data.data.uid, app.globalData.userInfo.nickName, app.globalData.userInfo.avatarUrl);

        if(data.data && data.data.nFlag === 'Y') {
          event.emit('report-new-user-created');
          event.emit('store-new-user-created', data.data.uid);
        }

        if (data.data.is_register !== undefined && data.data.is_register !== null && data.data.is_register === 0) {
          let logParams = {
            YB_REGISTER_SUCCESS: 5,
          };
          // logEvent(YB_REGISTER_SUCCESS, logParams);
          callbackFunc({
            succeed: true,
            message: "登录成功",
            code: 200,
            is_register: true,
          });
        }else{
          callbackFunc({
            succeed: true,
            message: "登录成功",
            code: 200,
            is_register: false,
          });
        }
      } else{
          callbackFunc({
            succeed: false,
            message: data.message,
            code: -1
          });
      }
    })
    .catch(error => {
      callbackFunc({
        succeed: false,
        message: error.message
      });
    });

}

//测试接口,将获取到的unionID等参数,上报给服务端以便于调试
function checkUnionIDExist(openID, unionID, srdSession, method) {
  let param = {
    ops: method,
    openId: openID,
    unionId: unionID,
    srdSession: srdSession
  }
  GET(API_HOST + "/wechat/miniapp/collect/", param)
    .then(data => {
      callbackFunc({
        succeed: true,
        message: ''
      });
    })
    .catch(error => {
      callbackFunc({
        succeed: false,
        message: error.message
      });
    });
}

//
function listen(callbackFunc){
  let app = getApp()
  if (!callbackFunc || typeof (callbackFunc) !== 'function') return
  listenerList.push(callbackFunc)
}

function trigger(succeed){
  let that = this
  for (var i = 0, fn; fn = listenerList[i++];) {
    fn.apply(that, arguments);
  }
}

/**
 * button触发getUserInfo之后立即解析获取unionid
 */
function decodeUnionId(srd_session,result,callbackFunc){
  var app = getApp();
  let res = result.detail;
  let userInfo = res.userInfo;
  let nickName = userInfo.nickName;

  //保存用户信息
  app.setUserInfo(res.userInfo)

  let param = {
    method: 'wechat.smallProgram.decodeUserInfo',
    srdSession: srd_session,
    encryptedData: res.encryptedData,
    iv: res.iv,
  }
  GET(API_HOST + '/wechat/', param)
    .then(data => {
      let responseData = data.data
      checkUnionIDExist(responseData.openid + '', responseData.union_id + '', responseData.srd_session + '', param.method)
      if (!isStringEmpty(responseData.union_id)) {
        //保存并查询该unionID是否有uid
        app.setWXUnionID(responseData.union_id);
        callbackFunc({
          isHaveUnionID: true,
        });
        sendWeChatUserDataWithUnionId(responseData.union_id, userInfo.nickName, userInfo.avatarUrl)
        wechatUserIsBind(responseData.union_id, nickName, userInfo.avatarUrl, callbackFunc);
      }
    })
    .catch(error => {
      callbackFunc({
        succeed: false,
        message: error.message
      });
    });
}

/**
 * 手动开启设置页面授权
 */
function openAuthorizeSettings(callbackFunc) {
  let that = this;
  let app = getApp()
  if (wx.getSetting) {
    wx.getSetting({
      success: (res) => {
        // console.log("userInfo:", res.authSetting["scope.userInfo"])
        if (res.authSetting["scope.userInfo"] !== null && res.authSetting["scope.userInfo"] !== undefined && res.authSetting["scope.userInfo"] === false) {
          wx.showModal({
            title: '',
            content: '检测到您未打开微信用户信息授权,开启后即可进行登录',
            confirmText: "去开启",
            confirmColor: "#000000",
            success: function (res) {
              if (res.confirm) {
                wx.openSetting({
                  success: (res) => {
                    // console.log(res.authSetting["scope.userInfo"])
                    if (res.authSetting["scope.userInfo"] !== null && res.authSetting["scope.userInfo"] !== undefined && res.authSetting["scope.userInfo"] === true) {
                      getUnionID(app.getWechatThirdSession(), function (response) {
                        callbackFunc(response);
                      })
                    }
                  },
                  fail: (e) => {
                    wx.navigateTo({
                      url: '../bindPhoneNumber/bindPhoneNumber',
                    });
                  }
                })
              } else {
                wx.navigateTo({
                  url: '../bindPhoneNumber/bindPhoneNumber',
                })
              }
            }
          })
        } else {
          wx.navigateTo({
            url: '../bindPhoneNumber/bindPhoneNumber',
          })
        }
      }
    })
  } else {
    wx.showModal({
      title: '提示',
      content: '当前微信版本过低,无法使用该功能,请升级到最新微信版本后重试。'
    })
  }

}
module.exports = {
  wechatLoginAction,
  getUnionID,
  decodeUnionId,
  getVerifyKey,
  bindAction,
  decodePhoneNumber,
  openAuthorizeSettings,
  listen,
  sendWeChatUserDataWithUnionId,
  sendWeChatUserData
}