uniapp 企业微信侧边栏开发网页授权 注入企业权限 注入应用权限 获取userid(2)

想知道怎么搭建一个企业微信侧边栏应用的,请移步:
https://blog.csdn.net/u013361179/article/details/131936040?spm=1001.2014.3001.5501

1、网页授权,获取code

代码:

oauthUrl() {
		const that = this
		uni.removeStorageSync('code')
		let REDIRECT_URI = encodeURIComponent(window.location.href)
		let CORPID = webConfig.appId
		let url =
			`https://open.weixin.qq.com/connect/oauth2/authorize?appid=${CORPID}&redirect_uri=${REDIRECT_URI}&response_type=code&scope=snsapi_base&state=STATE#wechat_redirect`
		if (window.location.href.indexOf('code=') != -1) { // 避免一直重复重定向无限获取code
			let code = that.getQueryVariable('code')
			if (code == that.getCode()) { // 微信获取code会重定向,所以从上个页面返回主页后,返回的其实是重定向之后的url,此时url一定带有上次的code,code只能用一次,这时候要重新获取
				let urls = that.ridUrlParam(window.location.href, ['code']) // 从url中祛除code,用没有code的url重新生成code 
				window.location.href = urls
			}
			that.setCode(code)  // 保存code
			that.getConfig() // 注入企业权限
		} else {
			window.location.href = url
		}
	},

里面用到的方法:

// 获取url后参数code

getQueryVariable(variable) {
		var query = window.location.search.substring(1);
		var vars = query.split("&");
		for (var i = 0; i < vars.length; i++) {
			var pair = vars[i].split("=");
			if (pair[0] == variable) {
				return pair[1];
			}
		}
		return (false);
	},

// 删除URL中指定search参数

ridUrlParam(url, params) {
		/**
		 * 删除URL中指定search参数,会将参数值一起删除
		 * @param {string} url 地址字符串
		 * @param {array} aParam 要删除的参数key数组,如['name','age']
		 * @return {string} 返回新URL字符串
		 */
		for (var index = 0; index < params.length; index++) {
			var item = params[index];
			var fromIndex = url.indexOf(item + "="); //必须加=号,避免参数值中包含item字符串
			if (fromIndex !== -1) {
				// 通过url特殊符号,计算出=号后面的的字符数,用于生成replace正则
				var startIndex = url.indexOf("=", fromIndex);
				var endIndex = url.indexOf("&", fromIndex);
				var hashIndex = url.indexOf("#", fromIndex);

				var reg = "";
				if (endIndex !== -1) {
					// 后面还有search参数的情况
					var num = endIndex - startIndex;
					reg = new RegExp(item + "=.{" + num + "}");
					url = url.replace(reg, "");
				} else if (hashIndex !== -1) {
					// 有hash参数的情况
					var num = hashIndex - startIndex - 1;
					reg = new RegExp("&?" + item + "=.{" + num + "}");
					url = url.replace(reg, "");
				} else {
					// search参数在最后或只有一个参数的情况
					reg = new RegExp("&?" + item + "=.+");
					url = url.replace(reg, "");
				}
			}
		}
		var noSearchParam = url.indexOf("=");
		if (noSearchParam === -1) {
			url = url.replace(/\?/, ""); // 如果已经没有参数,删除?号
		}
		return url;
	}

这个时候就会发现,如果你是从企业微信客户端侧边栏配置的自定义应用,点击不同的外部联系人时,获取到的code都是一致的,这时候从企业微信后台管理去配置,就每次获取到不同的code了

在这里插入图片描述

2、注入企业权限、应用权限、获取当前外部联系人userid
html引入js文件

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

然后在manifest.json中配置模板路径
在这里插入图片描述

在这里插入图片描述

这个时候,一般页面中会出现一个无法去掉的“取消”字样,通过查看是多了个<uni-actionsheet__action>组件,这时候在index.html中加了一行代码就解决了

<link rel="stylesheet" href="<%= BASE_URL %>static/index.css" />

完整代码如下:
在这里插入图片描述

注入企业权限(必须先注入企业权限,不然wx(jWeixin)中找不到agentConfig方法,就没法注入应用权限):

如果你使用的是uniapp,那么你会发现你在html引入js文件后,window中会找不到wx对象,这是因为uniapp把wx自用了,但是wx返回了wx和jWeixin两个,这时候直接用jWeixin就行(这个方法仅限PC)。
如果需要兼容安卓和ios的手机端,那就需要进行判断,Android使用jWeixin这个变量,iPhone|iPad|iPod|iOS使用wx这个变量,可以通过一个全局方法进行判断,示例代码:

// global.js
// 当前手机系统
	getEWechatSdk() {
		let eWechatSdk = ''
		
		if (/(Android)/i.test(navigator.userAgent)) {
			eWechatSdk = 'jWeixin'
		} else if (/(iPhone|iPad|iPod|iOS)/i.test(navigator.userAgent)) {
			eWechatSdk = 'wx'
		} else {
			eWechatSdk = 'jWeixin'
		}
		return eWechatSdk
	}
// index.vue
created() {
	this.chatSdk = this.$global.getEWechatSdk()
},
methods: {
	window?.[this.chatSdk].invoke('sendChatMessage', {
	  	msgtype: "text", //消息类型,必填
		enterChat: true, //为true时表示发送完成之后顺便进入会话,仅移动端3.1.10及以上版本支持该字段
		text: {
			content: "你好", //文本内容
		}
	}, function(res) {
		console.log(res, 'res')
	if (res.err_msg == 'sendChatMessage:ok') {
			//发送成功
		}
	})
}

