微信关注后自动回复,根据关键字回复

package me.chunyu.apps.weixin.controller;

import java.io.IOException;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import me.chunyu.apps.weixin.WeixinMenuYanda2;
import org.apache.commons.lang.StringEscapeUtils;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.taikang.healthcare.cust.CustomerService;
import com.taikang.healthcare.cust.OpenidService;
import com.taikang.healthcare.cust.XindexService;
import com.taikang.healthcare.order.OrderService;
import com.taikang.healthcare.order.WxVisitService;
import com.taikang.healthcare.sdk.DateUtil;
import com.taikang.healthcare.user.service.DeptService;
import com.taikang.healthcare.user.service.EmpOpenidService;
import com.taikang.healthcare.user.service.EmpService;
import com.taikang.healthcare.user.service.WechatService;

import me.chanjar.weixin.common.bean.menu.WxMenu;
import me.chanjar.weixin.common.bean.menu.WxMenuButton;
import me.chanjar.weixin.common.exception.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpConfigStorage;
import me.chanjar.weixin.mp.api.WxMpInMemoryConfigStorage;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.api.impl.WxMpServiceImpl;
import me.chanjar.weixin.mp.bean.message.WxMpXmlMessage;
import me.chanjar.weixin.mp.bean.message.WxMpXmlOutMessage;
import me.chanjar.weixin.mp.bean.message.WxMpXmlOutNewsMessage;
import me.chanjar.weixin.mp.bean.message.WxMpXmlOutNewsMessage.Item;
import me.chanjar.weixin.mp.bean.message.WxMpXmlOutTextMessage;
import me.chunyu.lightmvc.apps.common.controller.BaseController;
import me.chunyu.lightmvc.utils.HttpCommandProvider;
import me.chunyu.lightmvc.utils.ImageUtil;
import me.chunyu.lightmvc.utils.OAuthUtil;
import me.chunyu.lightmvc.utils.SettingUtil;
import me.chunyu.lightmvc.utils.StringUtil;
import me.chunyu.lightmvc.utils.ValidationUtil;
import net.sf.json.JSONObject;


@RestController
@RequestMapping("/weihospital/weixin")
public class WeixinController extends BaseController{

  private static final Logger LOGGER = LoggerFactory.getLogger(WeixinController.class);

  @Autowired protected EmpService empService;
  @Autowired protected EmpOpenidService empOpenidService;
  @Autowired protected OpenidService openidService;
  @Autowired protected XindexService xindexService;
  @Autowired protected CustomerService customerService;
  @Autowired protected OrderService orderService;
  @Autowired protected DeptService deptService;
  @Autowired protected WechatService wechatService;
  @Autowired protected WxVisitService wxVisitService;

  protected static String wxPageAuth2Url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=APP_ID&redirect_uri=REDIRECT_URI&response_type=code&scope=snsapi_base&state=APP_ID#wechat_redirect";

//  protected static WxMpService WxService = new WxMpServiceImpl();
  protected static WxMpInMemoryConfigStorage config = new WxMpInMemoryConfigStorage();
  protected static Map<String,Object> weixinAppid = new HashMap<String,Object>();

