WeChatServiceImpl.java 9.89 KB
package com.phxl.modules.wechat.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.phxl.common.util.Global;
import com.phxl.common.util.HTTPClient;
import com.phxl.common.util.JsonMapper;
import com.phxl.common.utils.BaseException;
import com.phxl.common.utils.CacheUtils;
import com.phxl.modules.wechat.constants.WeChatConstants;
import com.phxl.modules.wechat.constants.WeChatEnum;
import com.phxl.modules.wechat.entity.PushOrder;
import com.phxl.modules.wechat.entity.RequestParams;
import com.phxl.modules.wechat.service.WeChatService;
import com.phxl.modules.wechat.utils.WeChatHttpClient;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.text.SimpleDateFormat;

@Service("weChatServiceImpl")
public class WeChatServiceImpl implements WeChatService {

	private Logger logger=LoggerFactory.getLogger(WeChatServiceImpl.class);
	
	@Override
	public String pushData(String params,String url) {
		String sendJsonDataByPost="";
		try {
		    SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			RequestParams requestParams = JSON.toJavaObject((JSONObject)JSON.parse(params), RequestParams.class);
			for (String userOpenId : requestParams.getToUsers()) {
				WeChatEnum weChatEnum = WeChatEnum.valueOf(requestParams.getFindType());
				if(requestParams.getFindType().equals(WeChatConstants.order_type)) {
					for (PushOrder orders : requestParams.getParams()) {
						JSONObject subject=new JSONObject();
						//subject.put("url","http://subvau.natappfree.cc/dist/#/orderList/"+orders.getOrderNo());
						subject.put("url",weChatEnum.getFindLoc()+orders.getOrderNo());
						subject.put("touser",userOpenId);
						subject.put("template_id",weChatEnum.getTemplateId());
						JSONObject data=new JSONObject();
						//first
						JSONObject first=new JSONObject();
						first.put("value",weChatEnum.getFindMessage()+ orders.getStatusName());
						first.put("color","#173177");
						//订单号
						JSONObject order=new JSONObject();
						order.put("value",orders.getOrderNo());
						order.put("color","#173177");
						//变更时间
						JSONObject update=new JSONObject();
						update.put("value", simpleDateFormat.format(orders.getUpdateDate()));
						update.put("color","#173177");
						//订单号
						JSONObject remark=new JSONObject();
						remark.put("value","请注意查收!");
						remark.put("color","#173177");
						/*//品规数
						JSONObject count=new JSONObject();
						count.put("value", orders.getDrugCount());
						count.put("color","#173177");
						//总金额
						JSONObject totalPrice=new JSONObject();
						totalPrice.put("value", orders.getTotalPrice().setScale(2,BigDecimal.ROUND_DOWN));
						totalPrice.put("color","#173177");
						//制单人
						JSONObject user=new JSONObject();
						user.put("value", orders.getCreateUserName());
						user.put("color","#173177");
						//变更时间
						JSONObject update=new JSONObject();
						update.put("value", simpleDateFormat.format(orders.getUpdateDate()));
						update.put("color","#173177");*/
						data.put("first",first);
						data.put("remark",remark);
						data.put("keyword1",order);
						data.put("keyword2",update);
						/*data.put("count",count);
						data.put("price",totalPrice);
						data.put("user",user);
						data.put("update",update);*/
						subject.put("data",data);
						sendJsonDataByPost=push(JsonMapper.toJsonString(subject));
					}
				}else {
					JSONObject subject=new JSONObject();
					subject.put("touser",userOpenId);
					//subject.put("url","http://subvau.natappfree.cc"+weChatEnum.getFindLoc());
					subject.put("url",weChatEnum.getFindLoc());
					subject.put("template_id", weChatEnum.getTemplateId());
					JSONObject data=new JSONObject();
					JSONObject first=new JSONObject();
					first.put("value", weChatEnum.getFindMessage());
					first.put("color","#173177");
					
					JSONObject keyword1=new JSONObject();
					keyword1.put("value", requestParams.getParams().get(0).getName());
					keyword1.put("color","#173177");
					JSONObject keyword2=new JSONObject();
					keyword2.put("value", requestParams.getParams().get(0).getTime());
					keyword2.put("color","#173177");

					JSONObject remark=new JSONObject();
					remark.put("value","请注意查收!");
					remark.put("color","#173177");
					data.put("first",first);
					data.put("keyword1",keyword1);
					data.put("keyword2",keyword2);
					data.put("remark",remark);
					subject.put("data",data);
					sendJsonDataByPost=push(JsonMapper.toJsonString(subject));
				}
			}
		} catch (Exception e) {
			logger.error("推送微信端接口报错:"+e.getMessage());
		}
		return sendJsonDataByPost;
	}

