微信關注后自動回復,根據關鍵字回復


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


}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM