Browse Source

Merge branch 'dev' of trick9191/jw2.0 into dev

trick9191 6 years ago
parent
commit
bf7c38de19

+ 1 - 1
common/common-entity/src/main/java/com/yihu/jw/entity/base/wx/WechatTemplateDO.java

@ -17,7 +17,7 @@ public class WechatTemplateDO implements Serializable {
    private String url;//URL置空,则在发送后,点击模板消息会进入一个空白页面(ios),或无法点击(android)
    private Miniprogram miniprogram;
    private Miniprogram miniprogram; //小程序跳转
    private Map<String,WechatTemplateDataDO> data;//详细内容

+ 113 - 0
common/common-entity/src/main/java/com/yihu/jw/entity/base/wx/WxPushLogDO.java

@ -0,0 +1,113 @@
package com.yihu.jw.entity.base.wx;
import com.yihu.jw.entity.UuidIdentityEntity;
import javax.persistence.Column;
import java.util.Date;
/**
 * Created by Trick on 2018/8/21.
 */
public class WxPushLogDO extends UuidIdentityEntity {
    private String wechatId;//推送类型
    private String tempName;//模板名称
    private String scene;//场景值
    private String openid;//接收者openid
    private String receiver;//接收者code
    private String receiverName;//接收者姓名
    private String request;//请求入参
    private String response;//返回值
    private String status;//状态(0失败,1成功)
    private Date createTime;//创建时间
    @Column(name = "wechat_id")
    public String getWechatId() {
        return wechatId;
    }
    public void setWechatId(String wechatId) {
        this.wechatId = wechatId;
    }
    @Column(name = "temp_name")
    public String getTempName() {
        return tempName;
    }
    public void setTempName(String tempName) {
        this.tempName = tempName;
    }
    @Column(name = "scene")
    public String getScene() {
        return scene;
    }
    public void setScene(String scene) {
        this.scene = scene;
    }
    @Column(name = "openid")
    public String getOpenid() {
        return openid;
    }
    public void setOpenid(String openid) {
        this.openid = openid;
    }
    @Column(name = "receiver")
    public String getReceiver() {
        return receiver;
    }
    public void setReceiver(String receiver) {
        this.receiver = receiver;
    }
    @Column(name = "receiver_name")
    public String getReceiverName() {
        return receiverName;
    }
    public void setReceiverName(String receiverName) {
        this.receiverName = receiverName;
    }
    @Column(name = "request")
    public String getRequest() {
        return request;
    }
    public void setRequest(String request) {
        this.request = request;
    }
    @Column(name = "response")
    public String getResponse() {
        return response;
    }
    public void setResponse(String response) {
        this.response = response;
    }
    @Column(name = "status")
    public String getStatus() {
        return status;
    }
    public void setStatus(String status) {
        this.status = status;
    }
    @Column(name = "create_time")
    public Date getCreateTime() {
        return createTime;
    }
    public void setCreateTime(Date createTime) {
        this.createTime = createTime;
    }
}

+ 188 - 0
common/common-entity/src/main/java/com/yihu/jw/entity/base/wx/WxTemplateConfigDO.java

@ -0,0 +1,188 @@
package com.yihu.jw.entity.base.wx;
import com.yihu.jw.entity.UuidIdentityEntityWithOperator;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Table;
/**
 * Created by Trick on 2018/8/21.
 */
@Entity
@Table(name = "wx_template_config")
public class WxTemplateConfigDO extends UuidIdentityEntityWithOperator implements java.io.Serializable{
    private String wechatId;//微信id
    private String templateId;//微信模板id
    private String templateName;//自定义模板名称
    private String scene;//使用场景值
    private String sceneDescription;//使用场景描述
    private String first;//头部,
    private String url;//跳转链接
    private String remark;//备注
    private String keyword1;//项目
    private String keyword2;//项目
    private String keyword3;//项目
    private String keyword4;//项目
    private String keyword5;//项目
    private String keyword6;//项目
    private String keyword7;//项目
    private String appid;//跳转小程序的appid
    private String pagepath;//跳转小程序路径
    @Column(name = "wechat_id")
    public String getWechatId() {
        return wechatId;
    }
    public void setWechatId(String wechatId) {
        this.wechatId = wechatId;
    }
    @Column(name = "template_id")
    public String getTemplateId() {
        return templateId;
    }
    public void setTemplateId(String templateId) {
        this.templateId = templateId;
    }
    @Column(name = "template_name")
    public String getTemplateName() {
        return templateName;
    }
    public void setTemplateName(String templateName) {
        this.templateName = templateName;
    }
    @Column(name = "scene")
    public String getScene() {
        return scene;
    }
    public void setScene(String scene) {
        this.scene = scene;
    }
    @Column(name = "scene_description")
    public String getSceneDescription() {
        return sceneDescription;
    }
    public void setSceneDescription(String sceneDescription) {
        this.sceneDescription = sceneDescription;
    }
    @Column(name = "first")
    public String getFirst() {
        return first;
    }
    public void setFirst(String first) {
        this.first = first;
    }
    @Column(name = "url")
    public String getUrl() {
        return url;
    }
    public void setUrl(String url) {
        this.url = url;
    }
    @Column(name = "remark")
    public String getRemark() {
        return remark;
    }
    public void setRemark(String remark) {
        this.remark = remark;
    }
    @Column(name = "keyword1")
    public String getKeyword1() {
        return keyword1;
    }
    public void setKeyword1(String keyword1) {
        this.keyword1 = keyword1;
    }
    @Column(name = "keyword2")
    public String getKeyword2() {
        return keyword2;
    }
    public void setKeyword2(String keyword2) {
        this.keyword2 = keyword2;
    }
    @Column(name = "keyword3")
    public String getKeyword3() {
        return keyword3;
    }
    public void setKeyword3(String keyword3) {
        this.keyword3 = keyword3;
    }
    @Column(name = "keyword4")
    public String getKeyword4() {
        return keyword4;
    }
    public void setKeyword4(String keyword4) {
        this.keyword4 = keyword4;
    }
    @Column(name = "keyword5")
    public String getKeyword5() {
        return keyword5;
    }
    public void setKeyword5(String keyword5) {
        this.keyword5 = keyword5;
    }
    @Column(name = "keyword6")
    public String getKeyword6() {
        return keyword6;
    }
    public void setKeyword6(String keyword6) {
        this.keyword6 = keyword6;
    }
    @Column(name = "keyword7")
    public String getKeyword7() {
        return keyword7;
    }
    public void setKeyword7(String keyword7) {
        this.keyword7 = keyword7;
    }
    @Column(name = "appid")
    public String getAppid() {
        return appid;
    }
    public void setAppid(String appid) {
        this.appid = appid;
    }
    @Column(name = "pagepath")
    public String getPagepath() {
        return pagepath;
    }
    public void setPagepath(String pagepath) {
        this.pagepath = pagepath;
    }
}

+ 8 - 8
common/common-fegin/pom.xml

@ -99,15 +99,15 @@
            <artifactId>spring-cloud-starter-config</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-feign</artifactId>
        </dependency>
        <!--<dependency>-->
            <!--<groupId>org.springframework.cloud</groupId>-->
            <!--<artifactId>spring-cloud-starter-feign</artifactId>-->
        <!--</dependency>-->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-hystrix</artifactId>
        </dependency>
        <!--<dependency>-->
            <!--<groupId>org.springframework.cloud</groupId>-->
            <!--<artifactId>spring-cloud-starter-hystrix</artifactId>-->
        <!--</dependency>-->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-zuul</artifactId>

+ 1 - 0
common/common-request-mapping/src/main/java/com/yihu/jw/rm/base/WechatRequestMapping.java

@ -66,6 +66,7 @@ public class WechatRequestMapping {
        public static final String api_getWxTemplates="/template/list";
        public static final String api_getById="/template/{id}";
        public static final String api_sendTemplateMessage="/sendTemplateMessage";
        public static final String api_test_template="/test_template";
        public static final String message_success_create="wxTemplate create success";
        public static final String message_success_update="wxTemplate update success";

+ 12 - 0
common/common-util/pom.xml

@ -37,5 +37,17 @@
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-api</artifactId>
        </dependency>
        <dependency>
            <groupId>com.yihu.jw</groupId>
            <artifactId>common-util</artifactId>
        </dependency>
        <dependency>
            <groupId>com.yihu.jw</groupId>
            <artifactId>common-entity</artifactId>
        </dependency>
        <dependency>
            <groupId>com.yihu</groupId>
            <artifactId>utils</artifactId> <!-- 此依赖包含大部分常用工具类 -->
        </dependency>
    </dependencies>
</project>

+ 0 - 23
common/common-util/src/main/java/com/yihu/jw/util/wechat/PushMsgTask.java

@ -1,23 +0,0 @@
package com.yihu.jw.util.wechat;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import java.util.concurrent.LinkedBlockingQueue;
/**
 * Created by Trick on 2018/8/20.
 */
@Component
public class PushMsgTask {
    private static Logger logger = LoggerFactory.getLogger(PushMsgTask.class);
    private static LinkedBlockingQueue<JSONObject> queue = new LinkedBlockingQueue<JSONObject>();
}

+ 223 - 0
common/common-util/src/main/java/com/yihu/jw/util/wechat/WeixinMessagePushUtils.java

@ -0,0 +1,223 @@
package com.yihu.jw.util.wechat;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.yihu.jw.entity.base.wx.*;
import com.yihu.jw.util.wechat.wxhttp.HttpUtil;
import com.yihu.utils.network.HttpUtils;
import org.apache.commons.collections.map.HashedMap;
import org.apache.commons.lang3.StringUtils;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import javax.annotation.PostConstruct;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.LinkedBlockingQueue;
/**
 * 微信模板消息工具类
 * 调用putWxMsg 发送模板消息
 * 微信文档地址
 * https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1445241432
 * Created by Trick on 2018/8/21.
 */
@Component
public class WeixinMessagePushUtils {
    private static Logger logger = LoggerFactory.getLogger(WeixinMessagePushUtils.class);
    private static LinkedBlockingQueue<Map<String,Object>> queue = new LinkedBlockingQueue<Map<String,Object>>();
    public void putWxMsg(String accessToken,String opennid,WxTemplateConfigDO wxTemplateConfigDO){
        try {
            Map<String,Object> mes = new HashMap();
            if(StringUtils.isBlank(opennid)){
                logger.info("wechat queue put opennid is null ");
                return;
            }
            if(StringUtils.isBlank(accessToken)){
                logger.info("wechat queue put accessToken is null ");
                return;
            }
            mes.put("accessToken",accessToken);
            mes.put("openid",opennid);
            mes.put("wxTemplateConfig",wxTemplateConfigDO);
            queue.put(mes);
        }catch (Exception e){
            logger.info("wechat queue put error :",e);
        }
    }
    @PostConstruct
    private void run() {
        new Thread(new ConsumerTask()).start();
    }
    // 消费者
    class ConsumerTask implements Runnable {
        @Override
        public void run() {
            while (true) {
                try {
                    // 如果queue为空,则当前线程会堵塞,直到有新数据加入
                    Map<String,Object> mes = queue.take();
                    //发送微信模板消息
                    sendWeixinMessage(mes);
                }catch (Exception e){
                    logger.info("wechat ConsumerTask run:",e);
                }
            }
        }
    }
    /**
     * 发送微信模板消息
     * @param mes
     * @return
     */
    public boolean sendWeixinMessage(Map<String,Object> mes){
        WxTemplateConfigDO wxtemp = (WxTemplateConfigDO)mes.get("wxTemplateConfig");
        String token = (String)mes.get("accessToken");
        //发送微信模板地址
        String url = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token="+token;
        //微信消息参数
        String params = getWxParam(mes);
        if(StringUtils.isBlank(params)){
            logger.info("wechat params is null");
            return false;
        }
        //发送微信模板消息
        String result = HttpUtil.sendPost(url, params);
        JSONObject jsonResult = new JSONObject(result);
        if (Integer.parseInt(jsonResult.get("errcode").toString()) == 0) {
            logger.info("wechat temp send success");
            return true;
        } else {
            logger.error("wechat temp send fail:"+result);
            return false;
        }
    }
    /**
     * 构造微信模板参数
     *
     * @param mes
     * @return
     */
    public String getWxParam(Map<String,Object> mes){
        try{
            String toUser = (String)mes.get("openid");
            //微信模板消息实体
            WxTemplateConfigDO wxtemp = (WxTemplateConfigDO)mes.get("wxTemplateConfig");
            //创建微信模板实体,设置参数及内容
            WechatTemplateDO wechatTemp = new WechatTemplateDO();
            //接收者的openid
            wechatTemp.setTouser(toUser);
            //设置模板ID
            wechatTemp.setTemplate_id(wxtemp.getTemplateId());
            //设置跳转路径
            if(StringUtils.isNotBlank(wxtemp.getUrl())){
                wechatTemp.setUrl(wxtemp.getUrl());
            }
            //设置小程序跳转
            if(StringUtils.isNotBlank(wxtemp.getAppid())){
                Miniprogram miniprogram = new Miniprogram();
                miniprogram.setAppid(wxtemp.getAppid());
                miniprogram.setPagepath(wxtemp.getPagepath());
                wechatTemp.setMiniprogram(miniprogram);
            }
            //配置微信模板内容
            setWechatTemplateData(wechatTemp,wxtemp);
            ObjectMapper mapper = new ObjectMapper();
            String strJson = mapper.writeValueAsString(wechatTemp);
            logger.info("--------wechat param json message --------:" + strJson);
            return strJson;
        }catch (Exception e){
            logger.info("--------wechat param json message --------:" + e);
        }
        return "";
    }
    /**
     * 设置微信模板内容
     * @param wechatTemp 微信待发送模板
     * @param wxtemp 读取数据配置
     */
    public void setWechatTemplateData(WechatTemplateDO wechatTemp,WxTemplateConfigDO wxtemp){
        //设置模板内容
        Map<String,WechatTemplateDataDO> data = new HashedMap();
        //设置头部
        WechatTemplateDataDO first = new WechatTemplateDataDO();
        first.setValue(wxtemp.getFirst());
        first.setColor("#000000");
        data.put("first",first);
        //设置备注
        WechatTemplateDataDO remark = new WechatTemplateDataDO();
        remark.setValue(wxtemp.getRemark());
        remark.setColor("#000000");
        data.put("remark",remark);
        //配置keyword,微信最多可配置7个项目
        //设置keyword1
        if(StringUtils.isNotBlank(wxtemp.getKeyword1())){
            WechatTemplateDataDO keyword1 = new WechatTemplateDataDO();
            keyword1.setValue(wxtemp.getRemark());
            keyword1.setColor("#000000");
            data.put("keyword1",keyword1);
        }
        //设置keyword2
        if(StringUtils.isNotBlank(wxtemp.getKeyword2())){
            WechatTemplateDataDO keyword2 = new WechatTemplateDataDO();
            keyword2.setValue(wxtemp.getKeyword2());
            keyword2.setColor("#000000");
            data.put("keyword2",keyword2);
        }
        //设置keyword3
        if(StringUtils.isNotBlank(wxtemp.getKeyword3())){
            WechatTemplateDataDO keyword3 = new WechatTemplateDataDO();
            keyword3.setValue(wxtemp.getKeyword3());
            keyword3.setColor("#000000");
            data.put("keyword3",keyword3);
        }
        //设置keyword4
        if(StringUtils.isNotBlank(wxtemp.getKeyword4())){
            WechatTemplateDataDO keyword4 = new WechatTemplateDataDO();
            keyword4.setValue(wxtemp.getKeyword4());
            keyword4.setColor("#000000");
            data.put("keyword4",keyword4);
        }
        //设置keyword5
        if(StringUtils.isNotBlank(wxtemp.getKeyword5())){
            WechatTemplateDataDO keyword5 = new WechatTemplateDataDO();
            keyword5.setValue(wxtemp.getKeyword5());
            keyword5.setColor("#000000");
            data.put("keyword5",keyword5);
        }
        //设置keyword6
        if(StringUtils.isNotBlank(wxtemp.getKeyword6())){
            WechatTemplateDataDO keyword6 = new WechatTemplateDataDO();
            keyword6.setValue(wxtemp.getKeyword6());
            keyword6.setColor("#000000");
            data.put("keyword1",keyword6);
        }
        //设置keyword7
        if(StringUtils.isNotBlank(wxtemp.getKeyword7())){
            WechatTemplateDataDO keyword7 = new WechatTemplateDataDO();
            keyword7.setValue(wxtemp.getKeyword7());
            keyword7.setColor("#000000");
            data.put("keyword7",keyword7);
        }
        //设置微信内容,头部,备注,项目参数
        wechatTemp.setData(data);
    }
}

+ 171 - 0
common/common-util/src/main/java/com/yihu/jw/util/wechat/wxhttp/HttpUtil.java

@ -0,0 +1,171 @@
package com.yihu.jw.util.wechat.wxhttp;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
/**
 * Created by Trick on 2018/8/21.
 */
public class HttpUtil {
    private static final Logger logger = LoggerFactory.getLogger(HttpUtil.class);
    /**
     * 向指定URL发送GET方法的请求
     *
     * @param url
     *            发送请求的URL
     * @param param
     *            请求参数,请求参数应该是 name1=value1&name2=value2 的形式。
     * @return URL 所代表远程资源的响应结果
     */
    public static String sendGet(String url, String param) {
        String result = "";
        BufferedReader in = null;
        try {
            String urlNameString = url + "?" + param;
            URL realUrl = new URL(urlNameString);
            // 打开和URL之间的连接
            URLConnection connection = realUrl.openConnection();
            // 设置通用的请求属性
            connection.setRequestProperty("accept", "*/*");
            connection.setRequestProperty("connection", "Keep-Alive");
            connection.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            // 建立实际的连接
            connection.connect();
            // 定义 BufferedReader输入流来读取URL的响应
            in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (in != null) {
                    in.close();
                }
            } catch (Exception e2) {
                e2.printStackTrace();
            }
        }
        return result;
    }
    /**
     * 向指定 URL 发送POST方法的请求
     *
     * @param url
     *            发送请求的 URL带上参数
     * @param param
     *            POST参数。
     * @return 所代表远程资源的响应结果
     */
    public static String sendPost(String url, String param) {
        StringBuffer buffer = new StringBuffer();
        PrintWriter out = null;
        BufferedReader in = null;
        HttpURLConnection conn = null;
        try {
            URL realUrl = new URL(url);
            // 打开和URL之间的连接
            conn = (HttpURLConnection) realUrl.openConnection();
            conn.setRequestMethod("POST");
            conn.setConnectTimeout(5000);
            conn.setDoOutput(true);
            conn.setDoInput(true);
            conn.setUseCaches(false);
            conn.setRequestProperty("Content-Type", "application/text");
            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            OutputStreamWriter osw = new OutputStreamWriter(conn.getOutputStream(), "UTF-8");
            osw.write(param.toString());
            osw.flush();
            // 读取返回内容
            BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
            String temp;
            while ((temp = br.readLine()) != null) {
                buffer.append(temp);
                buffer.append("\n");
            }
        } catch (Exception e) {
            logger.error("push message error:", e);
        } finally {
            try {
                if (out != null) {
                    out.close();
                }
                if (in != null) {
                    in.close();
                }
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
        return buffer.toString();
    }
    /**
     * 向指定 URL 发送POST方法的请求
     *
     * @param url 发送请求的 URL带上参数
     * @param param POST参数。
     * @param charset 编码格式
     * @return 所代表远程资源的响应结果
     */
    public static String sendPost(String url, String param, String charset) {
        StringBuffer buffer = new StringBuffer();
        PrintWriter out = null;
        BufferedReader in = null;
        HttpURLConnection conn = null;
        try {
            URL realUrl = new URL(url);
            // 打开和URL之间的连接
            conn = (HttpURLConnection) realUrl.openConnection();
            conn.setRequestMethod("POST");
            conn.setDoOutput(true);
            conn.setDoInput(true);
            conn.setUseCaches(false);
            conn.setRequestProperty("Content-Type", "application/text");
            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            OutputStreamWriter osw = new OutputStreamWriter(conn.getOutputStream(), charset);
            osw.write(param.toString());
            osw.flush();
            // 读取返回内容
            BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream(), charset));
            String temp;
            while ((temp = br.readLine()) != null) {
                buffer.append(temp);
                buffer.append("\n");
            }
        } catch (Exception e) {
            logger.error("push message error:", e);
        } finally {
            try {
                if (out != null) {
                    out.close();
                }
                if (in != null) {
                    in.close();
                }
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
        return buffer.toString();
    }
}

+ 5 - 5
svr/svr-base/src/main/java/com/yihu/jw/business/wx/controller/WechatCoreController.java

@ -174,9 +174,9 @@ public class WechatCoreController extends EnvelopRestEndpoint {
        return strDigest;
    }
//    @RequestMapping(value ="test", method = RequestMethod.POST)
//    @ResponseBody
//    public String  testProcess() throws Exception{
//        return wechatCoreService.testProcess();
//    }
    @RequestMapping(value ="test", method = RequestMethod.POST)
    @ResponseBody
    public String  testProcess() throws Exception{
        return wechatCoreService.testProcess();
    }
}

+ 32 - 42
svr/svr-base/src/main/java/com/yihu/jw/business/wx/controller/WxTemplateController.java

@ -1,44 +1,34 @@
//package com.yihu.jw.business.wx.controller;
//
//import com.yihu.jw.business.wx.WechatResponse;
//import com.yihu.jw.base.wx.Miniprogram;
//import com.yihu.jw.base.wx.WxTemplateDO;
//import com.yihu.jw.base.wx.WxWechatDO;
//import com.yihu.jw.business.wx.service.WechatService;
//import com.yihu.jw.business.wx.service.WxTemplateService;
//import com.yihu.jw.exception.ApiException;
//import com.yihu.jw.restmodel.common.Envelop;
//import com.yihu.jw.restmodel.common.EnvelopRestController;
//import com.yihu.jw.restmodel.base.wx.WxTemplateVO;
//import com.yihu.jw.restmodel.base.wx.WxWechatVO;
//import com.yihu.jw.rm.base.WechatRequestMapping;
//import io.swagger.annotations.Api;
//import io.swagger.annotations.ApiOperation;
//import io.swagger.annotations.ApiParam;
//import org.apache.commons.lang.StringUtils;
//import org.json.JSONObject;
//import org.springframework.beans.factory.annotation.Autowired;
//import org.springframework.http.MediaType;
//import org.springframework.web.bind.annotation.*;
//
//import javax.servlet.http.HttpServletRequest;
//import javax.servlet.http.HttpServletResponse;
//import java.util.ArrayList;
//import java.util.List;
//
///**
// * Created by Administrator on 2017/5/19 0019.
// */
//@RestController
//@RequestMapping(WechatRequestMapping.api_common)
//@Api(value = "微信模版相关操作", description = "微信模版相关操作")
//public class WxTemplateController extends EnvelopRestController {
//    @Autowired
//    private WxTemplateService wxTemplateService;
//
//    @Autowired
//    private WechatService wechatService;
//
package com.yihu.jw.business.wx.controller;
import com.yihu.jw.business.wx.service.WxTemplateService;
import com.yihu.jw.restmodel.web.endpoint.EnvelopRestEndpoint;
import com.yihu.jw.rm.base.WechatRequestMapping;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
/**
 * Created by Administrator on 2017/5/19 0019.
 */
@RestController
@RequestMapping(WechatRequestMapping.api_common)
@Api(value = "微信模版相关操作", description = "微信模版相关操作")
public class WxTemplateController extends EnvelopRestEndpoint {
    @Autowired
    private WxTemplateService wxTemplateService;
    @PostMapping(value = WechatRequestMapping.WxTemplate.api_test_template, consumes = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ApiOperation(value = "测试发送微信模板", notes = "测试发送微信模板")
    public String sendWeTempMesTest(String wechatId,String openid)throws Exception{
        return wxTemplateService.sendWeTempMesTest(wechatId,openid);
    }
//    @PostMapping(value = WechatRequestMapping.WxTemplate.api_create, consumes = MediaType.APPLICATION_JSON_UTF8_VALUE)
//    @ApiOperation(value = "创建微信模版", notes = "创建微信模版")
//    public Envelop createWxTemplate(
@ -185,4 +175,4 @@
//            return Envelop.getSuccess("error", exception);
//        }
//    }
//}
}

+ 15 - 0
svr/svr-base/src/main/java/com/yihu/jw/business/wx/dao/WxTemplateConfigDao.java

@ -0,0 +1,15 @@
package com.yihu.jw.business.wx.dao;
import com.yihu.jw.entity.base.wx.WxTemplateConfigDO;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.repository.PagingAndSortingRepository;
/**
 * Created by Trick on 2018/8/21.
 */
public interface WxTemplateConfigDao extends PagingAndSortingRepository<WxTemplateConfigDO, String>, JpaSpecificationExecutor<WxTemplateConfigDO> {
    WxTemplateConfigDO findByWechatIdAndTemplateNameAndScene(String wechatId,String templateName,String scene);
}

+ 47 - 6
svr/svr-base/src/main/java/com/yihu/jw/business/wx/service/WechatCoreService.java

@ -88,12 +88,11 @@ public class WechatCoreService {
        String returnStr = "";
        Map<String, String> message = new HashMap();
        message.put("Content","1");
        message.put("CreateTime","1534486843");
        message.put("Event","subscribe");
        message.put("CreateTime","1534495338");
        message.put("ToUserName","gh_73959f6e996b");
        message.put("FromUserName","oVH-2uJdhNrcAMt0Jhp3PMarDdaM");
        message.put("MsgType","text");
        message.put("MsgId","6590570807493983575");
        message.put("MsgType","event");
        returnStr = messageProcess(message);
@ -165,7 +164,30 @@ public class WechatCoreService {
        return result;
    }
    public String scanEventProcess(Map<String, String> message){
    /**
     * 扫描二维码事件
     * 1. 用户未关注时,进行关注后的事件推送
     * <xml><ToUserName>< ![CDATA[toUser] ]></ToUserName><FromUserName>< ![CDATA[FromUser] ]></FromUserName><CreateTime>123456789</CreateTime><MsgType>< ![CDATA[event] ]></MsgType><Event>< ![CDATA[subscribe] ]></Event><EventKey>< ![CDATA[qrscene_123123] ]></EventKey><Ticket>< ![CDATA[TICKET] ]></Ticket></xml>
     * 2. 用户已关注时的事件推送
     * <xml> <ToUserName>< ![CDATA[toUser] ]></ToUserName> <FromUserName>< ![CDATA[FromUser] ]></FromUserName> <CreateTime>123456789</CreateTime> <MsgType>< ![CDATA[event] ]></MsgType> <Event>< ![CDATA[SCAN] ]></Event> <EventKey>< ![CDATA[SCENE_VALUE] ]></EventKey> <Ticket>< ![CDATA[TICKET] ]></Ticket> </xml>
     * @param message
     * @return
     */
    public String scanEventProcess(Map<String, String> message) throws Exception{
        //获取原始id
        String toUserName = message.get("ToUserName");
        //如果为已经关注,EventKey值为带参二维码值,如果是未关注 qrscene_为前缀,后面为二维码的参数值
        String eventKey = message.get("EventKey");
        //查询需要对应匹配的带参二维码事件值
        List<WxReplySceneDO> scenes = wxReplySceneDao.findByAppOriginIdAndMsgTypeAndEventAndStatus(toUserName,WeiXinMessageUtils.REQ_MESSAGE_TYPE_EVENT,WeiXinMessageUtils.EVENT_TYPE_SCAN,1);
        if(scenes!=null&&scenes.size()>0){
            for(WxReplySceneDO scene:scenes){
                //判断带参二维码中前缀是否包该场景值
                if(StringUtils.isNotBlank(scene.getScene())&&eventKey.indexOf(scene.getScene())!=-1){
                    return getGraphicXMl(scene.getScene(),scene.getWechatId(),message);
                }
            }
        }
        return "";
    }
@ -176,8 +198,9 @@ public class WechatCoreService {
     * @return
     */
    public String subscribeEventProcess(Map<String, String> message) throws Exception{
        //获取原始id
        String toUserName = message.get("ToUserName");
        List<WxReplySceneDO> scenes = wxReplySceneDao.findByAppOriginIdAndMsgTypeAndEventAndStatus(toUserName,WeiXinMessageUtils.RESP_MESSAGE_TYPE_TEXT,WeiXinMessageUtils.EVENT_TYPE_SUBSCRIBE,1);
        List<WxReplySceneDO> scenes = wxReplySceneDao.findByAppOriginIdAndMsgTypeAndEventAndStatus(toUserName,WeiXinMessageUtils.REQ_MESSAGE_TYPE_EVENT,WeiXinMessageUtils.EVENT_TYPE_SUBSCRIBE,1);
        if(scenes!=null&&scenes.size()>0){
            WxReplySceneDO scene = scenes.get(0);
            if(StringUtils.isNotBlank(scene.getScene())){
@ -187,10 +210,20 @@ public class WechatCoreService {
        return "";
    }
    /**
     * 取消关注事件,根据需求开发
     * @param message
     * @return
     */
    public String unsubscribeEventProcess(Map<String, String> message){
        return "";
    }
    /**
     * 点击事件,根据需求开发
     * @param message
     * @return
     */
    public String clickProcess(Map<String, String> message){
        return "";
    }
@ -232,6 +265,7 @@ public class WechatCoreService {
    public String getGraphicXMl(String secene,String wxId,Map<String, String> message)throws Exception{
        List<Map<String,Object>> group = getGraphicGroupByScene(secene,wxId);
        String result = "";
        String eventKey = message.get("EventKey");
        if(group!=null&&group.size()>0){
            List<Map<String, String>> articles = new ArrayList<>();
@ -251,6 +285,13 @@ public class WechatCoreService {
                if(url.indexOf("{appId}")!=-1){
                    url = url.replace("{appId}",appId);
                }
                //传递带参二维码给前端页面
                if(url.indexOf("{EventKey}")!=-1){
                    if(eventKey.indexOf("qrscene_")!=-1){
                        eventKey = eventKey.replace("qrscene_","");
                    }
                    url = url.replace("{EventKey}",eventKey);
                }
                article.put("Url", url);
                article.put("Title", title);

+ 2 - 2
svr/svr-base/src/main/java/com/yihu/jw/business/wx/service/WxAccessTokenService.java

@ -74,7 +74,7 @@ public class WxAccessTokenService extends BaseJpaService<WxAccessTokenDO, WxAcce
            params.put("appid", appId);
            params.put("secret", appSecret);
            String result = HttpUtils.doGet(token_url, params).getContent();
            logger.info("--------------微信返回结果:"+result+"---------------");
            logger.info("--------------wechat token return :"+result+"---------------");
            JSONObject json = new JSONObject(result);
            if (json.has("access_token")) {
                String token = json.get("access_token").toString();
@ -132,7 +132,7 @@ public class WxAccessTokenService extends BaseJpaService<WxAccessTokenDO, WxAcce
            params.put("appid", appId);
            params.put("secret", appSecret);
            String result = HttpUtils.doGet(token_url, params).getContent();
            logger.info("--------------微信返回结果:"+result+"---------------");
            logger.info("--------------wechat token return:"+result+"---------------");
            JSONObject json = new JSONObject(result);
            if (json.has("access_token")) {
                String token = json.get("access_token").toString();

+ 37 - 38
svr/svr-base/src/main/java/com/yihu/jw/business/wx/service/WxTemplateService.java

@ -1,40 +1,39 @@
//package com.yihu.jw.business.wx.service;
//
//import com.fasterxml.jackson.core.type.TypeReference;
//import com.fasterxml.jackson.databind.ObjectMapper;
//import com.yihu.jw.base.wx.*;
//import com.yihu.jw.business.wx.dao.WxTemplateDao;
//import com.yihu.jw.exception.ApiException;
//import com.yihu.jw.exception.code.ExceptionCode;
//import com.yihu.base.mysql.query.BaseJpaService;
//import com.yihu.jw.rm.base.WechatRequestMapping;
//import com.yihu.jw.util.HttpUtil;
//import org.json.JSONObject;
//import org.slf4j.Logger;
//import org.slf4j.LoggerFactory;
//import org.springframework.beans.factory.annotation.Autowired;
//import org.springframework.stereotype.Service;
//import org.springframework.util.StringUtils;
//
//import java.util.*;
//
///**
// * Created by Administrator on 2017/5/19 0019.
// */
//@Service
//public class WxTemplateService extends BaseJpaService<WxTemplateDO, WxTemplateDao> {
//
//    private Logger logger= LoggerFactory.getLogger(WxTemplateService.class);
//
//    @Autowired
//    private WxTemplateDao wxTemplateDao;
//
//    @Autowired
//    private WxAccessTokenService wxAccessTokenService;
//
//    @Autowired
//    private WechatService wechatService;
//
package com.yihu.jw.business.wx.service;
import com.yihu.jw.business.wx.dao.WxTemplateConfigDao;
import com.yihu.jw.entity.base.wx.WxTemplateConfigDO;
import com.yihu.jw.util.wechat.WeixinMessagePushUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
/**
 * Created by Administrator on 2017/5/19 0019.
 */
@Service
public class WxTemplateService {
    private Logger logger= LoggerFactory.getLogger(WxTemplateService.class);
    @Autowired
    private WxTemplateConfigDao wxTemplateConfigDao;
    @Autowired
    private WxAccessTokenService wxAccessTokenService;
    @Autowired
    private WeixinMessagePushUtils weixinMessagePushUtils;
    public String sendWeTempMesTest(String wechatId,String openid)throws Exception{
        WxTemplateConfigDO config = wxTemplateConfigDao.findByWechatIdAndTemplateNameAndScene(wechatId,"template_survey","test");
        config.setFirst(config.getFirst().replace("key1","小明"));
        config.setKeyword2("2018-08-21");
        weixinMessagePushUtils.putWxMsg(wxAccessTokenService.getWxAccessTokenById(wechatId).getAccessToken(),openid,config);
        return "success";
    }
//    public WxTemplateDO createWxTemplate(WxTemplateDO wxTemplate) {
//        if (StringUtils.isEmpty(wxTemplate.getTemplateId())) {
//            throw new ApiException(WechatRequestMapping.WxTemplate.message_fail_templateid_is_null, ExceptionCode.common_error_params_code);
@ -154,4 +153,4 @@
//    public List<WxTemplateDO> findByWxId(String code) {
//        return wxTemplateDao.findByWxId(code);
//    }
//}
}

+ 1 - 1
svr/svr-base/src/main/resources/bootstrap.yml

@ -29,4 +29,4 @@ spring:
  cloud:
    config:
      uri: ${wlyy.pring.config.uri:http://172.17.110.212:1221}
      label: ${wlyy.spring.config.label:jwprod}
      label: ${wlyy.spring.config.label:jwprod}