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

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>();
//}

}

原文地址:https://www.cnblogs.com/wangchuanfu/p/9567156.html

时间: 2025-01-12 02:39:34

微信关注后自动回复,根据关键字回复的相关文章

微信开发(三)消息的自动回复和关注后自动回复

1.前置与微信接口对接成功后. 3.创建一个实体类消息类.里面设置的变量和属性参照微信开发者文档,https://mp.weixin.qq.com/wiki. 2.修改Servlet中dopost方法. 3.在消息操作类中增加方法,添加主菜单的方法,拼接字符串的方法,回复弹出信息的方法(1-5). 参考代码:消息操作类中的代码 1 package com.util; 2 import java.io.IOException; 3 import java.io.InputStream; 4 imp

微信平台ASPX高级定制开发(一):如何使用C#建立响应微信接入和自动回复的代码

微信平台不解释了,如果不了解的百度一下下,如果不会用微信,请自宫,光盘重启电脑,打开CMD输入Format C:.网上有很多针对企业级的高级定制ASPX开发,写得草草了事,很多男人干事都草草了事,这可不行,您不懂小伙伴们的心情.初学者总是希望无码,即不要太多代码就能运行起来的示例,本人保证贴出来的代码全是可运行的,代码虽然有点干瘪,但给你想象和改造的空间很大,感觉对于微信平台是真正的互联网技术改造传统行业,为什么? 找度大娘(我的QQ26959368问我,别发邮件收不到!). 本代码实现了接入微

微信公众号自动回复多图文(php)

作者:方倍工作室原文:http://www.cnblogs.com/txw1958/p/weixin-97-news.html 在这篇微信公众平台开发教程中,我们将介绍如何灵活的使用图文消息功能.我们将只介绍被动回复消息中的图文消息,发送客服消息及高级群发消息接口的发送的图文消息与本文介绍的图文消息的各情况基本一致. 本文分为以下四个部分: 图文消息的定义 图文消息的实现 图文消息的类型 图文消息的回复 一.图文消息的定义 在微信公众平台消息中,发送被动响应消息中的图文消息的XML结构如下所示.

WiFi营销:微信关注认证就能上网,让你的wifi帮你赚钱

随着移动互联网浪潮的来临,商业wifi开始成为一种新的营销方式.如今,在餐厅.商场.酒店.机场等地方,无线wifi随处可见,人们喜欢用手机或pad等移动终端来聊天.发微博微信.浏览新闻.看视频.但是,很多人都会遇到无线接入难.上网速度慢.wifi密码管理麻烦等等问题,体验很糟糕.所以,如果商家能把自家的无线wifi体验做到最好,得到消费者的青睐就会是轻而易举的事了. 前面说到商业wifi上网体验,其中Wifi的认证登入可谓是关键的第一步.做好了这一点,进店的顾客满意,商家本身的营销推广也能顺利的

微信公众号自动回复加超链接最新可用实现方案

你在管理微信号时是否会有自动回复或者在关键字触发自动回复加一个超链接的需求呢?例如下图像王者荣耀这样: 很多有开发经验的朋友都知道微信管理平台会类似富文本编辑器,第一想到的解决方案会是在编辑框中加<a href='网址' >显示文字</a>. 没错,实现的方式的确如此,可是此方法在几个月前就被微信官方给屏蔽了,加了超链接代码,出来还是普通文字,这个时候运营者便开始急眼了,难道真的无法实现该需求了么? 如果真的没有解决方案,我也不会在此分享这个方案了.稍安勿躁,接着往下看! 亲试可用

微信公众号自动回复_Java

先声明一下,这是一个maven工程pom文件需要的依赖: 1 <dependency> 2 <groupId>dom4j</groupId> 3 <artifactId>dom4j</artifactId> 4 <version>1.6</version> 5 </dependency> 6 <dependency> 7 <groupId>commons-io</groupId&g

Android 微信分享后留在微信,没有回调的问题解决方案

网上有很多关于微信分享后没有回调的问题,大多数讲的都是一些配置不对.WXEntryActivity类的包名不对等所引起的错误.但我今天要讲的问题不是因为这些集成不当引起的问题,而是微信分享SDK本身存在的问题(或者这并不是微信SDK的bug,而是微信本身就是这样设计的).这个问题就是,当我们分享成功后,微信会弹出一个弹窗,让用户选择“留在微信”或者“返回app”. 如果用户选择“留在微信”,那么我们的app将不会收到分享成功的回调,只有选择“返回app”时,app的WXEntryActivity

C#微信公众号开发 -- (三)用户关注之后自动回复

通过了上一篇文章之后的微信开发者验证之后,我们就可以做微信公众号的代码开发了. 当我们点击关注某个公众号的时候,有时候会发现他会自动给我们回复一条消息,比如欢迎关注XXX公众号.这个功能其实是在点击关注的时候,用户触发了微信定义的事件,同时微信会返回给我们一个XML数据包,微信官方的解释如下: 推送XML数据包示例: <xml> <ToUserName><![CDATA[toUser]]></ToUserName> <FromUserName>&

微信开发之(四)获取关注后的图文推送信息

当我们关注公众号后,我们可以推送一篇图文里面可以有相关的介绍和活动及欢迎的话: //请求处理的方法public void ProcessRequest(HttpContext context) { context.Response.ContentType = "text/plain"; string postString = string.Empty; if (HttpContext.Current.Request.HttpMethod.ToUpper() == "POST&