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 進行獲取。
至此, 就可以實現會話聊天的功能了。。