gaoluyang
2 天以前 fe75cffbf3bae6777aa2794fd89fa5dc37f5df8d
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
import { tansParams } from "./ruoyi";
 
/**
 * 获取uuid
 * @returns 生成的uuid字符串
 */
export function generateUUID(): string {
  let uuid = "";
  const chars = "0123456789abcdef";
 
  for (let i = 0; i < 32; i++) {
    if (i === 8 || i === 12 || i === 16 || i === 20) {
      uuid += "-";
    }
    uuid += chars[Math.floor(Math.random() * chars.length)];
  }
 
  return uuid;
}
 
/**
 * 获取code
 * @returns 生成的code字符串
 */
export async function getWxCode(appid?: string, redirect_uri?: string) {
  // #ifdef H5
  if (appid == undefined || redirect_uri == undefined) return ""
  let code = "";
 
  // 截取url中的code方法
  function getUrlCode() {
    let url = location.search;
    console.log(url);
    let theRequest: any = new Object();
    if (url.indexOf("?") != -1) {
      let str = url.substr(1);
      let strs = str.split("&");
      for (let i = 0; i < strs.length; i++) {
        theRequest[strs[i].split("=")[0]] = strs[i].split("=")[1];
      }
    }
    return theRequest as { code: string };
  }
 
  code = getUrlCode().code; // 截取code
  if (code == undefined || code == "" || code == null) {
    // 如果没有code,则去请求
    console.log("h5");
    let href = "https://open.weixin.qq.com/connect/oauth2/authorize?" +
      tansParams({
        appid: appid,
        redirect_uri: redirect_uri,
        response_type: "code",
        scope: "snsapi_userinfo",
        state: "STATE",
      }) +
      "#wechat_redirect";
    console.log(href);
    setTimeout(() => {
      window.location.href = href;
    }, 5000);
  } else {
    return code;
  }
  // #endif
 
  // #ifdef MP-WEIXIN
  // @ts-ignore
  const res = await wx.login();
  return res.code;
  // #endif
}