likes
comments
collection
share

uniapp使用企业微信SDK踩坑指南

作者站长头像
站长
· 阅读数 16

这篇文章,主要是面向工作中在企业微信里引入jssdk的人。其实企业微信jssdk和微信公众号的jssdk是差不多的,但这里面有很多需要注意的地方。特别是在uniapp中使用企业微信SDK,有个很大的坑,因为无法联系企业微信的技术人员,这个问题拖了很久,经过不断的试错,最后才得以解决。

企业微信开发文档

developer.work.weixin.qq.com/document/pa…

引入JSSDK, 然后注册

<!--按照官方文档需要引入这两个SDK-->
<script src="https://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>

正常的话,从这一步开始,成功引入以后在相关的页面根据企业微信的文档来构建相关的接口 调用 config和angetConfig,调用成功后就可以使用企业微信提供的相关API了。在windows电脑上和安卓手机端也确实很快就成功了。

注册过程

  • 通过config接口注入权限验证配置
wx.config({
    beta: true,// 必须这么写,否则wx.invoke调用形式的jsapi会有问题
    debug: true, // 开启调试模式,调用的所有api的返回值会在客户端alert出来,若要查看传入的参数,可以在pc端打开,参数信息会通过log打出,仅在pc端时才会打印。
    appId: '', // 必填,企业微信的corpID
    timestamp: , // 必填,生成签名的时间戳
    nonceStr: '', // 必填,生成签名的随机串
    signature: '',// 必填,签名,见 附录-JS-SDK使用权限签名算法
    jsApiList: [] // 必填,需要使用的JS接口列表,凡是要调用的接口都需要传进来
});
  • 通过ready接口处理成功验证
wx.ready(function(){
    // config信息验证后会执行ready方法,
    //所有接口调用都必须在config接口获得结果之后,
    //config是一个客户端的异步操作,所以如果需要在页面加载时就调用相关接口,则须把相关接口放在ready函数中调用来确保正确执行。
    //对于用户触发时才调用的接口,则可以直接调用,不需要放在ready函数中。
});
  • 通过error接口处理失败验证
wx.error(function(res){});
  • 继续注册wx.agentConfig
wx.agentConfig({
    corpid: '', // 必填,企业微信的corpid,必须与当前登录的企业一致
    agentid: '', // 必填,企业微信的应用id (e.g. 1000247)
    timestamp: , // 必填,生成签名的时间戳
    nonceStr: '', // 必填,生成签名的随机串
    signature: '',// 必填,签名,见附录-JS-SDK使用权限签名算法
    jsApiList: [], //必填,传入需要使用的接口名称
	success: function(res) {
        // 回调
    },
    fail: function(res) {
        if(res.errMsg.indexOf('function not exist') > -1){
            alert('版本过低请升级')
        }
    }
});

以上是根据企业微信提供的文档整理的一些代码片段,在开发过程中,还需要对这些注册进行二次封装,便于不同页面使用。

踩坑分析

就在我在windows电脑上实现了相应的功能觉得万事大吉的时候,后来在测试的时候,发现了一个uniapp和企业微信的一个大坑。由于uniapp在转H5的过程中在内部编译的时候会将全局变量wx给用掉来适应微信公众号(不知道uniapp以后会不会做企业微信的适配而区分wx和jweixin,但现阶段没有)。这样一来企业微信的wx对象就无法使用了。后来查阅文档说可以用jWeixin这个对象来替代(企业微信的sdk返回了两个对象一个wx一个jWeixin)。但是在我们实际的使用的时候会发现jWeixin这个对象在ios或者mac中居然不生效无法获取(这个是什么鬼,这个锅好像应该是企业微信来背把)。这就导致了在企业微信上无法正常运行,一直卡在wx.agentConfig这儿走不下去,通过网络搜索我们会找到很多处理的方法,但是我一一试过之后好像都不行。

  • 方法1,在main.判断设备将wx和jWeixin挂在vue的原型上,经测试不行。
  • 方法2,将wx.agentConfg延时注册,说是苹果设备中是在页面完全加载完成以后才注入的,我将wx.agentConfig延迟1000ms执行依然失败。
  • 方法3,更换SDK,下面为文章链接,但是我尝试过依然不行,更换SDK甚至导致了公众号都不能正常使用,所以放弃。

developers.weixin.qq.com/community/d…

  • 使用npm安装依赖包解决 ,但是该方法依然存在mac设备的适配问题,所以我甚至都不愿意尝试。
npm install jweixin-module --save

还有其他的一些方法,就不一一描述,反正都没有成功,最后在unaipp的论坛看到一篇文章跟我的情况类似,根据他提供的代码片段尝试了一下,最终成功。

uniapp使用企业微信SDK踩坑指南 上图是最后在mac电脑的截图,图中右侧是企业微信侧边栏内嵌的h5网页。

正确的实现方法

首先在第一步引入SDK的时候,必须将wx对象重置

<!--按照官方文档需要引入这两个SDK-->
<script>
		window.wx = null;
		//uniapp默认的wx重置
</script>
<script src="https://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>

在封装的工具函数work.js中,根据设备使用不同的对象,并且将wx.agentConfig在wx.ready中注册,为了保险起见,我依然延迟1000ms注册。

import {getWorkConfig,getWorkAgentConfig} from "@/api/work.js"
export function initWxConfig() {
    return getTicket;
}

