前言:
本篇文章主要介绍 拉取企业微信打卡数据这个功能。
1)了解企业微信相关文档
本文中涉及的一些专业术语可以参考:https://work.weixin.qq.com/api/doc/90000/90135/90665#corpid
拉取企业微信打卡数据在OA数据接口这块, 这块的功能逻辑主要是这样的,
a.企业微信会提供一个接口给你,你需要传入你们公司对应的打卡应用的id 和 打卡应用的秘钥,
b.通过发送post 请求,封装请求的参数,
c.得到企业微信返回的数据,一般情况下数据为json,接下来就可以解析json
打卡的Api文档地址:
https://work.weixin.qq.com/api/doc/90000/90135/90262
2)获取打卡数据
可以看到:要做拉取打卡数据功能,我们首先需要获取AccessToken,获取到AccessToken 后我们需要传入用户id.
A.TestController
@GetMapping(value = "/listPushCardData")
public void listPushCardData() {
//获取本地打卡数据
pushCardService.listPushCardData();
}
B.PushCardServiceImpl
package com.test.service;
/**
* @Author tanghh
* @Date 2020/7/2 11:40
*/
public interface PushCardService {
/**
* 获取打卡数据
*/
void listPushCardData();
}
C.PushCardServiceImpl
package com.test.service.impl;
import com.alibaba.fastjson.JSONObject;
import com.sun.scenario.effect.impl.sw.sse.SSEBlend_SRC_OUTPeer;
import com.test.model.PushCardVo;
import com.test.service.PushCardService;
import com.test.util.DateUtil;
import com.test.util.QiWeiParametersUtil;
import com.test.wechat.SendRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
/**
* @Author tanghh
* @Date 2020/7/2 11:40
*/
@Service
public class PushCardServiceImpl implements PushCardService {
private Logger logger = LoggerFactory.getLogger(PushCardServiceImpl.class);
/**
* 获取打卡数据
*/
/**
* {
* "opencheckindatatype": 3,
* "starttime": 1492617600,
* "endtime": 1492790400,
* "useridlist": ["james","paul"]
* }
*/
@Override
public void listPushCardData() {
try {
//1.获取打卡数据
String accessToken = QiWeiParametersUtil.getPushCardAccessToken();
//2.获取当天的开始时间和结束时间
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
String todayTime = simpleDateFormat.format(new Date());
Map<String, Long> map = DateUtil.getStartTimeAndEndTime(todayTime);
Long startTime = map.get("startTime");
Long endTime = map.get("endTime");
//3.封装请求参数
PushCardVo vo = new PushCardVo();
vo.setOpencheckindatatype(3);
vo.setStarttime(startTime);
vo.setEndtime(endTime);
List userList = new ArrayList();
userList.add("*****");
vo.setUseridlist(userList);
String jsonStr = JSONObject.toJSONString(vo);
//4.发送请求
String url = QiWeiParametersUtil.getPushCardUrl.replace("ACCESS_TOKEN",accessToken);
JSONObject jsonObject = SendRequest.sendPost(url,jsonStr);
List list = (List) jsonObject.get("checkindata");
for (Object o : list) {
Map dataMap = (Map) o;
System.out.println("wifi的名字为:----"+dataMap.get("wifiname"));
System.out.println("用户id:----"+dataMap.get("userid"));
System.out.println("地址详情:----"+dataMap.get("location_detail"));
System.out.println("打卡类型:----"+dataMap.get("checkin_type"));
}
} catch (Exception e) {
logger.error("获取打卡记录数据失败",e);
}
}
}
D.其中涉及的类
QiWeiParametersUtil
package com.test.util;
import com.alibaba.fastjson.JSONObject;
import com.test.wechat.SendRequest;
/**
* 企业微信参数配置类
*
* @Author: tanghh18
* @Date: 2019/8/30 16:21
*/
public class QiWeiParametersUtil {
/**
* 1.获取AccessToken
*/
public static String getAccessTokenUrl = "https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid={corpid}&corpsecret={corpsecret}";
/**
* 发送企业微信AccessToken
*/
public static String sendAccessTokenUrl = "https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token=ACCESS_TOKEN";
/**
* 上传临时文件素材
* @param
* @return
*/
public static String uploadMediaUrl="https://qyapi.weixin.qq.com/cgi-bin/media/upload?access_token=ACCESS_TOKEN&type=TYPE";
/**
* 本地打卡数据
*/
public static String getPushCardUrl = "https://qyapi.weixin.qq.com/cgi-bin/checkin/getcheckindata?access_token=ACCESS_TOKEN";
/**
* 企业ID
*/
public final static String corpId = "企业id";
/**
* 企业应用的id,整型。可在应用的设置页面查看(yes)项目测试(ebo0.2版本)
*/
public final static int agentId = 1000049;
/**
* 应用secret
*/
public static String secret = "yin";
/**
* 打卡应用的agentid
*/
public static String punch_card_agentId = "3010011";
/**
* 打卡应用的secret
*/
public static String punch_card_secret = "在打卡应用中可以看到";
/**
* 获得各种access_token
*
* @return
*/
public static String getAccessToken() {
String url = getAccessTokenUrl.replace("{corpid}", corpId).replace("{corpsecret}", secret);
JSONObject departmentJson = SendRequest.sendGet(url);
return departmentJson.getString("access_token");
}
/**
* 获取打卡应用的Secret
*/
public static String getPushCardAccessToken(){
String url = getAccessTokenUrl.replace("{corpid}", corpId).replace("{corpsecret}", punch_card_secret);
JSONObject pushCardJsonObject = SendRequest.sendGet(url);
return pushCardJsonObject.getString("access_token");
}
}
E.DateUtil
package com.test.util;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
/**
* @Author tanghh
* @Date 2020/7/2 11:30
*/
public class DateUtil {
/**
* 获取一天的开始时间和结束时间
*/
public static Map<String,Long> getStartTimeAndEndTime(String dateTime) throws ParseException {
DateFormat format = new SimpleDateFormat("yyyy-MM-dd");
Map<String,Long> map = new HashMap(3);
Date date2 = format.parse(dateTime);
// 一天的毫秒-1
int dayMis = 1000 * 60 * 60 * 24;
// 返回自 1970 年 1 月 1 日 00:00:00 GMT 以来此 Date 对象表示的毫秒数。
// 当天的毫秒
long curMillisecond = date2.getTime();
// 当天最后一秒
long resultMis = curMillisecond + (dayMis - 1);
// 得到我需要的时间 当天最后一秒
Date endDate = new Date(resultMis);
//将数据保存到Map中
map.put("startTime",date2.getTime()/1000);
map.put("endTime",endDate.getTime()/1000);
return map;
}
}
SendRequest
package com.test.wechat;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.*;
import java.net.URL;
import java.net.URLConnection;
/**
* 用来发送请求的类
*
* @Author: tanghh18
* @Date: 2019/8/30 16:21
*/
public class SendRequest {
/**
* 发送GET请求
*
* @param url
* @return
*/
public static JSONObject sendGet(String url) {
HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
HttpSession session = request.getSession();
JSONObject jsonObject = null;
StringBuffer sb = new StringBuffer();
BufferedReader in = null;
try {
String urlName = url;
URL realUrl = new URL(urlName);
// 打开和URL之间的连接
URLConnection conn = realUrl.openConnection();
// 设置通用的请求属性
conn.setRequestProperty("accept", "*/*");
conn.setRequestProperty("connection", "Keep-Alive");
conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)");
//针对群晖NAS请求,加一个Cookie
if (session.getAttribute("sid") != null) {
conn.addRequestProperty("Cookie", "id=" + session.getAttribute("sid"));
}
conn.setConnectTimeout(10000);
// 建立实际的连接
conn.connect();
// 定义BufferedReader输入流来读取URL的响应
in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
String line;
while ((line = in.readLine()) != null) {
sb.append(line);
}
jsonObject = JSON.parseObject(sb.toString());
} catch (Exception e) {
System.out.println("发送GET请求出现异常!" + e);
} finally {
// 使用finally块来关闭输入流
try {
if (in != null) {
in.close();
}
} catch (IOException ex) {
System.out.println("关闭流异常");
}
}
return jsonObject;
}
/**
* 发送post请求(返回json)
*
* @param url
* @param param
* @return
*/
public static JSONObject sendPost(String url, String param) {
PrintWriter out = null;
BufferedReader in = null;
JSONObject jsonObject = null;
String result = "";
try {
URL realUrl = new URL(url);
// 打开和URL之间的连接
URLConnection conn = realUrl.openConnection();
// 发送POST请求必须设置如下两行
conn.setDoOutput(true);
conn.setDoInput(true);
// conn.addRequestProperty("Cookie", "stay_login=1 smid=DumpWzWQSaLmKlFY1PgAtURdV_u3W3beoei96zsXkdSABwjVCRrnnNBsnH1wGWI0-VIflgvMaZAfli9H2NGtJg id=EtEWf1XZRLIwk1770NZN047804");//设置获取的cookie
// 获取URLConnection对象对应的输出流(设置请求编码为UTF-8)
out = new PrintWriter(new OutputStreamWriter(conn.getOutputStream(), "UTF-8"));
// 发送请求参数
out.print(param);
// flush输出流的缓冲
out.flush();
// 获取请求返回数据(设置返回数据编码为UTF-8)
in = new BufferedReader(
new InputStreamReader(conn.getInputStream(), "UTF-8"));
String line;
while ((line = in.readLine()) != null) {
result += line;
}
jsonObject = JSONObject.parseObject(result);
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (out != null) {
out.close();
}
if (in != null) {
in.close();
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
return jsonObject;
}
}
3) 测试拉取打卡数据
访问:http://localhost:8084/listPushCardData
本篇文章就到这里了 ,感谢阅读。