python回复企业微信接收消息服务器验证 企业微信验证短信_微信

package com.eam.wx.entity;

import org.jxstar.util.config.SystemVar;

/**
 * 微信参数
 * 
 * @author feixiang Peng
 * 
 */
public class WxParames {
	// 1.微信参数
	// token
	public final static String token = "ray";
	// encodingAESKey
	public final static String encodingAESKey = "encodingAESKey";
	// 企业应用的id,整型。可在应用的设置页面查看
	public final static int agentId = "agentId";
	// 企业ID
	public final static String corpId = "corpId";
	// 应用的凭证秘钥
	public final static String agentSecret = "agentSecret";
	// 通讯录秘钥
	public final static String contactsSecret = "contactsSecret";
	//发送消息的请求URL
	public final static String sendMessage_Url = "https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token=";
	//获取access_token请求URL
	public final static String access_token_url = "https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=CORPID&corpsecret=CORPSECRET";
	//操作通讯录的请求URL
	public final static String createDepartment_url = "https://qyapi.weixin.qq.com/cgi-bin/department/create?access_token=ACCESS_TOKEN";
	public final static String updateDepartment_url = "https://qyapi.weixin.qq.com/cgi-bin/department/update?access_token=ACCESS_TOKEN";
	public final static String deleteDepartment_url = "https://qyapi.weixin.qq.com/cgi-bin/department/delete?access_token=ACCESS_TOKEN&id=ID";
	public final static String departmentList_url = "https://qyapi.weixin.qq.com/cgi-bin/department/list?access_token=ACCESS_TOKEN&id=ID";
	public final static String departmentUserList_url = "https://qyapi.weixin.qq.com/cgi-bin/user/simplelist?access_token=ACCESS_TOKEN&department_id=DEPARTMENT_ID&fetch_child=FETCH_CHILD";

	
	
	/**
	 * 以下是测试时使用的参数
	 */
//	// 企业应用的id,整型。可在应用的设置页面查看
//	public final static int agentId = 00000000;
//	// 企业ID
//	public final static String corpId = "corpId";
//	// 应用的凭证秘钥
//	public final static String agentSecret = "agentSecret";
//	// 通讯录秘钥
//	public final static String contactsSecret = "contactsSecret";



}
package com.eam.wx.controller;

import java.io.IOException;
import java.util.List;
import java.util.Map;
import org.jxstar.dao.DaoParam;
import org.jxstar.service.BusinessObject;
import com.eam.wx.controller.WeChatMsgSend;
import com.eam.wx.entity.WxParames;
import com.eam.wx.util.WeiXinUtil;
import com.gexin.fastjson.JSONObject;

/**
 * 定时任务业务逻辑类
 * 
 * @author pfx
 * 
 */
