# 附录三:接入代码示例

# 请求勤策API接口

# Java代码示例1(引用JAVA开发工具包openapi_tools-1.1.8.jar)

注意:openapi_tools-1.1.8.jar用于请求勤策openapi,要求jdk1.7及以上版本。

项目 名称 大小
JAVA开发工具包 openapi_tools-1.1.8.jar (opens new window) 12.6 KB
接口示例包 demo-openapi.zip (opens new window) 1.18 MB
import com.alibaba.fastjson.JSONObject;
import com.waiqin365.openapi.tools.WQApiHandler;
import com.waiqin365.openapi.vo.WQOpenApi;
import com.waiqin365.openapi.vo.WQRequest;
import com.waiqin365.openapi.vo.WQResponse;

public class TestSample
{
	public static void main(String[] args)
	{
        // 企业所在数据中心服务地址
        String region = "https://openapi.reqion1.qince.com";
        // 企业唯一授权令牌OPENID
        String openid = "8477409196644057335";
        // 企业授权加密秘钥
        String appkey = "hgmK95m5819uZjSPxH";


        WQOpenApi wqOpenApi = new WQOpenApi(openid, appkey);
        wqOpenApi.setOpenurl(String.format("%s/api", region));
        WQRequest request = new WQRequest();
        request.setWqOpenApi(wqOpenApi);
        request.setModule("organization");
        request.setVersion("v1");
        request.setOperation("modifyOrganization");
//
        JSONObject body = new JSONObject();
        body.put("org_id", "1000001");
        body.put("org_name", "南京掌控网络");
        body.put("org_sequence", 1);

        request.setRequestdata(body.toJSONString());
        try
        {
            WQResponse res = WQApiHandler.handleOpenApi(request);
            log.info(request.getRequestUrl());
            log.info("return_code:" + res.getReturn_code());
            log.info("return_message:" + res.getReturn_msg());
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
	}
}

# Java代码示例2

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.security.MessageDigest;
import java.text.SimpleDateFormat;
import java.util.Date;

public class TestWaiqinOpenApi
{
    public static void main(String[] args)
    {
        String openid = "4956175043842151507";
        String appkey = "xr7QNAFIUrW1t22ek8";
        
        Long msgId = java.util.UUID.randomUUID().getLeastSignificantBits() * -1;
        String timestamp = new SimpleDateFormat("yyyyMMddHHmmSS").format(new Date());
        String jsonData = "{\"org_name\":\"南京掌控网络\"}";
        String digest = encodeMd5(jsonData + "|" + appkey + "|" + timestamp);

        String url = "https://openapi.waiqin365.com/api/organization/v1/queryOrganization/" + openid + "/" + timestamp + "/" + digest + "/" + msgId;
        String resp = postJsonString(url, jsonData);
        System.out.println("勤策响应结果:" + resp);
    }

