Qiwei Development - H5 Application

Due to the development of Qiwei in the near future, the documentation of Qiwei is somewhat concise. I also encountered many problems in the process, and the accessible domain name must be in Qiwei to debug. The problems encountered can only be solved by guessing, and the page break point and alert are required to debug. . Difficult to develop, difficult to debug.....

So write this document. It is a reference for all Qiwei developers. Mainly use JS-SDK to develop H5 applications, which is suitable for the development of functions such as creating multiple external groups and sending messages.

Development environment: vite+ vue3 + ts + less

1. SDK introduction

1. Two sdk files need to be imported, in the index.html file

<script src="//res.wx.qq.com/open/js/jweixin-1.2.0.js "></script>

<script src="https://open.work.weixin.qq.com/wwopen/js/jwxwork-1.0.0.js"></script>

2. Generate signature

Generate the front through token. For security reasons, developers  should not  return the access_token to the frontend. It needs to be saved by the developer in the background. All requests to access the enterprise WeChat API are initiated by the backend and need to cooperate with the backend to generate the JS-SDK using the permission signature algorithm. Generate algorithm refer to official example https://developer.work.weixin.qq.com/document/path/90506

Note on the backend: You need to request the enterprise WeChat interface twice, respectively: get the jsapi_ticket of the enterprise and get the jsapi_ticket of the application.

The returned fields are as follows.

{
"code":200,
"msg":"success",
    data:{
    agentId:''// 企微应用的agentId
    appId: '', // 必填,企业微信的corpID
    timestamp: , // 必填,生成签名的时间戳
    nonceStr: '', // 必填,生成签名的随机串
    signature: '',// 必填,签名,见 附录-JS-SDK使用权限签名算法
    }
}

2. Qiwei JS-SDK initialization

// 企微 JSSDK 初始化
export function qywxJssdkInit(params: any) {
  wx.config({
    beta: false,
    debug: false,
    appId: params.appId,
    timestamp: params.timestamp,
    nonceStr: params.nonceStr,
    signature: params.signature,
    jsApiList: ["onMenuShareAppMessage", "onMenuShareWechat"],
  });
  wx.ready(function (err) {
    console.log("微信sdk基础环境初始化成功");
    wxReady(params);
  });

  wx.error(function (err) {
    console.log("jWeixin.error:", err);
  });
}

// 企微环境初始化成功后再调用,否则权限注入可能失败
// 企微权限注入
function wxReady(config: any) {
  console.log("执行企业微信初始化操作!", config);
  wx.agentConfig({
    corpid: config.appId, // 必填,企业微信的corpid,必须与当前登录的企业一致
    agentid: config.agentId, // 必填,企业微信的应用id (e.g. 1000247)
    timestamp: config.timestamp, // 必填,生成签名的时间戳
    nonceStr: config.nonceStr, // 必填,生成签名的随机串
    signature: config.appSignature, // 必填,签名,见附录-JS-SDK使用权限签名算法
    jsApiList: [ // 所有用到的企微方法,都需要在这里注入权限,否则会无法调用
      // 必填
      "openUserProfile",// 打开用户信息
      "openEnterpriseChat", // 创建会话
      "openExistedChatWithMsg",// 打开会话并发送消息
      "updateEnterpriseChat",// 更新会话信息,修改群成员
      "selectExternalContact",// 选择外部联系人
      "getContext",// 获取群内容
      "getCurExternalChat",// 获取群id
      "sendChatMessage",// 给当前群发送消息
      "shareToExternalContact",// 分享给外部联系人
      "shareToExternalChat",// 分享内容到外部群
    ],
    success: function (res) {
      console.log("企微应用初始化成功,相关应用特殊API需要在这之后触发");
    },
    fail: function (err) {
      if (err.errMsg.indexOf("function not exist") > -1) {
        alert("版本过低请升级");
      } else {
        alert(err + JSON.stringify(err));
      }
    },
  });
}

3. Background configuration - add authorization link

Note: Add authorization, otherwise it will report that it is not a trusted domain name. Domain names used by all interfaces need to be added. when first added. A file needs to be downloaded. Let the backend put the file in the root directory of the domain name.

4. Development of basic functions of Qiwei

Requirement: Meet the function of creating multiple external groups and sending messages at the same time

Note: Qiwei terminal needs to be updated to the latest version, preferably above 4.0.0, otherwise some functions cannot be used. If you want to use the basic functions of Qiwei, you must wait for the settings and permissions of Qiwei to be injected and configured. Therefore, when the page is initialized, a 1000ms timer needs to be added. Otherwise the call may fail.

1. Create a group chat and open a session

  • Create an external group - you must add an external customer in the contact (set a fixed external contact, everyone must add this external contact account: if it is not an external group, just remove it)

       externalUserIds: ' ' // fixed account

  • If you want to open a session, just pass in the chatId group chat Id. Note that you also need to fill in one for contacts and external contacts
  • Group chat sessions can be created multiple times in a loop

Currently: Android cannot directly open the session, it will directly open the contact single chat (compatibility issue), both PC and iPhone can be created directly

/**

* 创建群聊并打开会话

* 注意:userIds和externalUserIds至少选填一个。内部群最多2000人;外部群最多500人;

* 如果有微信联系人,最多40人

* chatId 会话id

* */