public class WeiXinServiceImpl extends BusinessObject {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	/**
	 * 待办消息数量提醒
	 * 
	 */
	public void sendoaMsgNum() {
		this._log.showDebug("-------------进入sendoaMsgNum-----------------");
		
		StringBuffer sb = new StringBuffer();
		
		sb.append("select distinct(user_id) as user_id from flow_todo");
		
		DaoParam param = _dao.createParam(sb.toString());
		List<Map<String, String>> list = _dao.query(param);
		for(Map<String, String> map:list){
			String user_id = map.get("user_id");
			StringBuffer mse = new StringBuffer();
			sb = new StringBuffer();
			sb.append("select count(0) as num from flow_todo where user_id = ? and (flow_level = 1 or flow_level is null)");
			String num1 = _dao.queryMap(_dao.createParam(sb.toString()).addStringValue(user_id)).get("num");
			sb = new StringBuffer();
			sb.append("select count(0) as num from flow_todo where user_id = ? and flow_level = 2");
			String num2 = _dao.queryMap(_dao.createParam(sb.toString()).addStringValue(user_id)).get("num");
			sb = new StringBuffer();
			sb.append("select count(0) as num from flow_todo where user_id = ? and flow_level = 3");
			String num3 = _dao.queryMap(_dao.createParam(sb.toString()).addStringValue(user_id)).get("num");
			int num = Integer.parseInt(num1)+Integer.parseInt(num2)+Integer.parseInt(num3);
			mse.append("特急: "+num3+"");
			mse.append("紧急: "+num2+"");
			mse.append("一般: "+num1+""+System.getProperty("line.separator"));
			mse.append("工作台现有"+num+"条待审批事项"+System.getProperty("line.separator"));
			mse.append("特急: "+num3+"");
			mse.append("紧急: "+num2+"");
			mse.append("一般: "+num1+"");
			
			
			if(sendMessage(user_id, mse.toString())){
				this._log.showDebug("发送消息成功!");
			}else{
				this._log.showDebug("发送消息失败!");
			}
		}
		
	}
	
	
	/**
	 * 获取未提示消息
	 */
	public void sendoaMsg() {

		this._log.showDebug("-------------进入sendoaMsg-----------------");
		StringBuffer sb = new StringBuffer();
		/*sb.append("select msg_id,to_userid,to_user,msg_content from oa_msg where qywx_inform is null or qywx_inform = 0 order by add_date asc");

		//催办微信提醒
		List<Map<String, String>> sendMessageList = _dao.query(_dao.createParam(sb.toString()));
		this._log.showDebug("有【" + sendMessageList.size() + "】条催办消息待发送...");
	
		// 未发送企业微信提醒的发送提醒
		for (Map<String, String> map : sendMessageList) {
			String senduserid = map.get("to_userid");
			String senduser = map.get("to_user");
			String sendmessage = map.get("msg_content");
			boolean bool = sendMessage(senduserid, sendmessage);
			if(!bool){
				this._log.showDebug("发送消息给 【" + senduser + "】 失败!");
			}
			// 发送提醒成功,更改发送状态
			if (bool) {
				String msgId = map.get("msg_id");
				sb = new StringBuffer();
				sb.append("update oa_msg set qywx_inform=1 where msg_id = ? ");
				DaoParam dp = _dao.createParam(sb.toString());
				dp.addStringValue(msgId);
				bool = _dao.update(dp);
				// this._log.showDebug("更改信息状态:" + (bool ? "成功" : "失败"));
			}
		}*/
		
		
		//从待办任务获取
		sb = new StringBuffer();
		sb.append("select user_name,message,create_time,fun_name,flow_level,user_id,flow_todo_id,data_id,fun_id ");
		sb.append(" from flow_todo where is_send = '0'");
		
		String selTable = "select table_name,pk_col from fun_base where fun_id = ?";
		String selUser = null;

		//催办微信提醒
		List<Map<String, String>> sendTaskMessageList = _dao.query(_dao.createParam(sb.toString()));
		this._log.showDebug("有【" + sendTaskMessageList.size() + "】条通知消息待发送...");
		// 未发送企业微信提醒的发送提醒
		for (Map<String, String> map : sendTaskMessageList) {
			String senduserid = map.get("user_id");
			String senduser = map.get("user_name");
			String fun_name = map.get("fun_name");
			String message = map.get("message");
			String flow_level = map.get("flow_level");
			if("1".equals(flow_level)){
				flow_level = "一般";
			}else if("2".equals(flow_level)){
				flow_level = "紧急!";
			}else if("3".equals(flow_level)){
				flow_level = "特急!!";
			}else{
				flow_level = "一般";
			}
			
			//取得表名
			DaoParam param1 = _dao.createParam(selTable);
			param1.addStringValue(map.get("fun_id"));
			String table_name = _dao.queryMap(param1).get("table_name");
			String pk_col = _dao.queryMap(param1).get("pk_col");
			
			//取得单据发起人
			selUser = "select user_name,dept_name,add_date from "+table_name+" where "+pk_col+" = ?";
			DaoParam param = _dao.createParam(selUser);
			param.addStringValue(map.get("data_id"));
			String user_name = _dao.queryMap(param).get("user_name");
			String dept_name = _dao.queryMap(param).get("dept_name");
			String add_date = _dao.queryMap(param).get("add_date");
			
			String newLine = System.getProperty("line.separator");//获取换行符
			String sendmessage = "紧急程度:"+flow_level+newLine+"您有新的待审批任务:"+newLine+"名称:"+fun_name+newLine+"审批内容:"+message+newLine
					+"发起人:"+user_name+newLine+"发起部门:"+dept_name+newLine+"发起时间:"+add_date+newLine+"紧急程度:"+flow_level;
			//this._log.showDebug("sendmessage:"+sendmessage);
			boolean bool = sendMessage(senduserid, sendmessage);
			if(!bool){
				this._log.showDebug("发送消息给 【" + senduser + "】 失败!");
			}
			// 发送提醒成功,更改发送状态
			if (bool) {
				String taskId = map.get("flow_todo_id");
				sb = new StringBuffer();
				sb.append("update flow_todo set is_send = '1' where flow_todo_id = ? ");
				DaoParam dp = _dao.createParam(sb.toString());
				dp.addStringValue(taskId);
				bool = _dao.update(dp);
				// this._log.showDebug("更改信息状态:" + (bool ? "成功" : "失败"));
			}
		}
		
		
		
		
		
		

	}
	
	/**
	 * 添加发送的企业微信消息日志(待完成)
	 * @return
	 */
	public boolean insertNoteLog(String msg_state,String msg_type,String msg_desc){
		
		String insertSql = "INSERT INTO wx_message(" +
				"msg_state, msg_type, bus_code, bus_name, msg_title, msg_desc, touser, pic_url, msg_url, edit_userid, " +
				"edit_user, write_date, plan_date, send_time, return_code, return_msg, msg_id, add_userid, add_date, modify_userid," +
				" modify_date, tenant_id, template_id) VALUES " +
				"('msg_state', 'msg_type', 'bus_code', 'bus_name', 'msg_title', 'msg_desc', 'touser', 'pic_url', 'msg_url', 'edit_userid', " +
				"'edit_user', 'write_date', 'plan_date', 'send_time', 'return_code', 'return_msg', 'msg_id', 'add_userid', 'add_date', 'modify_userid', " +
				"'modify_date', 'tenant_id', 'template_id' )";

		return false;
		
	}