    /**
     * md5摘要
     */
    public static synchronized String encodeMd5(String data)
    {
        MessageDigest digest = null;
        if (digest == null)
        {
            try
            {
                digest = MessageDigest.getInstance("MD5");
                digest.update(data.getBytes("UTF-8"));
                byte[] hash = digest.digest();

                StringBuffer buf = new StringBuffer(hash.length * 2);
                int i;
                for (i = 0; i < hash.length; i++)
                {
                    if ((hash[i] & 0xff) < 0x10)
                    {
                        buf.append("0");
                    }
                    buf.append(Long.toString(hash[i] & 0xff, 16));
                }
                return buf.toString();
            }
            catch (Exception nsae)
            {
                System.err.println("Failed to load the MD5 MessageDigest. ");
            }
        }
        return null;
    }
    /**
     * post请求
     */
    private static String postJsonString(String url, String jsonData)
    {
        String result = "";
        HttpURLConnection httpURLConnection = null;
        BufferedReader reader = null;
        try
        {
            URL httpUrl = new URL(url);
            httpURLConnection = (HttpURLConnection) httpUrl.openConnection();
            httpURLConnection.setRequestMethod("POST");
            httpURLConnection.setConnectTimeout(5000);
            httpURLConnection.setDoOutput(true);
            httpURLConnection.setDoInput(true);
            httpURLConnection.setUseCaches(false);
            httpURLConnection.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
            httpURLConnection.connect();
            OutputStream os = httpURLConnection.getOutputStream();
            os.write(jsonData.getBytes("utf-8"));
            os.flush();
            os.close();
            if(httpURLConnection.getResponseCode() == 200)
            {
                reader = new BufferedReader(new InputStreamReader(httpURLConnection.getInputStream()));
                String data = "";
                StringBuilder builder = new StringBuilder();
                while((data = reader.readLine()) != null)
                {
                    builder.append(data);
                }
                result = builder.toString();
            }
        }
        catch(Exception e)
        {
            System.out.println("发送请求失败:" + e.getMessage());
        }
        finally
        {
            try
            {
                if(reader != null)
                {
                    reader.close();
                }
                if(httpURLConnection != null)
                {
                    httpURLConnection.disconnect();
                }
            }
            catch(Exception e)
            {
                System.out.println("发送请求失败:" + e.getMessage());
            }
        }
        return result;
    }
}

# Python代码示例


#!/usr/bin/python
import urllib3
import json
import hashlib
import uuid
import time
import certifi

openid='4956175043842151507'
appkey='xr7QNAFIUrW1t22ek8'

bizID=7954760042973409999
Imgurl='https://dss0.bdstatic.com/l4oZeXSm1A5BphGlnYG/skin/115.jpg?2'    
    
host = 'https://openapi.waiqin365.com/api'
method = 'organization/v1/queryOrganization'
timstamp = time.strftime("%Y%m%d%H%M%S")
msgid = uuid.uuid1()

data = {
"bizId": bizID,
"instant":"0", # 0实时,1非实时
"images": [{
  "imageType": "0",
  "imageUrl": Imgurl
 }]
}

body_value=str(data)

digistSrc = '%s|%s|%s' %(body_value,appkey,timstamp)
m5 = hashlib.md5()
m5.update(digistSrc.encode('utf-8'))
digest = m5.hexdigest()

url = '%s/%s/%s/%s/%s/%s' % (host, method, openid, timstamp, digest, msgid)
print(url)

http = urllib3.PoolManager(cert_reqs='CERT_REQUIRED',ca_certs=certifi.where())
r = http.request('POST', url, headers={"Content-Type": "application/json", 'Accept-Encoding':'gzip, deflate'}, body=body_value)

if r.status == 200:
    data = r.data
    ret = json.loads(data.decode("utf-8"))
    return_code = ret.get("return_code")
    print("ReturnCode:\t%s" %(return_code))
    if return_code == 0:
        response_data = ret.get("response_data")
        print("ResponseData:\t%s" %(response_data))
    else:
        return_msg = ret.get("return_msg")
        print("ReturnMessage:\t%s" %(return_msg))
else:
    print(r.status)
    print(r.data)


# PHP代码示例

<?php
header("Content-Type: application/json;charset=utf-8");
date_default_timezone_set("Asia/Shanghai");

$OPENID="4956175043842151507";
$APPKEY="xr7QNAFIUrW1t22ek8";
$timestamp = date("Ymd").date("His");

$ROOT= "https://openapi.waiqin365.com/api/organization/v1/queryOrganization";

$body="{\"org_id\":\"0001\"}";
$msgid = md5(uniqid(mt_rand(), true));
$digest= md5($body. "|".$APPKEY."|". $timestamp);

$url= $ROOT. "/".$OPENID."/".$timestamp."/".$digest."/".$msgid;

$ret = request_by_curl($url,$body);
$ret_code = $ret->{"return_code"};
if($ret_code == 0)
{
    if(array_key_exists("response_data", $ret))
    {
        echo $ret->{"response_data"};
    }
}
else
{
    echo $ret_code . "\n";
    if(array_key_exists("return_msg", $ret))
    {
        echo $ret->{"return_msg"};
    }

}


function request_by_curl($sUrl, $body) {
  $ch = curl_init();
  $header[] = "Content-type: application/json;charset=UTF-8";
  curl_setopt($ch, CURLOPT_URL, $sUrl);
  curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
  curl_setopt($ch, CURLOPT_POSTFIELDS, $body);
  curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
  curl_setopt($ch, CURLOPT_ENCODING, "gzip,deflate");
  $response = curl_exec($ch);
  $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
  if ($http_code == 200)
  {
      $data = json_decode($response);
  }
  else
  {
      echo $http_code;
  }
  curl_close($ch);
  return $data;  
}
?>

# C#代码示例

using System;
using System.Text;
using System.Data;
using System.Data.SqlClient;
using System.IO;
using System.IO.Compression;
using System.Collections;
using System.Xml;
using System.Configuration;
using System.Net;
using System.Security.Cryptography;

namespace SyncWaiqin365Application 
{
	class SyncWaiqin365 
	{ 
		static void Main(string[] args) 
		{ 
			string openid = "4956175043842151507";
			string appkey = "xr7QNAFIUrW1t22ek8";
			string uuids = Guid.NewGuid().ToString("N");
			string timestamp = DateTime.Now.ToString("yyyyMMddHHmmss");
			string body = "{\"after_create_date\":\"2017-01-01 00:00:00\"}";
			string digest = MakeDigest(body + "|" + appkey + "|" + timestamp);

			string url = "https://openapi.waiqin365.com/api/store/v1/queryStore/" + openid + "/" + timestamp + "/" + digest + "/" + uuids;
			Console.WriteLine("Request URL:" + url);
			Console.WriteLine("Request BODY:" + body);
			string ret = httpPost(url, body);
			Console.WriteLine("Response: " + ret);

		}