export function creatEnterpriseChat(params: any) {

const { groupName, userList } = params;

const userIds = userList.join(";");

return new Promise((resolve) => {

wx.openEnterpriseChat({

userIds, //参与会话的企业成员列表,格式为userid1;userid2;...,用分号隔开。

externalUserIds: "", // 参与会话的外部联系人列表,格式为userId1;userId2;…,用分号隔开。

groupName, // 会话名称。单聊时该参数传入空字符串""即可。

chatId: "", // 若要打开已有会话,需指定此参数。如果是新建会话,chatId必须为空串

success: function (res: any) {

const result = {

...params,

chatId: res.chatId,

beCreated: true,

};

resolve(result);

},

fail: function (res: any) {

alert(JSON.stringify(res) + " creatEnterpriseChatfail ");

const result = { ...params, beCreated: false };

resolve(result);

if (res.errMsg.indexOf("function not exist") > -1) {

alert("版本过低请升级");

}

},

});

});

Refer to Qiwei development documents: https://developer.work.weixin.qq.com/document/path/92525

2. Send group messages (for external group messages, you can only use this openExistedChatWithMsg method)

Note: If you want to send a message, you must wait until the group is created before sending it. Doing so will interrupt the ability to create group chats. Currently, the mobile terminal can only support sending one group message (because it will automatically jump out of the page), and the PC terminal needs to use a timer to send multiple messages.

// 打开已有群聊并发送消息

export function sendMessge(id: any, params: any) {

wx.invoke(

"openExistedChatWithMsg",

{

chatId: id, // 群id

msg: {

msgtype: "link",

link: {

title:‘’, // 必需

desc:'', // 必需

url: ‘’, // 必需

},

},

},

function (res: any) {

console.log(res);

}

);

}

calling method

// 发送消息接口 data: 数据源 len: 创群成功的数量

const onSendMessage = (data: any, len: Number) => {

for (let i = 0; i < len; i++) {

if (isMobile) { // 判断是否是手机端 手机端有些版本可支持这种方式发送多条消息

sendMessge(data[i].chatId, data[i]);

} else { // PC端需要用定时器创建

state.timer = setTimeout(function timer() {

sendMessge(data[i].chatId, data[i]);

}, i * 2000);

}

}

};

Refer to Qiwei development documents: https://developer.work.weixin.qq.com/document/path/94549

3. Open the address book list to obtain the external enterprise micro user ID

export function openUserList() {

wx.invoke(

"selectExternalContact",

{

filterType: 0, //0表示展示全部外部联系人列表,1表示仅展示未曾选择过的外部联系人。默认值为0;除了0与1,其他值非法。在企业微信2.4.22及以后版本支持该参数

},

function (res: any) {

if (res.err_msg == "selectExternalContact:ok") {

const userIds = res.userIds; //返回此次选择的外部联系人userId列表,数组类型

alert(userIds);

} else {

//错误处理

}

}

);

}

Refer to Qiwei development documents: https://developer.work.weixin.qq.com/document/path/91797

4. Get the group id


// 获取群id

export function getCurExternalChat() {

return new Promise((resolve, reject) => {

wx.invoke("getCurExternalChat", {}, function (res) {

if (res.err_msg === "getCurExternalChat:ok") {

resolve(res);

} else {

// 错误处理

reject(res);

}

});

});

}

Refer to Qiwei development documents: https://developer.work.weixin.qq.com/document/path/92095

5. Configure the web page authorization path

It is used to obtain the user code of Qiwei, and the user trust information of Qiwei can be obtained through the code. Because the token and secret key are obtained at the backend. After the front-end builds the authorization link, it returns the code to the back-end, and the back-end obtains user information through the code.

/**

* 获取重定位的 OAuth 路径

* url 需要重定向的页面路径 可传可不传

* @returns {string}

*/

export const generateOAuthUrl = (url?: any) => {

const redirectUri = url || window.location.href;

const searchObj = {

appid: Config.APP_ID,

redirect_uri: encodeURIComponent(redirectUri),

response_type: "code",

scope: "snsapi_base",

agentid: import.meta.env.VITE_APP_AGENT_ID,

state: "A",

};

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`;

};

/**

* 判断当前网页是否需要重定向

*/

export const checkRedirect = async (getUserId: any) => {

const userId = localStorage.getItem("userId");

const unAuth = !userId || userId === "undefined" || userId === "null";

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

// 判断是否需要重定向

if (!codeExist) {

window.location.replace(generateOAuthUrl());

}

// 判断是否需要重新获取 userId

if (unAuth) {

const code = qs.parse(window.location.search.slice(1)).code as string;

const newUserId = await getUserId(code);

localStorage.setItem("userId", newUserId);

}

};

Refer to Qiwei development documents: https://developer.work.weixin.qq.com/document/path/91335

6. Close the current page window (the mobile terminal will automatically jump out of the page, but the PC terminal will not automatically close)

Note: The mobile terminal does not need to close the page, otherwise the callback cannot be executed. The PC side needs to close the window after all operations are completed.

export function onCloseWindow() {

wx.closeWindow();

}

// 页面定义方法

function closeWindow(time: number) {

if (!isMobile) { // 手机端不需要关闭

state.timer = setTimeout(() => {

onCloseWindow();

}, time);

}

}

Refer to Qiwei development documents: https://developer.work.weixin.qq.com/document/path/90491

5. Debugging tools

Windows version debugging

  1. Put  devtools_resources.pak  in the installation directory of Enterprise WeChat ( the copied file name must be devtools_resources.pak ), and note that the installation directory has a version number (4.0.1304.400 is the version number of the browser kernel);

  2. Close the enterprise WeChat and restart it;
  3. Press the shortcut key  ctrl + alt + shift + Dto enter the debugging mode;
  4. Right-click on the page that needs to be debugged, and click "Developer Tools" to enter the debug mode.

Mac version debugging

  1. Press  command + shift + control + D to enter debug mode

  2. Help -> Development and Debugging Options -> Enable webView element inspection

  3. Built-in browser right click -> inspect element

Guess you like

Origin blog.csdn.net/qq_25687271/article/details/124684300
Recommended