checkRedirect.ts 1.76 KB
Newer Older
Aivs's avatar
Aivs committed
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
import Cookies from 'js-cookie'
import qs from 'qs'
import {Config} from "./initSdk"
import {isMock} from "../jsSdk/utils";

type GetUserId = (code: string) => Promise<string>

/**
 * 获取重定位的 OAuth 路径
 * @returns {string}
 */
const generateOAuthUrl = (config: Config) => {
  const [redirectUri] = window.location.href.split('#');

  const searchObj = {
    appid: config.corpId,
    redirect_uri: encodeURIComponent(redirectUri),
    response_type: 'code',
    scope: 'snsapi_base',
    agentid: config.agentId,
    state: 'A1',
  };

  const search = Object.entries(searchObj)
    .map(entry => {
      const [key, value] = entry;
      return `${key}=${value}`;
    })
    .join('&');
  return `https://open.weixin.qq.com/connect/oauth2/authorize?${search}#wechat_redirect`;
};

/**
 * 判断当前网页是否需要重定向
 */
const checkRedirect = async (config: Config, getUserId: GetUserId, mockUserId?: string) => {
Aivs's avatar
Aivs committed
37 38
  // debugger
  
Aivs's avatar
Aivs committed
39
  if (isMock) {
Aivs's avatar
Aivs committed
40 41
    // let code='NWFkfNeQ1EgBc1Ay35wBwoIayUK1NWsCseiFT56VDoo'
    // const newUserIds = await getUserId(code)
Aivs's avatar
Aivs committed
42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61
    // 使用 mock 的 userId
    if (mockUserId) {
      Cookies.set('userId', mockUserId);
    }
    return ;
  }

  const userId = Cookies.get('userId')
  const unAuth = !userId || userId === 'undefined' || userId === 'null'

  const codeExist = window.location.search.includes('code');

  // 判断是否需要重定向
  if (unAuth && !codeExist) {
    window.location.replace(generateOAuthUrl(config));
  }

  // 判断是否需要重新获取 userId
  if (unAuth) {
    const code = qs.parse(window.location.search.slice(1)).code as string
Aivs's avatar
Aivs committed
62 63 64
    const newUserId:any = await getUserId(code)
    Cookies.set('userInfo', newUserId)
    Cookies.set('userId', newUserId.userid)
Aivs's avatar
Aivs committed
65 66 67 68
  }
};

export default checkRedirect