		//md5摘要
		public static string MakeDigest(string inputString)
		{
			MD5 md5 = new MD5CryptoServiceProvider();
			byte[] data = md5.ComputeHash(Encoding.UTF8.GetBytes(inputString));
			StringBuilder sBuilder = new StringBuilder();
			for (int i = 0; i < data.Length; i++)
			{
				sBuilder.Append(data[i].ToString("x2"));
			}
			return sBuilder.ToString();
		}

		//post请求
		private static string httpPost(string serverUrl, string postData)
		{
			byte[] dataArray = Encoding.UTF8.GetBytes(postData);
			//创建请求  
			HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(serverUrl);
			request.Method = "POST";
			request.ContentLength = dataArray.Length;
			//设置上传服务的数据格式  
			request.ContentType = "application/json;charset=UTF-8";
			request.Headers.Add("Accept-Encoding", "gzip, deflate");
			//请求的身份验证信息为默认  
			request.Credentials = CredentialCache.DefaultCredentials;
			//请求超时时间  
			request.Timeout = 10000;
			//创建输入流  
			Stream dataStream;
			try
			{
				dataStream = request.GetRequestStream();
			}
			catch (Exception ex)
			{
				Console.WriteLine("发送请求失败:" + ex.Message);
				return null;
			}
			//发送请求  
			dataStream.Write(dataArray, 0, dataArray.Length);
			dataStream.Close();
			//读取返回消息  
			string res = null;
			try
			{
				HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                Stream responseStream = null;

				if (response.ContentEncoding.ToLower().Contains("gzip"))
				{
					responseStream = new GZipStream(response.GetResponseStream(), CompressionMode.Decompress);
				}
				else
				{
					if (response.ContentEncoding.ToLower().Contains("deflate"))
					{
						responseStream = new DeflateStream(response.GetResponseStream(), CompressionMode.Decompress);
					}
				}
				if (responseStream == null)
				{
					responseStream = response.GetResponseStream();
				}
				StreamReader reader = new StreamReader(responseStream, Encoding.UTF8);
				res = reader.ReadToEnd();
				reader.Close();
			}
			catch(WebException e) {
				Console.WriteLine(" 请求服务器响应异常:" + e.Message);
                return null;
			}
			catch (Exception ex)
			{
				Console.WriteLine("响应失败:" + ex.Message);
				return null;
			}
			return res;
		}
	}
} 

# 接收勤策推送数据

# SpringBoot代码示例

项目 名称 大小
接收勤策推送示例 springboot-waiqin365.zip (opens new window) 112 KB
    1.将示例代码导入IDEA之后启动运行。
    2.在浏览器中输入,开始模拟请求数据:
    http://127.0.0.1:8080/waiqin365/mock
    3.在ProcessFactory中加入同步保存数据处理代码。建议接收到推送数据后保存入库完成即可同步返回,后面启动新线程ProcessSubThread处理业务逻辑

# SpringMVC框架代码示例

import com.alibaba.fastjson.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.security.MessageDigest;

@Controller
@RequestMapping(value = "/")
public class ReceiverController
{
	private static final Logger logger = LoggerFactory.getLogger(ReceiverController.class);
	public static String PUSH_SECRET = "xxxxxxx";