tips:代码中的getWxVerify是我们后台的接口,用来获取签名的,,,,最重要的一点,告知后台开发仔细看文档,获取access_token要用的corpsecret是应用秘钥,不是企业秘钥

在这里插入图片描述
还有,请求你们后端接口是,要把请求的ip添加到企业微信后台管理的白名单中

在这里插入图片描述

// 注入企业权限

getConfig() {
	const that = this
	const path = window.location.href.indexOf("#") !== -1 ? window.location.href.split("#")[0] : window.location.href;
	getWxVerify({
		url: encodeURIComponent(path),
		appId: webConfig.appId
	}).then(res => {
		console.log(res, 'ressss')
		window?.[chatSdk].config({
		    beta: true,// 必须这么写,否则wx.invoke调用形式的jsapi会有问题
		    debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来,若要查看传入的参数,可以在pc端打开,参数信息会通过log打出,仅在pc端时才会打印。
		    appId: res.result.appid, // 必填,企业微信的corpID,必须是本企业的corpID,不允许跨企业使用
		    timestamp: res.result.timestamp, // 必填,生成签名的时间戳
		    nonceStr: res.result.noncestr, // 必填,生成签名的随机串
		    signature: res.result.signature,// 必填,签名,见 附录-JS-SDK使用权限签名算法
		    jsApiList: ['getCurExternalContact'] ,// 必填,需要使用的JS接口列表,凡是要调用的接口都需要传进来
		});
		window?.[chatSdk].ready(function(){
			console.log('注入企业权限成功')
			console.log(window, 'window')
		    // config信息验证后会执行ready方法,所有接口调用都必须在config接口获得结果之后,config是一个客户端的异步操作,所以如果需要在页面加载时就调用相关接口,则须把相关接口放在ready函数中调用来确保正确执行。对于用户触发时才调用的接口,则可以直接调用,不需要放在ready函数中。
			that.getAgentConfig()  // 注入应用权限
		});
	})
},

注入应用权限:

// 注入应用权限

getAgentConfig() {
		const that = this
		const path = window.location.href.indexOf("#") !== -1 ? window.location.href.split("#")[0] : window.location.href;
		getWxVerify({
			url: encodeURIComponent(path),
			appId: webConfig.appId,
			type: 'agent_config'
		}).then(res => {
			console.log(res, 'ressss')
			window?.[chatSdk].agentConfig({
			    corpid: res.result.appid, // 必填,企业微信的corpID,必须是本企业的corpID,不允许跨企业使用
				agentid: 1000066, // 必填,企业微信的应用id (e.g. 1000247)
			    timestamp: res.result.timestamp, // 必填,生成签名的时间戳
			    nonceStr: res.result.noncestr, // 必填,生成签名的随机串
			    signature: res.result.signature,// 必填,签名,见 附录-JS-SDK使用权限签名算法
			    jsApiList: ['getCurExternalContact'] ,// 必填,需要使用的JS接口列表,凡是要调用的接口都需要传进来
				success: function(res) {
					// 回调
					console.log('注入应用权限成功',res)
					that.getCurrentUserId()  // 获取当前联系人的userid
				},
				fail: function(res) {
					console.log('注入应用权限失败',res)
					if (res.errMsg.indexOf('function not exist') > -1) {
						alert('版本过低请升级')
					}
				}
			});
		})
	},

获取当前联系人userid:

getCurrentUserId() {
		const that = this
		window?.[chatSdk].invoke('getCurExternalContact', {
			}, function(res){
				console.log(res, '获取当前外部联系人userIdres')
			if(res.err_msg == "getCurExternalContact:ok"){
				let userId  = res.userId ; //返回当前外部联系人userId
				that.setCurrentUserId(userId)
				console.log(userId, '获取当前外部联系人userId', res)
			}else {
				//错误处理
			}
		});
	},
  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 2
    评论
UniApp是一个跨平台的开发框架,可以同时开发iOS和Android平台的应用程序。而企业微信网页授权是指企业在使用微信办公平台时,通过网页授权的方式获取用户在企业微信中的基本信息。 在UniApp中实现企业微信网页授权,首先需要在企业微信开放平台创建一个应用,并获取到相应的corpId和agentId。然后,在UniApp的代码中,可以使用uni.request方法向企业微信网页授权接口发送请求,需要传递的参数包括corpId、agentId、redirect_uri和state等。其中,redirect_uri表示授权后重定向的回调链接,state可以用于传递额外的参数。 当用户访问需要授权的页面时,可以在页面中使用uni.request方法发起授权请求。企业微信网页授权接口会返回一个重定向链接,UniApp可以通过uni.navigateTo方法将用户重定向到该链接,用户在企业微信授权后会跳回到该链接所指向的页面,并携带授权结果等参数。 在UniApp中接收授权结果的方法比较灵活,可以在重定向的页面中通过uni.getLaunchOptionsSync方法获取授权结果等参数。也可以通过uni.onAppShow方法监听小程序的启动和切前台事件,在事件回调中处理授权结果。 总之,通过UniApp实现企业微信网页授权需要调用企业微信网页授权接口,并在UniApp中处理授权结果等参数。这样可以方便地在UniApp开发企业微信相关的功能。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

爱喝冰可乐

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值