1、操作流程
场景:要在企业微信里面集成企业自建应用,点击应用进入应用功能列表,获取当前企业微信用户信息。
UserId用于在一个企业内唯一标识一个用户,通过网页授权接口可以获取到当前用户的UserId信息,如果需要获取用户的更多信息可以调用
1.1、创建自建应用
1.2、设置可信域名
企业微信授权登录里面填写你的可信域名
1.3、设置工作台应用主页
在打开的网页里面需要携带用户的身份信息,第一步需要构造如下的链接来获取code参数。
http://zxf.xxxx.com/mobile/qyweixin/toBinding.action?
appId=你的appid&appSecret=你的appsecret&redirectUrl=http://zxf.xxxx.com/mobile/qyweixin/binding.action
/**
* 第一步:构造网页授权链接,获取code,下一步根据code参数获得员工的userid
* @param request
* @param map
* @return
*/
@SuppressWarnings("deprecation")
@RequestMapping({ "mobile/qyweixin/toBinding.action" })
public String toBinding(HttpServletRequest request, ModelMap map) {
String url = "https://open.weixin.qq.com/connect/oauth2/authorize
?appid={APPID}&redirect_uri={REDIRECT_URI}&response_type=code
&scope=snsapi_userinfo&state=STATE#wechat_redirect";
String appId = request.getParameter("appId");
String appSecret = request.getParameter("appSecret");
String redirectUrl = request.getParameter("redirectUrl");
redirectUrl = redirectUrl + "?appId=" + appId + "&appSecret="
+ appSecret;
redirectUrl = URLEncoder.encode(redirectUrl);
url = url.replace("{APPID}", appId);
url = url.replace("{REDIRECT_URI}", redirectUrl);
Log4j2Utils.addInfoLog(EnumType.访问, "微信接口", "微信url=" + url, "",
EnumBusinessName.参数管理, GetRemoteIp.getIpAddr(request),
EnumFromType.weixin);
return "redirect:" + url;
}
/**
* 第二步:网页授权后跳转到的地址,改步骤拿到code参数后调用接口获取企业用户userid
* @param request
* @param map
* @return
*/
@RequestMapping({ "mobile/qyweixin/binding.action" })
public String binding(HttpServletRequest request, ModelMap map) {
Map<String,String> getAccessTokenMap = qyWeixinService.getAccessToken(corpid, corpsecret);
String accessToken = "";
if(StringUtils.equals(getAccessTokenMap.get("errcode"), "0")){
accessToken = getAccessTokenMap.get("access_token");
}else{
map.put("msg", "错误信息:"
+getAccessTokenMap.get("errcode")+"错误信息:" + getAccessTokenMap.get("errmsg"));
return "weixin/msg";
}
StringBuffer url = new StringBuffer(
"https://qyapi.weixin.qq.com/cgi-bin/user/getuserinfo");
url.append("?access_token=" + accessToken);
url.append("&code=" + request.getParameter("code"));
JSONObject jsonObject = WeixinUtil.httpRequest(url.toString(), "GET",null);
System.out.println(jsonObject);
if (jsonObject == null) {
map.put("msg", "返回内容为空");
return "weixin/msg";
}
if (jsonObject.getInt("errcode")!=0) {
map.put("msg", "错误信息:" + jsonObject);
return "weixin/msg";
}
if (!jsonObject.has("UserId")) {
map.put("msg", "没有找到UserId:" + jsonObject);
return "weixin/msg";
}
System.out.println("request:"+request.getSession().getId());
map.put("msg", "企业微信获取网页权限成功!"+jsonObject.toString());
return "weixin/msg";
}