const getTicket = new Promise((resolve, reject) => {
	getWorkConfig(location.href).then(res=>{
		if (/(iPhone|iPad|iPod|iOS|macintosh|mac os x)/i.test(navigator.userAgent)) {
			wx.config({
				beta: true,// 必须这么写,否则wx.invoke调用形式的jsapi会有问题
				debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来,若要查看传入的参数,可以在pc端打开,参数信息会通过log打出,仅在pc端时才会打印。
				appId: res.data.appId, // 必填,企业微信的corpID
				timestamp:res.data.timestamp , // 必填,生成签名的时间戳
				nonceStr: res.data.nonceStr, // 必填,生成签名的随机串
				signature: res.data.signature,// 必填,签名,见 附录-JS-SDK使用权限签名算法
				jsApiList: res.data.jsApiList // 必填,需要使用的JS接口列表,凡是要调用的接口都需要传进来
			});
			wx.ready(function() {
				// resolve(wx);
				setTimeout(()=>{
					getWorkAgentConfig(location.href).then(response=>{
						wx.agentConfig({
						    corpid: response.data.corpid, // 必填,企业微信的corpid,必须与当前登录的企业一致
						    agentid: response.data.agentid, // 必填,企业微信的应用id (e.g. 1000247)
						    timestamp: response.data.timestamp, // 必填,生成签名的时间戳
						    nonceStr: response.data.nonceStr, // 必填,生成签名的随机串
						    signature: response.data.signature,// 必填,签名,见附录-JS-SDK使用权限签名算法
						    jsApiList: response.data.jsApiList, //必填,传入需要使用的接口名称
							success: function(data) {
						        resolve(data);
						    },
						    fail: function(err) {
						        if(err.errMsg.indexOf('function not exist') > -1){
									reject('版本过低请升级');
						        }
						    }
						});
					})
				},1000)
			})
		}else{
			// window.wx = window.jWeixin;
			jWeixin.config({
				beta: true,// 必须这么写,否则wx.invoke调用形式的jsapi会有问题
				debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来,若要查看传入的参数,可以在pc端打开,参数信息会通过log打出,仅在pc端时才会打印。
				appId: res.data.appId, // 必填,企业微信的corpID
				timestamp:res.data.timestamp , // 必填,生成签名的时间戳
				nonceStr: res.data.nonceStr, // 必填,生成签名的随机串
				signature: res.data.signature,// 必填,签名,见 附录-JS-SDK使用权限签名算法
				jsApiList: res.data.jsApiList // 必填,需要使用的JS接口列表,凡是要调用的接口都需要传进来
			});
			jWeixin.ready(function() {
				// resolve(wx);
				getWorkAgentConfig(location.href).then(response=>{
					jWeixin.agentConfig({
						corpid: response.data.corpid, // 必填,企业微信的corpid,必须与当前登录的企业一致
						agentid: response.data.agentid, // 必填,企业微信的应用id (e.g. 1000247)
						timestamp: response.data.timestamp, // 必填,生成签名的时间戳
						nonceStr: response.data.nonceStr, // 必填,生成签名的随机串
						signature: response.data.signature,// 必填,签名,见附录-JS-SDK使用权限签名算法
						jsApiList: response.data.jsApiList, //必填,传入需要使用的接口名称
						success: function(data) {
							resolve(data);
						},
						fail: function(err) {
							if(err.errMsg.indexOf('function not exist') > -1){
								reject('版本过低请升级');
							}
						}
					});
				})
			})
		}
		
	}).catch(err=>{
		reject(err);
	})
})

在页面调用initWxConfig方法成功以后,使用具体的api依然判断设备,使用wx和jWeixin。

onLoad() {
		initWxConfig().then((jWeixin) => {
        this.getUserID();
      }).catch((err) => {
        return this.$util.Tips({
          title: err
        });
      });
    }	
},
methods:{
  getUserID(){
    if (/(iPhone|iPad|iPod|iOS|macintosh|mac os x)/i.test(navigator.userAgent)){
					wx.invoke('getContext', {}, (res)=>{
						if(res.err_msg == "getContext:ok" && res.entry == "single_chat_tools"){
							let entry  = res.entry ; 
							//返回进入H5页面的入口类型,
							//目前有normal、contact_profile、single_chat_tools、group_chat_tools、chat_attachment
							wx.invoke('getCurExternalContact', {entry}, (response)=>{
								if(response.err_msg == "getCurExternalContact:ok"){
									//返回当前外部联系人userId
									this.userId = response.userId;
									this.$Cache.set('work_user_id',response.userId)
									this.getInfo();
								}
							});
						}else if(res.err_msg == "getContext:ok" && res.entry == "group_chat_tools"){
							uni.reLaunch({
								url:"/pages/work/groupInfo/index"
							})
						}
					});
				}else{
					jWeixin.invoke('getContext', {}, (res)=>{
						if(res.err_msg == "getContext:ok" && res.entry == "single_chat_tools"){
							let entry  = res.entry ; 
							//返回进入H5页面的入口类型,
							//目前有normal、contact_profile、single_chat_tools、group_chat_tools、chat_attachment
							jWeixin.invoke('getCurExternalContact', {entry}, (response)=>{
								if(response.err_msg == "getCurExternalContact:ok"){
									//返回当前外部联系人userId
									this.userId = response.userId;
									this.$Cache.set('work_user_id',response.userId)
									this.getInfo();
								}
							});
						}else if(res.err_msg == "getContext:ok" && res.entry == "group_chat_tools"){
							uni.reLaunch({
								url:"/pages/work/groupInfo/index"
							})
						}
					});
				}
  }
}

至此uniapp使用企业微信SDK在mac电脑的适配问题就得到了解决,如果有更好的方法或者建议,欢迎一起讨论。