	public String push(String params) throws Exception {
		Object object = CacheUtils.get(WeChatConstants.Access_Token);
		String pushMesUrl=WeChatConstants.push_mes_url.replace("ACCESSTOKEN", object.toString());
		String sendJsonDataByPost = HTTPClient.sendJsonDataByPost(pushMesUrl,params);
		JSONObject jsonObject = JSONObject.parseObject(sendJsonDataByPost);
		if(jsonObject.get("errcode").equals(0)) {
			logger.info("推送微信端接口成功:"+jsonObject.get("errmsg"));
		}else {
			logger.error("推送微信接口失败:"+jsonObject.get("errmsg"));
		}
		return sendJsonDataByPost;
	}

	
	@Override
	public JSONObject findDataList(JSONObject jsonObject) {
		 try {
			String config = Global.getConfig("spd_wechat_url");
			String sendJsonDataByPost = WeChatHttpClient.sendPostData(config+"findDatas",jsonObject);
			 JSONObject dataObject=JSONObject.parseObject(sendJsonDataByPost);
			 if(dataObject==null) {
			 	//返回前端进行跳转登录界面
				 dataObject=new JSONObject();
				 dataObject.put("code","123");
				 dataObject.put("message","用户登录信息过期!请重新登陆");
			 }
			 return dataObject;
		 } catch (Exception e) {
			logger.error("查询数据错误:"+e.getMessage());
			throw new BaseException("查询数据错误:"+e.getMessage());
		 }

	}

	@Override
	public JSONObject queryDrugInfo(JSONObject jsonObject) {
	     try {
			String config = Global.getConfig("spd_wechat_url");
			jsonObject.put("queryType",3);
			String sendJsonDataByPost =  WeChatHttpClient.sendPostData(config+"queryDrugByList",jsonObject);
		     JSONObject dataObject=JSONObject.parseObject(sendJsonDataByPost);
		     if(dataObject==null) {
			     dataObject=new JSONObject();
			     dataObject.put("code","123");
			     dataObject.put("message","用户登录信息过期!请重新登陆");
		     }
		     return dataObject;
	     } catch (Exception e) {
			logger.error("查询数据错误:"+e.getMessage());
			throw new BaseException("查询数据错误:"+e.getMessage());
	     }

	}

	
	@Override
	public String login(HttpServletRequest request, HttpServletResponse response) {
		String code=request.getParameter("code");
		try {
			String openId = getOpenId(code);
			if (StringUtils.isEmpty(openId)) {
				logger.error("登录失败!未获得用户openId,请稍后重新登录!");
				throw new BaseException("登录失败!未获得用户openId,请稍后重新登录!");
			}
			String config = Global.getConfig("spd_wechat_login");
			JSONObject jsonObject=new JSONObject();
			jsonObject.put("openId",openId);
			jsonObject.put("sessionId",request.getSession().getId());
			jsonObject.put("username",request.getParameter("username"));
			jsonObject.put("password",request.getParameter("password"));
			String sendJsonDataByPost = WeChatHttpClient.sendLogin(config,jsonObject);
			if (StringUtils.isEmpty(sendJsonDataByPost)) {
				logger.error("登录失败!"+sendJsonDataByPost);
				throw new BaseException("登录失败"+sendJsonDataByPost);
			}
			System.out.print(sendJsonDataByPost);
			return sendJsonDataByPost;
		}catch(Exception ex){
			logger.error("登录失败:"+ex.getMessage());
			throw new BaseException("登录失败:"+ex.getMessage());
		}
	}

	/**
	 * 得到用户openId
	 * @param code
	 * @return
	 */
	public String getOpenId(String code) {
		if(StringUtils.isNotEmpty(code)) {
			String appid=Global.getConfig("appid");
			String appsecrent=Global.getConfig("appsecrent");
			String url=WeChatConstants.wechat_open_id.replace("APPID", appid).replace("SECRET", appsecrent).replace("CODE", code);
			String sendHttpGet = HTTPClient.sendHttpGet(url);
			if(StringUtils.isNotEmpty(sendHttpGet)) {
				JSONObject jsonObject=JSONObject.parseObject(sendHttpGet);
				String openid = jsonObject.getString("openid");
				return openid;
			}
		}
		return null;
	}


	@Override
	public String logout(HttpServletRequest request, HttpServletResponse response) {
		String url = Global.getConfig("spd_wechat_logout");
		String sendHttpGet = WeChatHttpClient.sendLogout(url,request.getParameter("token"));
		return sendHttpGet;
	}

	@Override
	public String createMenu() {
		String sendJsonDataByPost="";
		try {
			String url="https://api.weixin.qq.com/cgi-bin/menu/create?access_token="+CacheUtils.get(WeChatConstants.Access_Token).toString();
			JSONObject jsonObject=new JSONObject();
			JSONArray ja=new JSONArray();
			JSONArray ja1=new JSONArray();
			JSONObject ob=new JSONObject();
			JSONObject ob1=new JSONObject();
			ob1.put("type","view");
			ob1.put("name","药品信息查询");
			ob1.put("url","http://6i3fx5.natappfree.cc/dist");
			ja1.add(ob1);
			ob.put("name","信息查询");
			ob.put("sub_button",ja1);
			ja.add(ob);
			jsonObject.put("button",ja1);
			sendJsonDataByPost= HTTPClient.sendJsonDataByPost(url,JsonMapper.toJsonString(jsonObject));
		} catch (Exception e) {
			e.printStackTrace();
		}
		return sendJsonDataByPost;
	}

	@Override
	public String deleteMenu() {
		String url="https://api.weixin.qq.com/cgi-bin/menu/delete?access_token="+CacheUtils.get(WeChatConstants.Access_Token).toString();
		String s = HTTPClient.sendHttpGet(url);
		return s;
	}

}