login-service.js 2.41 KB
import BaseService from './base-service.js';
import config from '../../../config.js';
import regeneratorRuntime from '../../libs/regenerator-runtime/index.js';

const WECHAT_SMALLPROGRAM_ONLOGIN = 'wechat.smallProgram.onLogin';
const WECHAT_SMALLPROGRAM_DECODEUSERINFO = 'wechat.smallProgram.decodeUserInfo';
const WECHAT_ADDUNIONUPDUSER = 'app.wechat.addUnionUpdUser';
const WECHAT_PASSPORT_SIGNINBYOPENID = 'app.passport.signinByOpenID';
const WECHAT_PASSPORT_MINIAPPBINDBYAUTO = 'app.passport.miniAppBindByAuto';
const WECHAT_ADDUPDUSER = 'app.wechat.addUpdUser';
const WECHAT_PASSPORT_VERIFY = 'app.passport.verify'
const WechatPath = '/wechat/';

export default class LoginService extends BaseService {
  async checkLogin(code) {
    return await this.GET({
      method: WECHAT_SMALLPROGRAM_ONLOGIN,
      jsCode: code,
      miniapp_type: config.mini_app_type
    }, {
      path: WechatPath
    })
  }

  async decodeUserInfo(srdSession, encryptedData, iv) {
    return await this.GET({
      method: WECHAT_SMALLPROGRAM_DECODEUSERINFO,
      srdSession,
      encryptedData,
      iv
    }, {
        path: WechatPath
    });
  }

  async checkUidAndSessionKey(uid, session_key) {
    let params = {}
    if (uid) {
      params.uid = uid
    }
    if (session_key) {
      params.session_key = session_key;
    }
    return await this.GET({
      method: WECHAT_PASSPORT_VERIFY,
      ...params
    })
  }

  async sendWeChatUserDataWithUnionId(unionId, nickname, avatarUrl) {
    if (!unionId || !nickname || !avatarUrl || avatarUrl === "images/mine_default_head.png") throw new Error('请检查 unionId 或用户信息是否有误');
    return await this.GET({
      method: WECHAT_ADDUNIONUPDUSER,
      unionId,
      headIco: avatarUrl,
      nickname
    });
  }

  async sendWeChatUserData(uid, nickname, avatarUrl) {
    if (!uid || !nickname || !avatarUrl || avatarUrl === "images/mine_default_head.png") throw new Error('请检查 uid 或用户信息是否有误');
    return await this.GET({
      method: WECHAT_ADDUPDUSER,
      uid,
      headIco: avatarUrl,
      nickname
    });
  }

  async wechatUserIsBind(unionId) {
    return await this.GET({
      method: WECHAT_PASSPORT_SIGNINBYOPENID,
      openId: unionId,
    })
  }

  async bindMiniAppByAuto(union_id, mobile, areaCode = 86) {
    return await this.GET({
      method: WECHAT_PASSPORT_MINIAPPBINDBYAUTO,
      open_id: union_id,
      mobile,
      area: areaCode
    })
  }
}