login-by-weixin-mobile.js 2.3 KB
Newer Older
DCloud_JSON's avatar
DCloud_JSON 已提交
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
const {
  initWeixin
} = require('../../lib/third-party/index')
const {
  getWeixinPlatform,
  getWeixinAccessToken,
  generateWeixinCache,
  saveWeixinUserKey
} = require('../../lib/utils/weixin')
const {
  ERROR
} = require('../../common/error')
const {
  preUnifiedLogin,
  postUnifiedLogin
} = require('../../lib/utils/unified-login')
const {
  LOG_TYPE
} = require('../../common/constants')
const {
  preBind,
  postBind
} = require('../../lib/utils/relate')

/**
 * 微信授权手机号登录
 * @tutorial https://uniapp.dcloud.net.cn/uniCloud/uni-id-pages.html#login-by-weixin-mobile
 * @param {Object} params
 * @param {String} params.phoneCode 微信手机号返回的code
 * @param {String} params.inviteCode 邀请码
 * @returns
 */
module.exports = async function (params = {}) {
  const schema = {
    phoneCode: 'string',
    inviteCode: {
      type: 'string',
      required: false
    }
  }

  this.middleware.validate(params, schema)

  const { phoneCode, inviteCode } = params

  const weixinApi = initWeixin.call(this)
  let mobile

  try {
    const accessToken = await getWeixinAccessToken.call(this)
    const mobileRes = await weixinApi.getPhoneNumber(accessToken, phoneCode)
    mobile = mobileRes.purePhoneNumber
  } catch (error) {
    console.error(error)
    await this.middleware.uniIdLog({
      success: false,
      type: LOG_TYPE.LOGIN
    })
    throw {
      errCode: ERROR.GET_THIRD_PARTY_ACCOUNT_FAILED
    }
  }

  const { type, user } = await preUnifiedLogin.call(this, {
    user: {
      mobile
    }
  })

  let extraData = {
    mobile_confirmed: 1
  }

  if (type === 'login') {
    // 绑定手机号
    if (!user.mobile_confirmed) {
      const bindAccount = {
        mobile
      }
      await preBind.call(this, {
        uid: user._id,
        bindAccount,
        logType: LOG_TYPE.BIND_MOBILE
      })
      await postBind.call(this, {
        uid: user._id,
        bindAccount,
        extraData: {
          mobile_confirmed: 1
        },
        logType: LOG_TYPE.BIND_MOBILE
      })
      extraData = {
        ...extraData,
        ...bindAccount
      }
    }
  }

  return postUnifiedLogin.call(this, {
    user,
    extraData: {
      ...extraData
    },
    isThirdParty: false,
    type,
    inviteCode
  })
}