vite-plugin-ww-auth
TypeScript icon, indicating that this package has built-in type declarations

0.2.11 • Public • Published

特性

引入该插件后

安装

使用npm安装

npm install vite-plugin-ww-auth

使用

在vite.config.ts文件中你可以这样配置

//...
import viteWwAuth from "vite-plugin-ww-auth";
// https://vitejs.dev/config/
export default defineConfig(({ mode }) => {
  // 环境变量
  const env = loadEnv(mode, root, "");
  return {
    // ...
    plugins: [
      viteWwAuth({
        corpid: '', // 必填,企业微信的corpid,必须与当前登录的企业一致
        corpsecret: '', // 必填,密钥
        timestamp: '', // 必填,生成签名的时间戳
        noncestr: '', // 必填,生成签名的随机串
        agentid: '', // 必填,企业微信的应用id (e.g. 1000247)
        url: '',
      })
    ],
  };
});

页面加载时,即可从window.__wwAuthInfo__获取企业微信SDK鉴权所需信息。

const wwAuthInfo = window.__wwAuthInfo__;

// 通过agentConfig注入应用的权限
const setUpAgentConfig = () => {
  const { corpid, agentid, timestamp, noncestr, appsign } = wwAuthInfo;
  return new Promise((resolve, reject) => {
    wx.agentConfig({
      corpid, // 必填,企业微信的corpid,必须与当前登录的企业一致
      agentid, // 必填,企业微信的应用id (e.g. 1000247)
      timestamp, // 必填,生成签名的时间戳
      nonceStr: noncestr, // 必填,生成签名的随机串
      signature: appsign, // 必填,签名,见附录-JS-SDK使用权限签名算法
      jsApiList: [
        "selectExternalContact",
        "getExternalContact",
        "getCurExternalContact",
        "getCurExternalChat",
        "shareToExternalChat",
        "shareToExternalContact",
        "chooseImage",
        "getContext"
      ], //必填,传入需要使用的接口名称
      success: (res) => {
        // 回调
        resolve(res);
      },
      fail: (res) => {
        if (res.errMsg.indexOf("function not exist") > -1) {
          console.error("版本过低请升级");
        }
        reject(res);
      }
    });
  });
};

// 初始化企业微信鉴权
export const initSdk = async () => {
  const { noncestr, timestamp, corpid, corpsign } = wwAuthInfo;

  return new Promise((resolve, reject) => {
    wx.config({
      beta: true, // 必须这么写,否则wx.invoke调用形式的jsapi会有问题
      debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来,若要查看传入的参数,可以在pc端打开,参数信息会通过log打出,仅在pc端时才会打印。
      appId: corpid, // 必填,企业微信的corpID,必须是本企业的corpID,不允许跨企业使用
      timestamp, // 必填,生成签名的时间戳
      nonceStr: noncestr, // 必填,生成签名的随机串
      signature: corpsign, // 必填,签名,见 附录-JS-SDK使用权限签名算法
      jsApiList: ["chooseImage"] // 必填,需要使用的JS接口列表,凡是要调用的接口都需要传进来
    });

    wx.ready(async () => {
      console.log("wx.ready");
      try {
        const agentConfigRes = await setUpAgentConfig();
        resolve(agentConfigRes);
      } catch (err) {
        reject(err);
      }
    });

    wx.error((err) => {
      // config信息验证失败会执行error函数,如签名过期导致验证失败,具体错误信息可以打开config的debug模式查看,也可以在返回的res参数中查看,对于SPA可以在这里更新签名。
      console.log("wx.error: ", err);
      reject(err);
    });
  });
};

Readme

Keywords

Package Sidebar

Install

npm i vite-plugin-ww-auth

Weekly Downloads

0

Version

0.2.11

License

ISC

Unpacked Size

16.4 kB

Total Files

9

Last publish

Collaborators

  • wuwhs