企业微信JS-SDK实现会话聊天功能

vue引入企业微信JS-SDK实现会话聊天功能

这两天在做一个对接企业微信实现会话聊天的功能, 发现企业微信文档这块儿做的不是特别详细,网上搜索也没找到特别完整的流程。 期间也踩了不少的坑, 在此进行分享, 希望大家以后能少走弯路。。

首先我们需要在 index.html 内引入jssdk

index.html

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

这里需要提醒的是,企业微信官方并没有发布官方的npm包, 官方需要使用 script 标签在 index.html 文件内进行引入。 这里有个不小的坑, 使用 npm 安装的 微信 jssdk 在使用会话聊天功能会出现如下报错:

openEnterpriseChat:invalid size of userids and externaluserids

如果你也有类似问题, 建议使用 script 标签方式进行引入。然后在 main.js 内挂载 wx对象。

main.js

const wx = window.wx; // index.html中引入外部js,获取js暴露的wx Vue.$wx = Vue.prototype.$wx = wx;

第二步我们需要进行 config 的配置:

const account_id = this.$store.state.account_id; const data = qs.stringify({ account_id, url: location.href.split("#")[0] //向服务端提供授权url参数,并且不需要#后面的部分 }); axios({ method: "POST", url: "后端服务器API", data }) .then(res => { if (res.data.code == 1) { const d = res.data.data; this.$wx.config({ beta: true, // 必须这么写,否则wx.invoke调用形式的jsapi会有问题 debug: true, // 开启调试模式, appId: d.appid, // 必填,企业号的唯一标识,此处填写企业号corpid timestamp: d.timestamp, // 必填,生成签名的时间戳 nonceStr: d.nonceStr, // 必填,生成签名的随机串 signature: d.signature, // 必填,签名,见附录1 jsApiList: [ "openEnterpriseChat,agentConfig,selectExternalContact" ] // 必填,需要使用的JS接口列表,所有JS接口列表见附录2 }); } }) .catch(error => { console.log(error); }); //通过ready接口处理成功验证 this.$wx.ready(function() { // config信息验证后会执行ready方法,所有接口调用都必须在config接口获得结果之后,config是一个客户端的异步操作,所以如果需要在页面加载时就调用相关接口,则须把相关接口放在ready函数中调用来确保正确执行。对于用户触发时才调用的接口,则可以直接调用,不需要放在ready函数中。 }); this.$wx.error(function(res) { console.log(res); //config信息验证失败会执行error函数,如签名过期导致验证失败,具体错误信息可以打开config的debug模式查看,也可以在返回的res参数中查看,对于SPA可以在这里更新签名。 }); this.$wx.checkJsApi({ jsApiList: ["openEnterpriseChat,"], // 需要检测的JS接口列表,所有JS接口列表见附录2, success: function(res) { console.log(res); // 以键值对的形式返回,可用的api值true,不可用为false // 如:{"checkResult":{"chooseImage":true},"errMsg":"checkJsApi:ok"} } });

接下来就是调用企业微信的 api了

onSession() { const external_userid = this.external_userid; console.log("external_userid", external_userid); if (!external_userid) { this.$toast("非企业微信联系人无法发起聊天!"); return; } this.$wx.openEnterpriseChat({ userIds: "",// 注意:userIds和externalUserIds至少选填一个,且userIds+externalUserIds总数不能超过2000。 externalUserIds: external_userid, //参与会话的企业成员列表,格式为userid1;userid2;...,用分号隔开。 groupName: "", // 必填,会话名称。单聊时该参数传入空字符串""即可。 success: function(res) { console.log("success", res); // 回调 }, fail: function(res) { console.log("fail", res); if (res.errMsg.indexOf("function not exist") > -1) { alert("版本过低请升级"); } } }); },

此处外部联系人可以通过 外部联系人选人接口selectExternalContact 获得(此API需要进行agentconfig配置), 或者通过服务器API的 https://work.weixin.qq.com/api/doc/90000/90135/92113 进行获取。

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/wpywyz.html