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

引入JSSDK, 然后注册

注册过程
    通过config接口注入权限验证配置
    通过ready接口处理成功验证
wx.ready(function(){
    // config信息验证后会执行ready方法,
    //所有接口调用都必须在config接口获得结果之后,
    //config是一个客户端的异步操作,所以如果需要在页面加载时就调用相关接口,则须把相关接口放在ready函数中调用来确保正确执行。
    //对于用户触发时才调用的接口,则可以直接调用,不需要放在ready函数中。
});
    通过error接口处理失败验证
wx.error(function(res){});
    继续注册wx.agentConfig

踩坑分析

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

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

正确的实现方法

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

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

在页面调用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"
							})
						}
					});
				}
  }
}
经验分享 程序员 微信小程序 职场和发展