如何拉取企業微信打卡數據

前言: 

本篇文章主要介紹 拉取企業微信打卡數據這個功能。

本文涉及到阿里巴巴的JsonObject的解析,可參考我的另一篇blog

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

本篇文章就到這裏了 ,感謝閱讀。

 

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章