企业微信对接轻应用获取用户信息

企业微信对接轻应用获取用户信息

前端代码

下面展示一些 内联代码片

//微信对接获取openid
				const appId = "XXXXXXXX";//微信企业ID
				const code = this.getUrlParam('code');//这是获取请求路径中带code参数得方法
				const local = window.location.href;//获取当前页面的url,就是回调地址
				if(code == null){
					window.location.href = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid='+appId+'&redirect_uri='+ encodeURIComponent(local)+'&response_type=code&scope=snsapi_base&state=STATE#wechat_redirect';
				}else{
					this.getOpenId(code);
				}
//getOpenId方法
getOpenId : function(code){//得到code后访问后台,获得openid
		var self = this;
		$.ajax({
			type: 'GET',
			url: '../../../../books/booksApp.do?method=getOpenId&code='+code,
			dataType:'json',
			success: function(result){
			debugger;
			console.log("openid==============>>"+result.openId);
			console.log("openid==============>>"+result.userInfo);
			//保存用户openid
			self.setUserInfo({
				openid: result.openId
			});
			
			self.setUserInfo(result.userInfo);
			if(sessionStorage.openId != result.openId){
				sessionStorage.openId = result.openId;
				sessionStorage.mobile = result.userInfo.mobile;
			}														
						
			},
			error: function(error){
				alert("数据加载出现错误:" + error);
			}
		});
	}

后端代码

public static String CONSTANT_APPID = "XXXXX";//微信企业ID
	public static String CONSTANT_APPSECRET = "xxxxx";//微信自建应用密钥
	//js异步调用方法
	public void getOpenId(HttpServletRequest request,HttpServletResponse response) throws Exception{
		Map<String,Object> result = new HashMap<String, Object>();
		String code = request.getParameter("code");//获取code后,请求链接获取access_token
		String urlToken = "https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid="+CONSTANT_APPID+"&corpsecret="+CONSTANT_APPSECRET;
		JSONObject jsonToken = doGetJson(urlToken);
		String accssToken = jsonToken.getString("access_token");
		
		String urlUserId = "https://qyapi.weixin.qq.com/cgi-bin/user/getuserinfo?access_token="+accssToken+"&code="+code;
		//2. 向微信发出请求,带上APPSCECRET和code,获取openid和access_toekn
		JSONObject jsonUserId = doGetJson(urlUserId);
		String userId = jsonUserId.getString("UserId");
		String urlUserInfo = "https://qyapi.weixin.qq.com/cgi-bin/user/get?access_token="+accssToken+"&userid="+userId;
		JSONObject jsonUserInfo = doGetJson(urlUserInfo);
		
		if(jsonUserInfo.getString("errcode").equals("0")){//请求成功
			UserInfoVO infoVO = new UserInfoVO();//创建一个VO,将需要的用户信息提取并保存
			infoVO.setLoginToken(accssToken);
			infoVO.setMobile(jsonUserInfo.getString("mobile"));
			infoVO.setName(jsonUserInfo.getString("name"));
			infoVO.setLoginId(jsonUserInfo.getString("userid"));
	        result.put("userInfo", infoVO);
	        result.put("openId", infoVO.getOpenid());
			writeResponseObject(result, response);
		}
	}
private void writeResponseObject(Object obj, HttpServletResponse response) throws Exception {
	    byte[] data = this.objectMapper.writeValueAsBytes(obj);
	    response.setCharacterEncoding("UTF-8");
	    response.setContentType("application/json;charset=UTF-8");
	    response.setContentLength(data.length);
	    response.getOutputStream().write(data);
	    response.getOutputStream().close();
	}
public static JSONObject doGetJson(String url) throws ClientProtocolException, IOException{
		 JSONObject jsonObject = null;
	     DefaultHttpClient client = new DefaultHttpClient();
	     HttpGet httpGet = new HttpGet(url);
	     HttpResponse response = client.execute(httpGet);//发送请求
	     HttpEntity entity = response.getEntity();
	     if(entity !=null) {
	         String result = EntityUtils.toString(entity, "UTF-8");
	         jsonObject = JSONObject.fromObject(result);
	     }
	     httpGet.releaseConnection();//释放连接
	     return jsonObject;
	}

第一次写微信轻应用对接,百度了很久,看了很多代码和官方文档走了挺多弯路,写篇文章记录一下,写到这里还没完,项目要跑起来测试数据,还需要去企业微信设置,如图:
在这里插入图片描述
把这个勾选上,之后下载微信开发者工具,登录后就可以开始跑了
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值