	/**
	 * 发送微信消息
	 * 
	 * @param message
	 */
	public boolean sendMessage(String senduserid, String sendmessage) {
		StringBuffer sb = new StringBuffer();
		boolean bool = false;
		// 发送人不为空
		if (!senduserid.isEmpty()) {
			// 查询系统中该用户消息
			sb.append("select * from sys_user where user_id = ?");
			DaoParam dp = _dao.createParam(sb.toString());
			dp.addStringValue(senduserid);

			Map<String, String> userMap = _dao.queryMap(dp);

			// 查询出该用户,并查看是否存在微信id
			if (!userMap.isEmpty()) {
				String wxqyUserid = userMap.get("wxqy_userid");
				// TODO 测试发送时,给下面变量赋值固定发送给一个测试人员
				//wxqyUserid = "lil.r";
				//wxqyUserid = "PengFeiXiang";
				// 企业用户不为空,同步企业微信数据
				if (!wxqyUserid.isEmpty()) {
					bool = sendMessageToQYWeiXin(wxqyUserid, sendmessage);
				} else {
					this._log.showDebug("用户【" + senduserid + "】企业微信映射不存在!");
				}
			} else {
				this._log.showDebug("接收信息用户【" + senduserid + "】不存在!");
			}
		}
		return bool;

	}

	/**
	 * 发送消息到企业微信
	 */
	public boolean sendMessageToQYWeiXin(String wxqyUserid, String sendmessage) {
		WeChatMsgSend swx = new WeChatMsgSend();
		boolean bool = false;
		try {
			String token = WeiXinUtil.getAccessToken(WxParames.agentSecret);
			String postdata = swx.createpostdata(wxqyUserid, "text", WxParames.agentId, "content", sendmessage);
			String resp = swx.post("utf-8", WeChatMsgSend.CONTENT_TYPE, WxParames.sendMessage_Url, postdata, token);
			// this._log.showDebug("获取到的token======>" + token);
			// this._log.showDebug("请求数据======>" + postdata);
			// this._log.showDebug("发送微信的响应数据======>" + resp);
			JSONObject jsonObject = JSONObject.parseObject(resp);
			String errcode = jsonObject.get("errcode").toString();
			// String errmsg = jsonObject.get("errmsg").toString();
			if ("0".equals(errcode)) {
				bool = true;
				this._log.showDebug("发送给【" + wxqyUserid + "】的消息【" + sendmessage + "】成功!");
			}else{
				this._log.showDebug("发送给【" + wxqyUserid + "】的消息【" + sendmessage + "】失败! 错误码为:"+errcode+",token为"+token);
			}
		} catch (IOException e) {
			e.printStackTrace();
			bool = false;
		}

		return bool;
	}

	/**
	 * 更新企业通讯录,映射本地与企业微信用户名关联
	 * 
	 * @throws IOException
	 */
	public void getAllParmentInfo() {
		WeiXinUtil wxUtil = new WeiXinUtil();
		StringBuffer sb = new StringBuffer();
		List<Map<String, Object>> wxUserList = wxUtil.getAllwxUser();

		for (Map<String, Object> userMap : wxUserList) {
			String wxUserid = userMap.get("userid").toString();
			String wxUserName = userMap.get("name").toString();
			//企业微信用户名不规范,特作此处理
			if(wxUserName.indexOf("-")!=-1){
				String users[] = wxUserName.split("-");
				for(int i = users.length-1;i>=0;i--){
					if(checkAllParmentInfo(users[i],wxUserid)){
						break;
					}
				}
			}else{
				checkAllParmentInfo(wxUserName,wxUserid);
			}
			

		}

	}
	
	public boolean checkAllParmentInfo(String wxUserName,String wxUserid){
		// 查询现有数据
		StringBuffer sb = new StringBuffer();
		sb.append("select * from sys_user where user_name = ?");
		DaoParam dp = _dao.createParam(sb.toString());
		dp.addStringValue(wxUserName);
		List<Map<String, String>> userList = _dao.query(dp);
		if (!userList.isEmpty()) {
			// 有且只有一个同名用户
			if (userList.size() == 1) {
				String localwxqyUserid = userList.get(0).get("wxqy_userid");
				String localUserid = userList.get(0).get("user_id");
				// 更新用户信息映射数据
					sb = new StringBuffer();
					sb.append("UPDATE sys_user SET wx_openid = 'wx_openid' , wxqy_userid = ? WHERE user_id = ?");
					DaoParam updatedp = _dao.createParam(sb.toString());
					updatedp.addStringValue(wxUserid);
					updatedp.addStringValue(localUserid);
					boolean bool = _dao.update(updatedp);
					if(!bool){
						this._log.showDebug("更新【" + wxUserName + "】企业微信映射失败" );
						return false;
					}
			} else {
				this._log.showDebug("查询到多个【" + wxUserName + "】的本地人员信息");
				return false;
			}
		} else {
			this._log.showDebug("未查询到【" + wxUserName + "】的本地人员信息");
			return false;
		}
		return true;
	}

}