UsersApi.js 8.54 KB
import api from '~/utils/request/request'
// const { appId } = wx.getAccountInfoSync().miniProgram
import {
  appId
} from '~/utils/constantData'
// console.log(appId, 'appId')
let loginCount = null,
  loginCache = null,
  loginTimer = null
class UsersApi {
  /**调用后台接口获取用户信息 */
  async login() {
    const appEnter = wx.getEnterOptionsSync()
    try {
      if (appEnter.scene === 1154 && appEnter.mode === 'singlePage') throw 'login:fail rejected due to no permission currently'
      if (!loginCount) {
        loginCache = null
        loginCount = Date.now()
        const {
          code
        } = await this.getWxCode(),
          data = await api.post({
              method: 'scrm.api.sso.weapp.jscode.login',
              appId,
              code,
              delSessionId: true
            },
            true
          )
        loginCache = data
        loginCount = null
        return Promise.resolve(data)
      } else {
        return new Promise((resolve) => {
          loginTimer = setInterval(() => {
            if (loginCache) {
              clearInterval(loginTimer)
              loginCount = null
              resolve(loginCache)
            }
          }, 1e3)
        })
      }
    } catch (error) {
      if (loginTimer) clearInterval(loginTimer)
      loginCount = null
      return Promise.reject(error)
    }
  }
  /**调用接口获取登录凭证(code)。通过凭证进而换取用户登录态信息,包括用户在当前小程序的唯一标识(openid)、微信开放平台帐号下的唯一标识(unionid,若当前小程序已绑定到微信开放平台帐号)及本次登录的会话密钥(session_key)等。用户数据的加解密通讯需要依赖会话密钥完成。 */
  getWxCode() {
    return new Promise((resolve, reject) => {
      wx.login({
        success: res => resolve(res),
        fail: err => reject(err)
      })
    })
  }
  /**授权手机号 */
  async authUserPhone(detail, sessionId) {
    if (!sessionId) {
      wx.$api.showToast('缺少sessionId')
      Promise.reject({
        errMsg: '缺少sessionId'
      })
    }
    if (detail.errMsg && detail.errMsg == 'getPhoneNumber:fail user deny') Promise.reject()
    delete detail.errMsg
    if (detail.iv && detail.encryptedData) {
      wx.$api.showLoading()
      detail.sessionId = sessionId
      wx.$storage.rm('userInfo')
      wx.$storage.rm('sessionId')
      return api.post({
          method: 'scrm.api.sso.weapp.auth.phone',
          ...detail
        },
        true
      )
    } else Promise.reject(detail.errMsg)
  }
  /**更新客户手机号  */
  updataCustomerPhone() {
    let customerId = wx.$storage.get('srcm_shopmall_customer_id'),
      merchantId = wx.$storage.get('srcm_shopmall_merchant_id')
    api
      .post({
        method: 'scrm.api.sso.weapp.mark.phone',
        customerId,
        merchantId
      })
      .then(() => {
        wx.$storage.rm('srcm_shopmall_customer_id')
      })
  }
  /**调用后台接口获取用户信息js_code换取sessionId */
  async wxCodeLogin() {
    const appEnter = wx.getEnterOptionsSync()
    try {
      if (appEnter.scene === 1154 && appEnter.mode === 'singlePage') throw 'login:fail rejected due to no permission currently'
      const {
        code
      } = await this.getWxCode()
      return await api.post({
          method: 'scrm.api.sso.wechat.applets.jscode.login',
          appId,
          code
        },
        true
      )
    } catch (error) {
      return Promise.reject(error)
    }
  }