	@RequestMapping(value = "/receivce")
	@ResponseBody
	public JSONObject receivce(String msgId, String dataType, String dataId, String dataVersion, String dataFormat, String dataSource, String data, long timestamp,String digest, String status, @RequestParam(required = false) String statusTime, String tenantId)
	{

		logger.info("[NEW]===========================================================");
		logger.info("msgId:      {}", msgId);
		logger.info("dataType:   {}", dataType);
		logger.info("dataId:     {}", dataId);
		logger.info("dataVersion:{}", dataVersion);
		logger.info("dataFormat: {}", dataFormat);
		logger.info("dataSource: {}", dataSource);
		logger.info("data:       {}", data);
		logger.info("timestamp:  {}", timestamp);
		logger.info("digest:     {}", digest);
		logger.info("status:     {}", status);
		logger.info("statusTime: {}", statusTime);
		logger.info("tenantId:   {}", tenantId);

		StringBuffer mdata = new StringBuffer();
		mdata.append(data).append("|").append(PUSH_SECRET).append("|").append(timestamp);
		String ndigest = encodeMd5(mdata.toString());
		logger.info("Calcdigest: {}", ndigest);

		if(!ndigest.equals(digest))
		{
			JSONObject json = new JSONObject();
			json.put("return_code", "1");
			json.put("return_msg", "数据签名校验失败,请求不合法!");
			return json;
		}
		// TODO: add proccess code

		JSONObject json = new JSONObject();
		json.put("return_code", "0");
		return json;
	}

	public static synchronized String encodeMd5(String data)
	{
		MessageDigest digest = null;
		if (digest == null)
		{
			try
			{
				digest = MessageDigest.getInstance("MD5");
				digest.update(data.getBytes("UTF-8"));
				byte[] hash = digest.digest();

				StringBuffer buf = new StringBuffer(hash.length * 2);
				int i;
				for (i = 0; i < hash.length; i++)
				{
					if ((hash[i] & 0xff) < 0x10)
					{
						buf.append("0");
					}
					buf.append(Long.toString(hash[i] & 0xff, 16));
				}
				return buf.toString();
			}
			catch (Exception nsae)
			{
				System.err.println("Failed to load the MD5 MessageDigest. ");
			}
		}
		return null;
	}

}

# JSP代码示例

<%@ page language="java" pageEncoding="UTF-8"%>
<%@ page import="com.zk.platform.util.StringUtil" %>
<%@ page import="com.alibaba.fastjson.JSONObject" %>
<%
    String PUSH_SECRET = "xxxxxx";

    String msgId = request.getParameter("msgId");
    String dataType = request.getParameter("dataType");
    String dataId = request.getParameter("dataId");
    String dataVersion = request.getParameter("dataVersion");
    String dataFormat = request.getParameter("dataFormat");
    String dataSource = request.getParameter("dataSource");
    String data = request.getParameter("data");
    String timestamp = request.getParameter("timestamp");
    String digest = request.getParameter("digest");
    String status = request.getParameter("status");
    String statusTime = request.getParameter("statusTime");
    String tenantId = request.getParameter("tenantId");

    System.out.println("[NEW]===========================================================");
    System.out.println("msgId:      " +  msgId);
    System.out.println("dataType:   " +  dataType);
    System.out.println("dataId:     " +  dataId);
    System.out.println("dataVersion:" +  dataVersion);
    System.out.println("dataFormat: " +  dataFormat);
    System.out.println("dataSource: " +  dataSource);
    System.out.println("data:       " +  data);
    System.out.println("timestamp:  " +  timestamp);
    System.out.println("digest:     " +  digest);
    System.out.println("status:     " +  status);
    System.out.println("statusTime: " +  statusTime);
    System.out.println("tenantId:   " +  tenantId);

    StringBuffer mdata = new StringBuffer();
    mdata.append(data).append("|").append(PUSH_SECRET).append("|").append(timestamp);
    String ndigest = StringUtil.hashKey(mdata.toString(), StringUtil.HASH_TYPE_MD5);
    System.out.println("Calcdigest: " +  ndigest);

    if(!ndigest.equals(digest))
    {
        JSONObject json = new JSONObject();
        json.put("return_code", "1");
        json.put("return_msg", "数据签名校验失败,请求不合法!");
        out.println(json.toString());
        return;
    }
    JSONObject json = new JSONObject();
    json.put("return_code", "0");
    out.println(json.toString());
%>