如果企业需要在打开的网页里面携带用户的身份信息,第一步需要构造如下的链接来获取code参数:
https://open.weixin.qq.com/connect/oauth2/authorize?appid=CORPID&redirect_uri=REDIRECT_URI&response_type=code&scope=snsapi_base&state=STATE&agentid=AGENTID#wechat_redirect
设置可信域名,新应用首次配置需要下载可信用的txt文件上传到自定义系统服务器上,可信域名配置不支持ip地址
配置菜单调整链接
自定义系统配置
前端根据跳转地址判断是不是企业微信跳转地址,根据code参数获取企业微信人员信息,userId对应企业微信的账号。
后台使用 weixin-java-cp 插件
/**
* 获取企业微信访问用户身份
* @param code
* @param agentId
* @param corpSecret
* @return
*/
public static Map<String, Object> getOauthUser(String code, int agentId, String corpSecret) {
Map<String, Object> result = new HashMap<String, Object>();
WxCpService wxCpService = getWxCpService(Wxperson.getCorpId(),agentId,corpSecret);
try {
WxCpOauth2UserInfo userInfo = wxCpService.getOauth2Service().getUserInfo(code);
wxCpService.getJsapiTicket();
if(null != userInfo) {
result.put("code", "200");
result.put("userId", userInfo.getUserId());
result.put("deviceId", userInfo.getDeviceId());
}
} catch (Exception e) {
e.printStackTrace();
result.put("code", "500");
result.put("message", e.getMessage());
}
return result;
}
<script src="//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>
<script src="https://wwcdn.weixin.qq.com/node/open/js/wecom-jssdk-1.3.1.js">script>
<template>
<div></div>
</template>
<script setup lang="ts">
import { onMounted, ref, watch } from 'vue'
import { wechatConfig, getWechatOauth2Url } from '@/api/login'
import { HSoft } from '@/utils/hsoft'
import { useRouter } from 'vue-router'
import type { RouteLocationNormalizedLoaded } from 'vue-router'
import { ElMessage } from 'element-plus'
const { currentRoute, push } = useRouter()
const redirect = ref<string>('')
const otherQuery = ref({})
let wx = window.wx
const userAgent = window.navigator.userAgent;
watch(
() => currentRoute.value,
(route: RouteLocationNormalizedLoaded) => {
redirect.value = route?.query?.redirect as string
otherQuery.value = getOtherQuery(route?.query)
},
{
immediate: true
}
)
function getOtherQuery(query: any) {
return Object.keys(query).reduce((acc: any, cur: any) => {
if (cur !== 'redirect') {
acc[cur] = query[cur]
}
return acc
}, {})
}
function getWeConfig() {
console.log(window.navigator.userAgent,"HHHHH");
//openDefaultBrowser()
if(userAgent.includes('wxwork')) {
if(userAgent.includes('Windows') || userAgent.includes('Mac')){
let params = {
// 当前网页的URL,不包含#及其后面部分,签名算法的时候会用到
url: window.location.href.split("#")[0],
agentId: HSoft.AGENTID,
corpSecret: HSoft.CORPSECRET
}
wechatConfig(params).then(res => {
console.log(res);
const data = res.data;
wx.config({
beta: true,// 必须这么写,否则wx.invoke调用形式的jsapi会有问题
debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来,若要查看传入的参数,可以在pc端打开,参数信息会通过log打出,仅在pc端时才会打印。
appId: data.appId, // 必填,企业微信的corpID,必须是本企业的corpID,不允许跨企业使用
timestamp: data.timestamp, // 必填,生成签名的时间戳
nonceStr: data.nonceStr, // 必填,生成签名的随机串
signature: data.signature,// 必填,签名,见 附录-JS-SDK使用权限签名算法
jsApiList: ['openDefaultBrowser'] // 必填,需要使用的JS接口列表,凡是要调用的接口都需要传进来
});
wx.ready(function () {
//执行你的业务逻辑代码
//......
//如果要使用到agent_config相关接口 初始化agentConfig配置
openDefaultBrowser()
//getWechatAgentConfig()
});
wx.error(function (res) {
console.log(res);
// config信息验证失败会执行error函数,如签名过期导致验证失败
// ,具体错误信息可以打开config的debug模式查看,也可以在返回的res参数中查看,
// 对于SPA可以在这里更新签名。
});
}).catch(err => {
console.log(err)
})
}else{
let params = {
url: otherQuery.value['url'],
agentId: HSoft.AGENTID,
corpSecret: HSoft.CORPSECRET,
state: 'wechatCP',
}
getWechatOauth2Url(params).then(res => {
console.log(res);
location.href = res.data.url;
})
}
}else{
push(`/login?unauto=true`)
}
}
function openDefaultBrowser(){
let params = {
url: otherQuery.value['url'],
agentId: HSoft.AGENTID,
corpSecret: HSoft.CORPSECRET,
state: 'wechatCP',
}
getWechatOauth2Url(params).then(res => {
console.log(res);
//if((userAgent.includes('Windows') || userAgent.includes('Mac'))){
wx.invoke('openDefaultBrowser', {
// 在默认浏览器打开redirect_uri,并附加code参数;也可以直接指定要打开的url,此时不会附带上code参数。
// 'url': "https://open.weixin.qq.com/connect/oauth2/authorize?appid=******&redirect_uri=http%3A%2F%2Fabc.com%3A6868%2Fwechat%2Fpc&response_type=code&scope=snsapi_userinfo&agentid=**&state=STATE#wechat_redirect"
'url': res.data.url
}, function(res){
console.log('res------------->', res)
if(res.err_msg != "openDefaultBrowser:ok"){
//错误处理
ElMessage.error("企业微信授权登录地址获取异常,请使用账号密码登录")
push(`/login?unauto=true`)
}else{
wx.closeWindow();
window.close();
}
})
// }else{
// location.href = res.data.url;
// }
}).catch(err => {
console.log(err)
})
}
onMounted(() => {
getWeConfig();
})
</script>
后台方法 wechatConfig
public static Map<String, Object> wechatConfig(String url, Integer agentId, String corpSecret) {
Map<String, Object> result = new HashMap<String, Object>();
WxCpService wxCpService = getWxCpService(Wxperson.getCorpId(),agentId,corpSecret);
try {
WxJsapiSignature createJsapiSignature = wxCpService.createJsapiSignature(url);
if(null != createJsapiSignature) {
result.put("code", "200");
result.put("appId",createJsapiSignature.getAppId());
result.put("timestamp",createJsapiSignature.getTimestamp());
result.put("nonceStr",createJsapiSignature.getNonceStr());
result.put("signature",createJsapiSignature.getSignature());
}
} catch (Exception e) {
e.printStackTrace();
result.put("code", "500");
result.put("message", e.getMessage());
}
return result;
}
getWechatOauth2Url
public static Map<String, Object> getWechatOauth2Url(String url, Integer agentId, String corpSecret, String state, String scope) {
Map<String, Object> result = new HashMap<String, Object>();
WxCpService wxCpService = getWxCpService(Wxperson.getCorpId(),agentId,corpSecret);
try {
String buildAuthorizationUrl = wxCpService.getOauth2Service().buildAuthorizationUrl(url, state, scope);
if(HSoft.isNotEmpty(buildAuthorizationUrl)) {
result.put("code", "200");
result.put("url",buildAuthorizationUrl);
}
} catch (Exception e) {
e.printStackTrace();
result.put("code", "500");
result.put("message", e.getMessage());
}
return result;
}
企业微信web登录
<script src="https://wwcdn.weixin.qq.com/node/open/js/wecom-jssdk-1.3.1.js">script>
<!--企业微信扫码登录-->
<template>
<div id="wechatScanLogin" >
</div>
</template>
<script setup lang="ts">
import { onMounted } from 'vue'
import { HSoft } from '@/utils/hsoft'
// 初始化
const wwLogin = () => {
window.ww.createWWLoginPanel({
el: '#wechatScanLogin',
params: {
login_type: 'CorpApp',
appid: HSoft.APPID,
agentid: HSoft.AGENTID,
redirect_uri: 'http://xxx.xxx.com:8088/login',
state: 'loginState',
redirect_type: 'callback',
},
onCheckWeComLogin({ isWeComLogin }) { // 企业微信桌面端是否已登录
console.log(isWeComLogin)
},
onLoginSuccess({ code }) { // 企业微信登录成功回调 Auth Code
console.log({ code })
//调用获取企业微信自动登录接口
},
onLoginFail(err) {
console.log(err)
},
})
}
onMounted( () => {
wwLogin()
})
</script>