  register(data = {}) {
    return api.post({
        method: 'scrm.api.sso.wechat.account.register',
        ...data,
        platformEntrance: 'STORE_ASSISTANT'
      },
      true
    )
  }
  /**退出登录 */
  logout() {
    return api.post({
        method: 'scrm.api.sso.wechat.applets.logout'
      },
      true
    )
  }
  /**授权手机号登录 */
  async authStorePhone(detail, loginToken) {
    if (!loginToken) {
      wx.$api.showToast('缺少loginToken')
      Promise.reject({
        errMsg: '缺少loginToken'
      })
      return
    }
    if (detail.errMsg && detail.errMsg == 'getPhoneNumber:fail user deny') Promise.reject()
    delete detail.errMsg
    if (detail.iv && detail.encryptedData) {
      detail.loginToken = loginToken
      return api.post({
          method: 'scrm.api.sso.wechat.applets.auth.phone',
          ...detail,
          platformEntrance: 'STORE_ASSISTANT' // 平台标识:生意助手-BUSINESS_ASSISTANT,门店助手-STORE_ASSISTANT
        },
        true
      )
    } else Promise.reject(detail.errMsg)
  }
  /**账号密码登录 */
  accountLogin(data = {}) {
    return api.post({
        method: 'scrm.api.sso.wechat.applets.password.login',
        ...data,
        platformEntrance: 'STORE_ASSISTANT'
      },
      true
    )
  }
  /** 手机号获取短信验证码 */
  getSmsCode(mobile) {
    return api.post({
        method: 'scrm.api.sso.wechat.applets.sms.get.code',
        mobile
      },
      true
    )
  }
  /** 手机号短信验证码登录 */
  phoneSmsLogin(data = {}) {
    return api.post({
        method: 'scrm.api.sso.wechat.applets.sms.login',
        ...data,
        source: 'MINIAPP',
        platformEntrance: 'STORE_ASSISTANT'
      },
      true
    )
  }
  /** 获取登录账号列表 */
  getAccountList(sessionId) {
    return api.post({
        method: 'scrm.api.sso.wechat.applets.listSelectAccount',
        platformEntrance: 'STORE_ASSISTANT',
        sessionId
      },
      true
    )
  }
  /**
   * 选择账号登录(手机绑定多个账号时) */
  selectAccountLogin(data) {
    return api.post({
        method: 'scrm.api.sso.wechat.applets.selectAccountLogin',
        platformEntrance: 'STORE_ASSISTANT',
        ...data
      },
      true
    )
  }
  /**检查sessionId 是否过期 */
  checkSession(data = {}) {
    return api.post({
        method: 'scrm.api.sso.login.status.check',
        ...data
      },
      true
    )
  }
  /**获取微信用户信息 */
  async getWXUserInfo() {
    let wx_user_info = wx.$storage.get('wx_user_info')
    if (!wx_user_info) {
      try {
        const data = await this.getUserProfile()
        wx.$storage.set('wx_user_info', data)
        return data
      } catch (error) {
        return {}
      }
    } else return wx_user_info
  }
  /** 手机号授权解析(单纯解析内容返回前端)
   * 只传loginToken就返回unionId和openid
   * 传加密信息就解析手机号
   */
  async getUserProfile(loginToken, detail = {}) {
    if (detail.errMsg && detail.errMsg == 'getPhoneNumber:fail user deny') Promise.reject()
    delete detail.errMsg
    if (!loginToken) {
      let res = await this.wxCodeLogin()
      loginToken = res.data
    }
    detail.loginToken = loginToken
    return api.post({
      method: 'scrm.api.sso.wechat.applets.phone.grant.analysis',
      ...detail,
      platformEntrance: 'STORE_ASSISTANT'
    })
  }

  /**微信登录检查是否有门店账号 
   * single ? 手机号 : 加密信息
   * 
   */
  checkUserPhone(data, single) {
    const method = single ? 'scrm.api.sso.user.login.account.isStaffPhone' : 'scrm.api.sso.wechat.check.phone.have.store.assistant.account'
    return api.post({
      method,
      ...data,
    }, true)
  }

  /**更新C端用户信息 */
  //
  async updateUserInfo(userInfo) {
    try {
      const {
        openId,
        unionId
      } = await this.getWXUserInfo()
      userInfo.openId = openId
      userInfo.appId = appId
      userInfo.unionId = unionId
      return api.post({
        method: 'scrm.api.wechat.auth.userProfile.updateUserInfo',
        userInfo
      })
    } catch (error) {
      return Promise.reject()
    }
  }

  /**
   * 选择账号登录(手机绑定多个账号时) */
  selectAccountLoginByPassword(data) {
    return api.post({
        method: 'scrm.api.sso.wechat.applets.password.selectAccountLogin',
        platformEntrance: 'STORE_ASSISTANT',
        ...data
      },
      true
    )
  }


  /*
   *C端手机号短信登录
   */
  phoneLogin(data) {
    return api.post({
      method: 'scrm.api.sso.weapp.auth.phone.mini',
      source: 'MINIAPP',
      ...data
    }, true)
  }
   // 解析微信群的opengid
   async getOpengid(data) {
    const {
      code
    } = await this.getWxCode()
    data.code = code
    data.appId = appId
    return api.post({
      method: 'scrm.api.sso.wechat.convert.analysis.opengid',
      ...data
    }, true)
  }

   /**opengid转chatId */
   async openGIdtoChatId(data) {
    data.projectName = 'entmicro'
    return api.post({
      method: 'entmicro.api.customer.base.chat.opengid.to.chantid',
      ...data
    }, true)
  }
}
export default UsersApi