  @RequestMapping("/{appId}/entry/")
  public void service(@PathVariable String appId, HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {

    response.setContentType("text/html;charset=utf-8");
    response.setStatus(HttpServletResponse.SC_OK);
    //微信安全校验
//    String signature = request.getParameter("signature");
    //屏蔽
//    logger.info("屏蔽微信安全验证");
    String nonce = request.getParameter("nonce");
    String timestamp = request.getParameter("timestamp");
//    config.setAccessToken(appId);
    weixinAppid.put("platAppId", appId);
    List<Map<String, Object>> hospitalList = null;
    try {
        hospitalList = weixinAppIdService.selectAppidByAppId(weixinAppid);
    } catch (Exception e) {
        e.printStackTrace();
        logger.error("微信安全验证不通过,获取weixin_appid对象异常:appId="+appId+", message="+e.getMessage());
    }
    if(hospitalList != null && hospitalList.size() > 0){
        weixinAppid = hospitalList.get(0);
        if(StringUtil.notNull(weixinAppid,"platformAppId","platformSecretId", "platformToken", "platformAeskey")){
            config.setSecret(weixinAppid.get("platformSecretId").toString());
            config.setToken(weixinAppid.get("platformToken").toString());
            config.setAesKey(weixinAppid.get("platformAeskey").toString());
        }else {
            logger.error("微信安全验证不通过,weixin_appid配置不完整:appId="+appId+", weixinAppid="+weixinAppid.toString());
        }
    }else {
        logger.error("微信安全验证不通过,缺少weixin_appid对象:appId="+appId);
    }
//    WxService.setWxMpConfigStorage(config);

//    if (!WxService.checkSignature(timestamp, nonce, signature)) {
//      // 消息签名不正确,说明不是公众平台发过来的消息
//      response.getWriter().println("非法请求");
//      return;
//    }

    String echostr = request.getParameter("echostr");
    String encryptType = StringUtils.isBlank(request.getParameter("encrypt_type")) ? "raw" : request.getParameter("encrypt_type");

    if (StringUtils.isNotBlank(echostr)) {
      // 说明是一个仅仅用来验证的请求,回显echostr
      response.getWriter().println(echostr);
    } else if ("raw".equals(encryptType)) {
      // 明文传输的消息
      WxMpXmlMessage inMessage = WxMpXmlMessage.fromXml(request.getInputStream());
      WxMpXmlOutMessage outMessage = handle(weixinAppid,inMessage,request);
      if (outMessage != null) {
        response.getWriter().write(outMessage.toXml());
      }
    } else if ("aes".equals(encryptType)) {
            WxMpConfigStorage WxconfigStorage = config;
      // 是aes加密的消息
      String msgSignature = request.getParameter("msg_signature");
      WxMpXmlMessage inMessage = WxMpXmlMessage.fromEncryptedXml(request.getInputStream(),  WxconfigStorage, timestamp, nonce, msgSignature);
      WxMpXmlOutMessage outMessage = handle(weixinAppid,inMessage,request);
      if (outMessage != null) {
        response.getWriter().write(outMessage.toEncryptedXml(WxconfigStorage)+outMessage.toEncryptedXml(WxconfigStorage));
      }
    } else {
      response.getWriter().println("不可识别的加密类型");
    }
  }

  public WxMpXmlOutMessage handle(Map<String,Object> weixinAppid,WxMpXmlMessage wxMessage,HttpServletRequest request) {
    try {
            String orgName = "", partnerKey = "", partner = "", empId= "", cyDoctorId="", empName="";
            String positionName = "", smallPortrait ="";
            String ticket_type="0"; //处理医生二维码 多渠道 234343_1 前面是empId 后面是 渠道方式 1科室
            int deptId = 0;
            long orgId = 0l;
        if(StringUtil.notNull(weixinAppid,"name","partnerkey", "partner")){
            orgName = weixinAppid.get("name").toString();
            partnerKey = weixinAppid.get("partnerkey").toString();
            partner = weixinAppid.get("partner").toString();
            orgId = Long.valueOf(weixinAppid.get("org_id").toString());
        }
      logger.info(" eventInfo : "+ wxMessage.getEvent()+ ", fromUser: "+ wxMessage.getFromUser());
      //自动回复功能
      if("text".equals(wxMessage.getMsgType()) && 100==orgId) {
                  List<Map<String,Object>> autoReplyList= wechatService.queryAutoReplyByOrg(orgId);
                  for(Map<String,Object> autoReply : autoReplyList) {
                      String[] keywords = autoReply.get("keyword").toString().split("\\|");  //已竖线拆分关键字
                      for(String key : keywords) {
                          if(StringUtil.stringNotNull(key.trim()) && wxMessage.getContent().toUpperCase().contains(key.toUpperCase())) { //有字母的都转换成大写判断
                            String content=StringEscapeUtils.unescapeHtml(autoReply.get("content").toString());
                              return echoTextMessage(wxMessage, content);
                          }
                      }
                  }
      }
      if(null!=wxMessage.getEvent()){
            switch (wxMessage.getEvent()) {
                case "scan":
                case "SCAN":

                case "subscribe":
                    String eventKey = wxMessage.getEventKey();
                if(StringUtil.stringNotNull(eventKey)){
                        eventKey = eventKey.startsWith("qrscene_") ? eventKey.replace("qrscene_", "") : eventKey;
                        if(eventKey.contains("_")) {
                            String[] eventKeyArray = eventKey.split("_");
                            eventKey = eventKeyArray[0];
                            ticket_type = eventKeyArray[1];
                        }
                            if(ValidationUtil.isNumber(eventKey) && ValidationUtil.isNumber(ticket_type)){
                                Map<String,Object> mm = empService.selectEmpById(Long.valueOf(eventKey));
                                if(null!=mm && null!=mm.get("name") && null!=mm.get("deletedFlag") && !(boolean)mm.get("deletedFlag")){
                                    empId = eventKey;
                                    empName = mm.get("name").toString();
                                    cyDoctorId = mm.get("doctorId")==null?null:mm.get("doctorId").toString();
                                    positionName = mm.get("positionName")==null?"":mm.get("positionName").toString();
                                    deptId = mm.get("deptId")==null?0:(Integer)mm.get("deptId");
                                    smallPortrait = mm.get("smallPortrait")==null?"":mm.get("smallPortrait").toString();
                                }
                            }
                    }
                    if(StringUtil.stringNotNull(eventKey) && !"WIFI".equals(eventKey) && !"GHYDEWM".equals(eventKey.toUpperCase())){
                        //打点
                        Map<String,Object> sensorsMap = new HashMap<String,Object>();
                        sensorsMap.put("appId",weixinAppid.get("platformAppId").toString());
                        sensorsMap.put("openId", wxMessage.getFromUser());
                        sensorsMap.put("from_type", "weixin");
                        sensorsMap.put("doctorName", empName);
                        sensorsDataUtil.scanCodeOrder(request, sensorsMap, "wxScanMessage");
                    }
                    if(null!=empId&&!"".equals(empId)&&null!=empName&&!"".equals(empName)){
                        empOpenidService.saveEmpOpenid(Long.valueOf(empId), wxMessage.getFromUser(), orgId, Short.valueOf(ticket_type));
                        //保存记录openid
                        openidService.saveUserAndOpenid(wxMessage.getFromUser(), weixinAppid.get("platformAppId").toString(), (short)0);
                        LOGGER.info("扫描"+empName+"医生二维码");
                        if(StringUtil.stringNotNull(cyDoctorId)) {
                            subscribeDoctor(wxMessage.getFromUser(),Long.valueOf(empId),cyDoctorId,partner,partnerKey,weixinAppid.get("platformAppId").toString(),empName,request); //关注当前医生
                        }else {
                            LOGGER.error("emp not set cyDoctorId, empId:"+empId+", empName:"+empName);
                        }
                        if(("product".equals(SettingUtil.getEnvironment()) && !"100".equals(weixinAppid.get("org_id").toString()))  || (!"product".equals(SettingUtil.getEnvironment()) && "100".equals(weixinAppid.get("org_id").toString()))) {            //排除燕达
                            if(StringUtil.stringNotNull(cyDoctorId)) {
                                String url = SettingUtil.getHospitalsUrl()+"/cyhospital/revisitqaController/"+partner+"/revisitPage/?cyDoctorId="+cyDoctorId+"&user_id="+wxMessage.getFromUser();
                                String doctorImageUrl = "";
                                if(StringUtil.stringNotNull(smallPortrait)) {
                                    doctorImageUrl = SettingUtil.isMongodb()?SettingUtil.getSaasUrl()+"/prescriptionController/selectArrayTypeFileById?id="+smallPortrait : smallPortrait;
                                }
                                //推送客服图文消息
                                  Map<String,Object> dept  = new HashMap<String,Object>();
                                  dept.put("orgId", orgId);
                                  dept.put("deptId", deptId);
                                  dept = deptService.searchDeptById(dept);
                                  String picUrl = ImageUtil.graphicsGeneration(empName, dept.get("deptName").toString(), positionName, orgName, doctorImageUrl);
                                return echoNewsMessage(wxMessage, "", picUrl, "向"+empName+"医生咨询", url);
                            }else {
                                return echoTextMessage(wxMessage, "很抱歉,您关注的医生当前不在线,无法问诊。\n请选择其他医生问诊。");
                            }
                        }
                        //后来转发到我的医生的对应的医生首页
                        return echoTextMessage(wxMessage, "欢迎关注"+orgName+",您可以在线咨询医生,随时随地看病\n<a href=\""+wxPageAuth2Url.replaceAll("APP_ID", weixinAppid.get("platformAppId").toString()).replace("REDIRECT_URI", URLEncoder.encode(SettingUtil.getHospitalsUrl()+"/cyhospital/weihospital/"+partner+"/myDoctorListToh/?doctorId="+empId))+"\">点击这里,与"+empName+"医生交流</a>");
                    }else if(null!=eventKey && "WIFI".equals(eventKey)){
                        if(StringUtil.notNull(weixinAppid,"wifi_name")&&StringUtil.notNull(weixinAppid,"wifi_secret")){
                            return echoTextMessage(wxMessage, "您好,"+orgName+"wifi\n热点名:"+weixinAppid.get("wifi_name")+"\n密码:"+weixinAppid.get("wifi_secret"));
                        }
                    }else if(null!=eventKey && "YANDAZIXUN".equals(eventKey)){    //燕达咨询连接
                        return echoTextMessage(wxMessage, "<a href=\"https://put.zoosnet.net/LR/Chatpre.aspx?id=PUT32645561&lng=cn\">点击这里马上咨询</a>");
                    }else if(null!=eventKey && "GHYDEWM".equals(eventKey.toUpperCase())){  //支持挂号
                        //保存记录openid
                        openidService.saveUserAndOpenid(wxMessage.getFromUser(), weixinAppid.get("platformAppId").toString(), (short)0);
                        //统计访问量
                        String visit_url = SettingUtil.getHospitalsUrl() + "/cyhospital/weihospital/"+partner+"/clinicIndex/";
                        wxVisitService.insertWxVisitRecord(wxMessage.getFromUser(),weixinAppid.get("platformAppId").toString(),visit_url, "1", DateUtil.getCurrentTime(),"ghydewm");
                        //推送挂号链接
                        return echoTextMessage(wxMessage, "欢迎关注"+orgName+",请点击<a href=\""+wxPageAuth2Url.replaceAll("APP_ID", weixinAppid.get("platformAppId").toString()).replace("REDIRECT_URI", URLEncoder.encode(SettingUtil.getHospitalsUrl()+"/cyhospital/weihospital/"+partner+"/clinicIndex/"))+"\">这里</a>进行挂号");
                    } else if (null!=eventKey && "TOHCDM".equals(eventKey.toUpperCase())){
                        return echoTextMessage(wxMessage, "智能血压管理,京冀医疗合作示范三级综合医院医生1对1服务,为用户制定专属降压方案,服务有:24小时动态血压、单月血压服务、包年血压服务还附赠【脉搏专业医疗级别智能云血压计1台】等更多选择。\n<a href=\""+wxPageAuth2Url.replaceAll("APP_ID", weixinAppid.get("platformAppId").toString()).replace("REDIRECT_URI", URLEncoder.encode(SettingUtil.getHospitalsUrl()+"/cyhospital/redirects/yanda/goToCdmIndex/"))+"\">点击这里,了解详情</a>");
                    }else {
                        if("100".equals(weixinAppid.get("org_id").toString())) {
                            String autoReplyContent = "";

                            //String content=wechatService.queryAutoReplyByKeyWord(map);
                            List<Map<String, Object>> autoReplyList = wechatService.queryAutoReplyByOrg(orgId);
                            for (Map<String, Object> autoReply : autoReplyList) {
                                if (autoReply.get("keyword").equals("gz")) { //有字母的都转换成大写判断
                                    autoReplyContent = autoReply.get("content").toString();
                                    break;
                                }
                            }
                            //转义
                            //StringEscapeUtils.escapeHtml(content);
                            //反转义
                            autoReplyContent = StringEscapeUtils.unescapeHtml(autoReplyContent);
                            autoReplyContent = autoReplyContent.replace("<br>", "\r\n");
                            return echoTextMessage(wxMessage, "欢迎关注" + autoReplyContent);

                        }else{
                            return echoTextMessage(wxMessage, "欢迎关注" + orgName);

                        }
                    }
                case "VIEW":
                        //保存记录openid
                        openidService.saveUserAndOpenid(wxMessage.getFromUser(), weixinAppid.get("platformAppId").toString(), (short)0);
                        return null;
                case "text":
                  return echoTextMessage(wxMessage, String.format("您发送的消息为:%s",wxMessage.getContent()));
                case "CLICK":
                case "image":
                default:
                  return echoTextMessage(wxMessage, String.format("未识别消息类型:%s",wxMessage.getEvent()));
              }
        }
    } catch (Exception ex) {
      LOGGER.error("", ex);
    }
    return null;
  }

  public WxMpXmlOutMessage echoTextMessage(WxMpXmlMessage wxMessage, String text) {
    WxMpXmlOutTextMessage m = WxMpXmlOutTextMessage.TEXT().content(text)
                    .fromUser(wxMessage.getToUser()).toUser(wxMessage.getFromUser()).build();
    return m;
  }

  public WxMpXmlOutMessage echoNewsMessage(WxMpXmlMessage wxMessage, String description, String picUrl, String title, String url) {
      Item item = new Item();
      item.setDescription(description);
      item.setPicUrl(picUrl);
      item.setTitle(title);
      item.setUrl(url);
      WxMpXmlOutNewsMessage m = WxMpXmlOutNewsMessage.NEWS().addArticle(item)
              .fromUser(wxMessage.getToUser()).toUser(wxMessage.getFromUser()).build();
        return m;
  }

  //内容消息连接
  protected static String message1Url = "/cyhospital/weihospital/PARTNER/my_bill/?cuXindexId=CUXINDEXID";
  protected static String message2Url = "/cyhospital/weihospital/PARTNER/checkup_info/?cardNo=CARDNO&sync=1";
  protected static String message3Url = "/cyhospital/weihospital/PARTNER/checkup_info/?cardNo=CARDNO&sync=1";
  protected static String message11Url = "/cyhospital/weihospital/PARTNER/my_bill/?cuXindexId=CUXINDEXID";
  //模版类型:1缴费提醒,2检验报告,3检查报告,10医生回复消息模版,11就诊通知
  @RequestMapping("/sendMessage/")
  public void sendMessage(String orgId,String hisId,String messageType,String boTicketId, HttpServletRequest request, HttpServletResponse response){
      try {
        Map<String,Object> prem = new HashMap<String,Object>();
        prem.put("orgId", orgId);
        List<String> openIdList = new ArrayList<String>();
        List<Map<String,Object>> appList = weixinAppIdService.selectAppidByOrgId(prem);
            for(Map<String,Object> appMap : appList) {
                String appId = appMap.get("platformAppId").toString();
                String appSecret = appMap.get("platformSecretId").toString();
                Map<String,Object> messageTemplate = wxSendTemplateMessageService.getWxMessageTemplate(Long.valueOf(orgId), appId, Integer.valueOf(messageType));
                if(StringUtil.notNull(messageTemplate, "template_id")){
               openIdList = openidService.searchOpenidByOrgIdAndHisId(Integer.valueOf(orgId),hisId,appId,(short)0);
               LOGGER.info("微推开始:orgId="+orgId+", hisId="+hisId+", messageType="+messageType+", openid="+openIdList.toString());
               if(null!=openIdList && openIdList.size()>0){
                    String url = "";
                    String data = "";
                    Map<String,Object> preMap = new HashMap<String,Object>();
                    preMap.put("typeId", Integer.valueOf(orgId));
                    preMap.put("value", hisId);
                    List<Map<String,Object>> xindexList = xindexService.search(preMap);
                    String topcolor = "";
                    if(StringUtil.notNull(messageTemplate, "topcolor")){
                        topcolor = messageTemplate.get("topcolor").toString();
                    }
                    if(null!=xindexList&&xindexList.size()>0&&null!=xindexList.get(0).get("customerId")){
                        Map<String,Object> custMap= customerService.searchById(xindexList.get(0).get("customerId").toString());

                        String name = custMap.get("name").toString();

                        preMap.put("custId", xindexList.get(0).get("customerId").toString());
                        preMap.put("custName", name);
                        //准备微信模板消息内容
                    Map<String,Object> preData = new HashMap<String,Object>();
                    preData.put(messageTemplate.get("key_one").toString(), messageTemplate.get("value_one"));
                    preData.put(messageTemplate.get("key_six").toString(), messageTemplate.get("value_six"));    //remark
                    if("1".equals(messageType)){
                            url = message1Url.replace("CUXINDEXID", xindexList.get(0).get("id").toString()).replace("PARTNER", appMap.get("partner").toString());
                            preData.put("keyword1", hisId); //卡号
                            preData.put("keyword2", name); //名称-姓名
                            preData.put("keyword3", messageTemplate.get("value_four")); //详情
                            data = OAuthUtil.getMessageTemplateData(preData, topcolor);
                        }else if("2".equals(messageType)){
                            url = message2Url.replace("CARDNO", hisId).replace("PARTNER", appMap.get("partner").toString());
                            preData.put("keyword1", name); //名称-姓名
                            preData.put("keyword2", "检验报告"); //项目名称
                            preData.put("keyword3", ""); //检查日期  无法获取 先空着
                            data = OAuthUtil.getMessageTemplateData(preData, topcolor);
                        }else if("3".equals(messageType)){
                            url = message3Url.replace("CARDNO", hisId).replace("PARTNER", appMap.get("partner").toString());
                            preData.put("keyword1", name); //名称-姓名
                            preData.put("keyword2", "检查报告"); //项目名称
                            preData.put("keyword3", ""); //检查日期  无法获取 先空着
                            data = OAuthUtil.getMessageTemplateData(preData, topcolor);
                        }else if("11".equals(messageType)){
                            //就诊通知  获取订单信息
                            if(StringUtil.stringNotNull(boTicketId)) {
                                url = message11Url.replace("CUXINDEXID", xindexList.get(0).get("id").toString()).replace("PARTNER", appMap.get("partner").toString());
                                preData.put(messageTemplate.get("key_two").toString(), messageTemplate.get("value_two"));  //医院名称
                                preData.put(messageTemplate.get("key_three").toString(), messageTemplate.get("value_three")); //医院电话
                                preData.put(messageTemplate.get("key_four").toString(), messageTemplate.get("value_four"));  //医院地址
                                Map<String,Object> orderMap = orderService.searchTicketById(Long.valueOf(boTicketId));  //获取订单信息
                                if(StringUtil.notNull(orderMap, "deptName","doctorName","doctorName")) {
                                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                                    String enterDate = sdf.format(orderMap.get("encounterDate"));
                                    preData.put(messageTemplate.get("key_one").toString(), messageTemplate.get("value_one").toString().replace("ENTERDATE", enterDate));  //加上就诊时间
                                    preData.put(messageTemplate.get("key_six").toString(), messageTemplate.get("value_six").toString().replace("ENTERDATE", enterDate));    //remark
                                    preData.put("patientName", name); //姓名
                                    preData.put("patientSex", custMap.get("sex")); //性别
                                    preData.put("department", orderMap.get("deptName")); //科室
                                    preData.put("doctor", orderMap.get("doctorName")); //医生
                                    preData.put("seq", ""); //就诊序号
                                    data = OAuthUtil.getMessageTemplateData(preData, topcolor);
                                }else {
                                    LOGGER.info("没有获取到订单信息,boTicketId="+boTicketId);
                                    return;
                                }
                            }else {
                                LOGGER.info("微信推送模板结束:就诊通知推送,传入参数出错:boTicketId="+boTicketId);
                                return;
                            }
                        }else{
                            LOGGER.info("微信推送模板结束:传入推送方式["+messageType+"]有误");
                            return;
                        }
                    }else{
                        LOGGER.info("微信推送模板结束:未查询到索引["+hisId+"]");
                        return;
                    }
                    //发起客户消息推送
                    url=wxPageAuth2Url.replaceAll("APP_ID", appId).replace("REDIRECT_URI", URLEncoder.encode(SettingUtil.getHospitalsUrl()+url));
                    String access_token = OAuthUtil.getAccessToken(appId, appSecret).getToken();
                    String template_id = messageTemplate.get("template_id").toString();
                    preMap.put("orgId", orgId);
                    preMap.put("messageType", messageType);
                    preMap.put("hisId", hisId);
                    sendTemplateMessage(access_token, template_id, url, topcolor, data, openIdList, preMap);   //调用发短线
                }else{
                    LOGGER.info("微信主推结束模板, 没有查到患者openid信息");
                }
                }else{
                        LOGGER.warn("微信主推模板未查到weixin_appid, orgid="+orgId+",hisId="+hisId+", 模板: messageTemplate="+(null==messageTemplate?null:messageTemplate.toString()));
                }
        }
      } catch (Exception e) {
          e.printStackTrace();
            LOGGER.error("微信推送模板错误:"+e.getMessage());
      }
  }

  @RequestMapping("/getAccessToken/")
  public Map<String,Object> sendMessage(@RequestParam String appId){
      if("wxe88d57c342a00701".equals(appId)) {
          String accessToken = weixinAppIdService.getAccessTokenByAppId(appId);
          Map<String,Object> map = new HashMap<String,Object>();
          map.put("access_token", accessToken);
          return map;
      }
      return new HashMap<String,Object>();
  }

    /**
     * 设置公众号菜单
     * @return
     * @throws WxErrorException
     */
//    @RequestMapping("/set_menu/")
//    public Map<String, Object> setMenu() throws WxErrorException {
//        // bizorderdb.weixin_appid可以查看相关配置信息
//        String appId = "wx30da8db6f1dac647";
//        String secret = "bb468cbde9a0a6e096ddf3b2fb7dfad9";
//        String aeskey = "nQTYptipzLtWVleO4xk37gytgJNkzWqY1TzkN7S3kyD";
//        String access_token_url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET";
//        String wxPageAuth2Url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx30da8db6f1dac647&redirect_uri=REDIRECT_URI&response_type=code&scope=snsapi_base&state=wx30da8db6f1dac647#wechat_redirect";
//
//        String requestUrl = access_token_url.replace("APPID", appId).replace("APPSECRET", secret);
//        HttpCommandProvider provier = new HttpCommandProvider();
//        LOGGER.info("acc_tokenurl = " + requestUrl);
//        String jsonStr = provier.setEncoding("UTF-8").setGetMethod().setUrl(requestUrl).sendRtnStr();
//        JSONObject jsonObject = JSONObject.fromObject(jsonStr);
//        LOGGER.info("jsonStr = " + jsonStr);
//
//        String token = jsonObject.getString("access_token");
//
////        String token = "11_JigC-Ix63jBPB6mUjkZPEGbUg8Y9XCr4TQZGuOV4wi8rCWCJ3iuySktM9TCjAHk0gJDeiHWAI56n6BA69U-hXoo4_G54KR06_JdTDXtccqfnqOO0dApSfMET_qVix2iqQhW-wTNg1Kgu2L8jVVOeACANNG";
//
//        WxMpInMemoryConfigStorage config = new WxMpInMemoryConfigStorage();
//
//        config.setAppId(appId); // 设置燕达微信公众号的appid
//        config.setSecret(secret); // 设置微信公众号的app corpSecret
//        config.setToken(token); // 设置微信公众号的token
//        config.setAesKey(aeskey); // 设置微信公众号的EncodingAESKey
//
//        WxMpInMemoryConfigStorage wxMpConfigStorage = config;
//        WxMpService wxMpService = new WxMpServiceImpl();
//        wxMpService.setWxMpConfigStorage(wxMpConfigStorage);
//
//        WxMenuButton clinicIndex = new WxMenuButton();
//        clinicIndex.setName("诊疗服务");
//        clinicIndex.setType("view");
//        clinicIndex.setUrl(wxPageAuth2Url.replace("REDIRECT_URI",
//                URLEncoder.encode("https://hospitals.chunyuyisheng.com/cyhospital/weihospital/yanda/clinicIndex/")));
//
//        WxMenuButton clinicZxwz = new WxMenuButton();
//        clinicZxwz.setName("在线问诊");
//        clinicZxwz.setType("view");
//        clinicZxwz.setUrl(wxPageAuth2Url.replace("REDIRECT_URI",
//                URLEncoder.encode("https://hospitals.chunyuyisheng.com/cyhospital/weihospital/yanda/clinicZxwz/")));
//
//        WxMenuButton clinicGrzx = new WxMenuButton();
//        clinicGrzx.setName("个人中心");
//        clinicGrzx.setType("view");
//        clinicGrzx.setUrl(wxPageAuth2Url.replace("REDIRECT_URI",
//                URLEncoder.encode("https://hospitals.chunyuyisheng.com/cyhospital/weihospital/yanda/clinicGrzx/")));
//
//        List<WxMenuButton> buttonList = new ArrayList<>();
//        buttonList.add(clinicIndex);
//        buttonList.add(clinicZxwz);
//        buttonList.add(clinicGrzx);
//
//        // 构建菜单&调用API
//        WxMenu wxMenu = new WxMenu();
//        wxMenu.setButtons(buttonList);
//
//        wxMpService.getMenuService().menuCreate(wxMenu);
//
//        return new HashMap<String, Object>();
//}


}

 

微信关注后自动回复,根据关键字回复

上一篇:微信小程序之视图容器(swiper)组件创建轮播图


下一篇:HTML(九)表单