附录三:代码示例

项目 名称 大小
JAVA开发工具包 openapi_tools-1.0.8.jar 12.6 KB
接口示例包 demo-openapi.zip 1.18 MB

请求外勤365接口:

//Java 示例

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 openid = "4956175043842151507";
		String appkey = "xr7QNAFIUrW1t22ek8";

		WQOpenApi wqOpenApi = new WQOpenApi(openid, appkey);
		WQRequest request = new WQRequest();
		request.setWqOpenApi(wqOpenApi);
		request.setModule("organization");
		request.setVersion("v1");
		request.setOperation("modifyOrganization");
		
		JSONObject body = new JSONObject();
		body.put("org_id", "ORG001");
		body.put("org_name", "南京掌控网络");
		body.put("org_sequence", 002);
		
		request.setRequestdata(body.toJSONString());
		try
		{
			WQResponse res = WQApiHandler.handleOpenApi(request);
			System.out.println("return_code:" + res.getReturn_code());
			System.out.println("return_message:" + res.getReturn_msg());
		}
		catch (Exception e)
		{
			e.printStackTrace();
		}
	}
}
        

接收外勤365推送数据接口:

// Spring MVC 框架接收数据

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 API_APPKEY = "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, 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(API_APPKEY).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 API_APPKEY = "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(API_APPKEY).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());
%>
		
# Python代码示例

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

openid='4956175043842151507'
appkey='xr7QNAFIUrW1t22ek8'

    
host = 'https://openapi.waiqin365.com/api'
method = 'organization/v1/queryOrganization'
timstamp = time.strftime("%Y%m%d%H%M%S")
msgid = uuid.uuid1()

body_value='{"org_id":"0001"}' 

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;
		}
	}
}