Browse Source

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

chenweida 8 years ago
parent
commit
ef06932f1a
31 changed files with 1360 additions and 270 deletions
  1. 22 22
      common/common-rest-model/src/main/java/com/yihu/jw/restmodel/wx/MWxGraphicMessage.java
  2. 39 2
      common/common-rest-model/src/main/java/com/yihu/jw/restmodel/wx/MWxMenu.java
  3. 32 34
      common/common-rest-model/src/main/java/com/yihu/jw/restmodel/wx/MWxTemplate.java
  4. 0 9
      common/common-rest-model/src/main/java/com/yihu/jw/restmodel/wx/MWxWechat.java
  5. 17 22
      common/common-rest-model/src/main/java/com/yihu/jw/restmodel/wx/WxContants.java
  6. 27 11
      svr-lib-parent-pom/pom.xml
  7. 8 0
      svr/svr-base/pom.xml
  8. 115 0
      svr/svr-base/src/main/java/com/yihu/jw/util/HttpUtil.java
  9. 109 0
      svr/svr-base/src/main/java/com/yihu/jw/util/MessageUtil.java
  10. 4 17
      svr/svr-base/src/main/java/com/yihu/jw/wx/controller/WxAccessTokenController.java
  11. 26 1
      svr/svr-base/src/main/java/com/yihu/jw/wx/controller/WxGraphicMessageController.java
  12. 25 1
      svr/svr-base/src/main/java/com/yihu/jw/wx/controller/WxMenuController.java
  13. 30 1
      svr/svr-base/src/main/java/com/yihu/jw/wx/controller/WxTemplateController.java
  14. 26 1
      svr/svr-base/src/main/java/com/yihu/jw/wx/dao/WxMenuDao.java
  15. 30 0
      svr/svr-base/src/main/java/com/yihu/jw/wx/model/Miniprogram.java
  16. 58 0
      svr/svr-base/src/main/java/com/yihu/jw/wx/model/WechatTemplate.java
  17. 31 0
      svr/svr-base/src/main/java/com/yihu/jw/wx/model/WechatTemplateData.java
  18. 4 4
      svr/svr-base/src/main/java/com/yihu/jw/wx/model/WxAccessToken.java
  19. 35 34
      svr/svr-base/src/main/java/com/yihu/jw/wx/model/WxGraphicMessage.java
  20. 45 4
      svr/svr-base/src/main/java/com/yihu/jw/wx/model/WxMenu.java
  21. 45 46
      svr/svr-base/src/main/java/com/yihu/jw/wx/model/WxTemplate.java
  22. 1 12
      svr/svr-base/src/main/java/com/yihu/jw/wx/model/WxWechat.java
  23. 15 6
      svr/svr-base/src/main/java/com/yihu/jw/wx/service/WechatService.java
  24. 52 20
      svr/svr-base/src/main/java/com/yihu/jw/wx/service/WxAccessTokenService.java
  25. 107 4
      svr/svr-base/src/main/java/com/yihu/jw/wx/service/WxGraphicMessageService.java
  26. 167 15
      svr/svr-base/src/main/java/com/yihu/jw/wx/service/WxMenuService.java
  27. 78 4
      svr/svr-base/src/main/java/com/yihu/jw/wx/service/WxTemplateService.java
  28. 105 0
      web-gateway/src/main/java/com/yihu/jw/controller/base/wx/WechatController.java
  29. 37 0
      web-gateway/src/main/java/com/yihu/jw/fegin/base/wx/WechatFegin.java
  30. 22 0
      web-gateway/src/main/java/com/yihu/jw/fegin/fallback/base/wx/WechatFeginFallback.java
  31. 48 0
      web-gateway/src/main/java/com/yihu/jw/fegin/fallbackfactory/base/wx/WechatFeginFallbackFactory.java

+ 22 - 22
common/common-rest-model/src/main/java/com/yihu/jw/restmodel/wx/MWxGraphicMessage.java

@ -8,18 +8,18 @@ import java.util.Date;
public class MWxGraphicMessage {
    private Long id;
    private String code;//业务code
    private String wechatCode;//关联的微信code 关联表 Wx_Wechat
    private String name;//名称
    private String value;//图文消息url值
    private String keyword;//关键字
    private String title;//标题
    private String description;//描述
    private String url;//图文消息url值
    private String picUrl;//图片地址
    private String createUser;//创建人
    private String createUserName;//创建人名
    private Date createTime;//创建时间
    private String updateUser;//修改人
    private String updateUserName;//修改人名称
    private Date updateTime;//修改时间
    private String remark;
    private Integer status; //状态 -1 已删除 0可用
    private String remark;//备注
    private Integer status;  //状态 -1删除 0 冻结 1可用
    public Long getId() {
        return id;
@ -37,36 +37,36 @@ public class MWxGraphicMessage {
        this.code = code;
    }
    public String getWechatCode() {
        return wechatCode;
    public String getTitle() {
        return title;
    }
    public void setWechatCode(String wechatCode) {
        this.wechatCode = wechatCode;
    public void setTitle(String title) {
        this.title = title;
    }
    public String getName() {
        return name;
    public String getDescription() {
        return description;
    }
    public void setName(String name) {
        this.name = name;
    public void setDescription(String description) {
        this.description = description;
    }
    public String getValue() {
        return value;
    public String getUrl() {
        return url;
    }
    public void setValue(String value) {
        this.value = value;
    public void setUrl(String url) {
        this.url = url;
    }
    public String getKeyword() {
        return keyword;
    public String getPicUrl() {
        return picUrl;
    }
    public void setKeyword(String keyword) {
        this.keyword = keyword;
    public void setPicUrl(String picUrl) {
        this.picUrl = picUrl;
    }
    public String getCreateUser() {

+ 39 - 2
common/common-rest-model/src/main/java/com/yihu/jw/restmodel/wx/MWxMenu.java

@ -6,21 +6,58 @@ import java.util.Date;
 * Created by Administrator on 2017/5/20 0020.
 */
public class MWxMenu {
    private Long id;
    private Long id;//主键id
    private String code;//业务code
    private String wechatCode;//关联的微信code 关联表 Wx_Wechat
    private String supMenucode;//父菜单id 如果是一级菜单 此字段为空
    private String type;//菜单类型 1 view 2click
    private String type;//菜单类型
    private String name;//菜单名称
    private String key;//click等点击类型必须
    private Integer sort;//菜单排序 父菜单排序 不包含子菜单那
    private String url;//url
    private String mediaId;//点用新增永久素材接口返回的合法media_id
    private String appid;//小程序的appid
    private String pagepath;//小程序的页面程序
    private String updateUser;//更新人
    private Date updateTime;//更新时间
    private Date createTime;//创建时间
    private String createUser;//创建人
    private String remark;//备注
    private Integer status; //状态 -1 已删除 0可用
    public String getKey() {
        return key;
    }
    public void setKey(String key) {
        this.key = key;
    }
    public String getMediaId() {
        return mediaId;
    }
    public void setMediaId(String mediaId) {
        this.mediaId = mediaId;
    }
    public String getAppid() {
        return appid;
    }
    public void setAppid(String appid) {
        this.appid = appid;
    }
    public String getPagepath() {
        return pagepath;
    }
    public void setPagepath(String pagepath) {
        this.pagepath = pagepath;
    }
    public Long getId() {
        return id;
    }

+ 32 - 34
common/common-rest-model/src/main/java/com/yihu/jw/restmodel/wx/MWxTemplate.java

@ -8,10 +8,10 @@ import java.util.Date;
public class MWxTemplate {
    private Long id;
    private String code;//模板code
    private String name;//模板名称
    private String title;//模板标题
    private String wechatCode;//关联的微信code 关联表 Wx_Wechat
    private String templateCode;//微信的模板code
    private String value;//模板值
    private String templateId;//微信模板id
    private String content;//模板内容
    private String createUser;//创建人
    private String createUserName;//创建人名
    private Date createTime;//创建时间
@ -19,7 +19,23 @@ public class MWxTemplate {
    private String updateUserName;//修改人名称
    private Date updateTime;//修改时间
    private String remark;
    private Integer status; //状态 -1 已删除 0可用
    private Integer status;  //状态 -1删除 0 冻结 1可用
    public String getRemark() {
        return remark;
    }
    public void setRemark(String remark) {
        this.remark = remark;
    }
    public Integer getStatus() {
        return status;
    }
    public void setStatus(Integer status) {
        this.status = status;
    }
    public Long getId() {
        return id;
@ -37,12 +53,12 @@ public class MWxTemplate {
        this.code = code;
    }
    public String getName() {
        return name;
    public String getTitle() {
        return title;
    }
    public void setName(String name) {
        this.name = name;
    public void setTitle(String title) {
        this.title = title;
    }
    public String getWechatCode() {
@ -53,20 +69,20 @@ public class MWxTemplate {
        this.wechatCode = wechatCode;
    }
    public String getTemplateCode() {
        return templateCode;
    public String getTemplateId() {
        return templateId;
    }
    public void setTemplateCode(String templateCode) {
        this.templateCode = templateCode;
    public void setTemplateId(String templateId) {
        this.templateId = templateId;
    }
    public String getValue() {
        return value;
    public String getContent() {
        return content;
    }
    public void setValue(String value) {
        this.value = value;
    public void setContent(String content) {
        this.content = content;
    }
    public String getCreateUser() {
@ -116,22 +132,4 @@ public class MWxTemplate {
    public void setUpdateTime(Date updateTime) {
        this.updateTime = updateTime;
    }
    public String getRemark() {
        return remark;
    }
    public void setRemark(String remark) {
        this.remark = remark;
    }
    public Integer getStatus() {
        return status;
    }
    public void setStatus(Integer status) {
        this.status = status;
    }
}

+ 0 - 9
common/common-rest-model/src/main/java/com/yihu/jw/restmodel/wx/MWxWechat.java

@ -10,7 +10,6 @@ public class MWxWechat {
    private Long id;
    private String code;//业务code
    private String saasId;//'saas配置id'
    private String weichatId;//微信的id
    private String name;//名称
    private String status;//'类型 -1 已删除 0待审核 1审核通过 2 审核不通过'
    private String type;//'1:服务号 2 订阅号
@ -49,14 +48,6 @@ public class MWxWechat {
        this.saasId = saasId;
    }
    public String getWeichatId() {
        return weichatId;
    }
    public void setWeichatId(String weichatId) {
        this.weichatId = weichatId;
    }
    public String getName() {
        return name;
    }

+ 17 - 22
common/common-rest-model/src/main/java/com/yihu/jw/restmodel/wx/WxContants.java

@ -6,40 +6,38 @@ package com.yihu.jw.restmodel.wx;
public class WxContants {
    //微信token模块常量
    public static class WxAccessToken{
        public static final String message_success_create="wxAccessToken create success";
        public static final String message_success_get="wxAccessToken get success";
        public static final String api_common="wxAccessToken";
        public static final String api_create="create";
        public static final String api_get="get";
        public static final String message_fail_wechatCode_is_null="wechatCode is null";
        public static final String message_fail_expiresIn_is_null="expiresIn is null";
    }
    //微信按钮模块常量
    public static class WxMenu{
        public static final String api_common="wxMenu";
        public static final String api_create="create";
        public static final String api_get="get";
        public static final String api_delete="delete";
        public static final String api_getByCode="getByCode";
        public static final String api_update="update";
        public static final String api_getWxMenus="getWxMenus";
        public static final String api_getWxMenuNoPage="getWxMenuNoPage";
        public static final String api_createMenu="createMenu";
        public static final String message_fail_wechatCode_is_null="wechatCode is null";
        public static final String message_fail_wxMenuName_is_null="wxMenuName is null";
        public static final String message_fail_wechatcode_is_null="wechatCode is null";
        public static final String message_fail_code_is_null="code is null";
        public static final String message_fail_name_is_null="weChatMenuName is null";
        public static final String message_fail_id_is_null="id is null";
        public static final String message_fail_code_no_exist="id is null";
        public static final String message_fail_name_is_null="name is null";
        public static final String message_fail_type_is_null="type is null";
        public static final String message_fail_wxMenuKey_is_null="key is null";
        public static final String message_fail_wxMenuKey_is_toLong="key is toLong";
        public static final String message_fail_sort_is_null="sort is null";
        public static final String message_fail_sort_is_repeat="sort is repeat";
        public static final String message_fail_code_no_exist="code no exist";
        public static final String message_success_update="wxMenu update success";
        public static final String message_success_delete="wxMenu delete success";
        public static final String message_success_find="wxMenu find success";
        public static final String message_success_create="wxMenu create success";
        public static final String message_success_get="wxMenu get success";
        public static final String message_success_find_functions="wxMenu find success";
    }
    //微信模板消息
@ -51,6 +49,7 @@ public class WxContants {
        public static final String api_getByCode="getByCode";
        public static final String api_getWxTemplates="getWxTemplates";
        public static final String api_getWxTemplatesNoPage="getWxTemplatesNoPage";
        public static final String api_sendTemplateMessage="sendTemplateMessage";
        public static final String message_success_create="wxTemplate create success";
        public static final String message_success_update="wxTemplate update success";
@ -58,18 +57,18 @@ public class WxContants {
        public static final String message_success_find_functions="wxTemplate find success";
        public static final String message_success_delete="wxTemplate delete success";
        public static final String message_fail_name_exist="wxTemplate name exist";
        public static final String message_fail_code_is_null="code is null";
        public static final String message_fail_name_is_null="wxTemplate is null";
        public static final String message_fail_id_is_null="id is null";
        public static final String message_fail_code_no_exist="code no exist";
        public static final String message_fail_wechatCode_is_null="wechatCode is null";
        public static final String message_fail_templateid_is_null="templateid is null";
        public static final String message_fail_content_is_null="content is null";
        public static final String message_fail_content_format_is_not_right="content format is not right";
    }
    //微信配置表
    public static class Wechat {
        public static final String api_common="wechat";
        public static final String api_create="create";
        public static final String api_get="get";
        public static final String api_update="update";
        public static final String api_delete="delete";
        public static final String api_getWechatNoPage="getWechatNoPage";
@ -82,23 +81,21 @@ public class WxContants {
        public static final String message_success_find_functions="wechat find success";
        public static final String message_success_delete="wechat delete success";
        public static final String message_fail_name_exist="wechat name exist";
        public static final String message_fail_code_is_null="code is null";
        public static final String message_fail_name_is_null="wechat is null";
        public static final String message_fail_id_is_null="id is null";
        public static final String message_fail_code_no_exist="code no exist";
        public static final String message_fail_appId_is_null="appId is null";
        public static final String message_fail_appSecret_is_null="appSecret is null";
        public static final String message_fail_appId_exist="wechat appId exist";
        public static final String message_fail_status_is_null="status is null";
        public static final String message_fail_type_is_null="type is null";
    }
    //微信图文消息
    public static class WxGraphicMessage {
        public static final String api_common="wxGraphicMessage";
        public static final String api_create="create";
        public static final String api_get="get";
        public static final String api_update="update";
        public static final String api_delete="delete";
        public static final String api_getWxGraphicMessageNoPage="getWxGraphicMessageNoPage";
        public static final String api_sendGraphicMessages="sendGraphicMessages";
        public static final String api_getWxGraphicMessages="getWxGraphicMessages";
        public static final String api_getByCode="getByCode";
@ -109,11 +106,9 @@ public class WxContants {
        public static final String message_success_find_functions="wxGraphicMessage find success";
        public static final String message_success_delete="wxGraphicMessage delete success";
        public static final String message_fail_code_is_null="code is null";
        public static final String message_fail_id_is_null="id is null";
        public static final String message_fail_code_no_exist="code no exist";
        public static final String message_fail_code_exist="code exist";
        public static final String message_fail_appSecret_is_null="appSecret is null";
        public static final String message_fail_appId_exist="wxGraphicMessage appId exist";
        public static final String message_fail_value_is_null="value is null";
        public static final String message_fail_status_is_null="status is null";
    }
}

+ 27 - 11
svr-lib-parent-pom/pom.xml

@ -20,17 +20,17 @@
    </developers>
    <!--deploy 的时候发布到这个服务器-->
    <distributionManagement>
    <repository>
        <id>releases</id>
        <name>Releases</name>
        <url>http://172.19.103.43:8081/nexus/content/repositories/releases/</url>
    </repository>
    <snapshotRepository>
        <id>snapshots</id>
        <name>Snapshots</name>
        <url>http://172.19.103.43:8081/nexus/content/repositories/snapshots/</url>
    </snapshotRepository>
</distributionManagement>
        <repository>
            <id>releases</id>
            <name>Releases</name>
            <url>http://172.19.103.43:8081/nexus/content/repositories/releases/</url>
        </repository>
        <snapshotRepository>
            <id>snapshots</id>
            <name>Snapshots</name>
            <url>http://172.19.103.43:8081/nexus/content/repositories/snapshots/</url>
        </snapshotRepository>
    </distributionManagement>
    <modules>
        <module>../svr-configuration</module> <!--配置服务-->
@ -67,6 +67,8 @@
        <version.quartz>2.3.0</version.quartz>
        <version.logback>1.2.3</version.logback>
        <version.spring-elasticsearch>2.1.3.RELEASE</version.spring-elasticsearch>
        <version.json>20160212</version.json>
        <version.springside>4.2.3-GA</version.springside>
    </properties>
    <!--dependencyManagement作用子配置不写版本默认继承父配置-->
    <dependencyManagement>
@ -424,6 +426,20 @@
                <version>${version.logback}</version>
            </dependency>
            <!--log end-->
            <!-- json start-->
            <dependency>
                <groupId>org.json</groupId>
                <artifactId>json</artifactId>
                <version>${version.json}</version>
            </dependency>
            <!--json end -->
            <!-- springside-core start-->
            <dependency>
                <groupId>org.springside</groupId>
                <artifactId>springside-core</artifactId>
                <version>${version.springside}</version>
            </dependency>
            <!-- springside-core end-->
        </dependencies>
    </dependencyManagement>

+ 8 - 0
svr/svr-base/pom.xml

@ -108,5 +108,13 @@
            <groupId>org.springframework.data</groupId>
            <artifactId>spring-data-commons</artifactId>
        </dependency>
        <dependency>
            <groupId>org.json</groupId>
            <artifactId>json</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springside</groupId>
            <artifactId>springside-core</artifactId>
        </dependency>
    </dependencies>
</project>

+ 115 - 0
svr/svr-base/src/main/java/com/yihu/jw/util/HttpUtil.java

@ -0,0 +1,115 @@
package com.yihu.jw.util;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
/*
 * MD5 算法
 */
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();
	}
}

+ 109 - 0
svr/svr-base/src/main/java/com/yihu/jw/util/MessageUtil.java

@ -0,0 +1,109 @@
package com.yihu.jw.util;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import javax.servlet.http.HttpServletRequest;
import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
 * Created by Administrator on 2017/5/23 0023.
 */
public class MessageUtil {
    /**
     * 返回消息类型:文本
     */
    public static final String RESP_MESSAGE_TYPE_TEXT = "text";
    /**
     * 返回消息类型:音乐
     */
    public static final String RESP_MESSAGE_TYPE_MUSIC = "music";
    /**
     * 返回消息类型:图文
     */
    public static final String RESP_MESSAGE_TYPE_NEWS = "news";
    /**
     * 请求消息类型:文本
     */
    public static final String REQ_MESSAGE_TYPE_TEXT = "text";
    /**
     * 请求消息类型:图片
     */
    public static final String REQ_MESSAGE_TYPE_IMAGE = "image";
    /**
     * 请求消息类型:链接
     */
    public static final String REQ_MESSAGE_TYPE_LINK = "link";
    /**
     * 请求消息类型:地理位置
     */
    public static final String REQ_MESSAGE_TYPE_LOCATION = "location";
    /**
     * 请求消息类型:音频
     */
    public static final String REQ_MESSAGE_TYPE_VOICE = "voice";
    /**
     * 请求消息类型:推送
     */
    public static final String REQ_MESSAGE_TYPE_EVENT = "event";
    /**
     * 事件类型:subscribe(订阅)
     */
    public static final String EVENT_TYPE_SUBSCRIBE = "subscribe";
    /**
     * 事件类型:unsubscribe(取消订阅)
     */
    public static final String EVENT_TYPE_UNSUBSCRIBE = "unsubscribe";
    /**
     * 事件类型:CLICK(自定义菜单点击事件)
     */
    public static final String EVENT_TYPE_CLICK = "CLICK";
    /**
     * 解析微信发来的请求(XML)
     *
     * @param request
     * @return
     * @throws Exception
     */
    @SuppressWarnings("unchecked")
    public static Map<String, String> parseXml(HttpServletRequest request) throws Exception {
        // 将解析结果存储在HashMap中
        Map<String, String> map = new HashMap<String, String>();
        // 从request中取得输入流
        InputStream inputStream = request.getInputStream();
        // 读取输入流
        SAXReader reader = new SAXReader();
        Document document = reader.read(inputStream);
        // 得到xml根元素
        Element root = document.getRootElement();
        // 得到根元素的所有子节点
        List<Element> elementList = root.elements();
        // 遍历所有子节点
        for (Element e : elementList)
            map.put(e.getName(), e.getText());
        // 释放资源
        inputStream.close();
        inputStream = null;
        return map;
    }
}

+ 4 - 17
svr/svr-base/src/main/java/com/yihu/jw/wx/controller/WxAccessTokenController.java

@ -10,8 +10,10 @@ import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
/**
 * Created by cyx on 2017/5/11.
@ -42,19 +44,4 @@ public class WxAccessTokenController extends EnvelopRestController {
            return Envelop.getError(e.getMessage(), e.getErrorCode());
        }
    }
    @PostMapping(value = WxContants.WxAccessToken.api_create, consumes = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ApiOperation(value = "创建WxAccessToken")
    public Envelop createWxAccessToken(
            @ApiParam(name = "wxAccessToken", value = "对象JSON结构体", allowMultiple = true)
            @RequestBody String wxAccessTokenJson) throws Exception {
        try {
            WxAccessToken wxAccessToken = toEntity(wxAccessTokenJson, WxAccessToken.class);
            wxAccessToken = wxAccessTokenService.createWxAccessToken(wxAccessToken);
            return Envelop.getSuccess(WxContants.WxAccessToken.message_success_create, wxAccessToken);
        }catch (ApiException e) {
            return Envelop.getError(e.getMessage(), e.getErrorCode());
        }
    }
}

+ 26 - 1
svr/svr-base/src/main/java/com/yihu/jw/wx/controller/WxGraphicMessageController.java

@ -20,7 +20,7 @@ import java.util.ArrayList;
import java.util.List;
/**
 * Created by chenweida on 2017/5/11.
 *   2017/5/11.
 */
@RestController
@RequestMapping(WxContants.WxGraphicMessage.api_common)
@ -42,6 +42,7 @@ public class WxGraphicMessageController extends EnvelopRestController {
        }
    }
    @PutMapping(value = WxContants.WxGraphicMessage.api_update, consumes = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ApiOperation(value = "修改微信图文消息", notes = "修改微信图文消息")
    public Envelop updateWxGraphicMessage(
@ -126,4 +127,28 @@ public class WxGraphicMessageController extends EnvelopRestController {
        return Envelop.getSuccessList(WxContants.WxGraphicMessage.message_success_find_functions,mWxGraphicMessages);
    }
    @GetMapping(value = WxContants.WxGraphicMessage.api_sendGraphicMessages)
    @ApiOperation(value = "发送图文消息")
    public Envelop sendGraphicMessages(
            @ApiParam(name = "codes", value = "根据code发送微信图文消息,多个code用,分割")
            @RequestParam(value = "codes", required = true) String codes,HttpServletRequest request) throws Exception {
        String messages = wxGraphicMessageService.sendGraphicMessages(codes, request);
        return Envelop.getSuccess("成功",messages);
    }
    @GetMapping(value = WxContants.WxGraphicMessage.api_sendGraphicMessages)
    @ApiOperation(value = "发送图文消息")
    public Envelop sendGraphicMessages(
            @ApiParam(name = "codes", value = "根据code发送微信图文消息,多个code用,分割")
            @RequestParam(value = "codes", required = true) String codes,
            @ApiParam(name = "fromUserName", value = "用户openid")
            @RequestParam(value = "fromUserName", required = true) String fromUserName,
            @ApiParam(name = "toUserName", value = "公众号")
            @RequestParam(value = "toUserName", required = true) String toUserName
            ) throws Exception {
        String messages = wxGraphicMessageService.sendGraphicMessages(codes, fromUserName,toUserName);
        return Envelop.getSuccess("成功",messages);
    }
}

+ 25 - 1
svr/svr-base/src/main/java/com/yihu/jw/wx/controller/WxMenuController.java

@ -11,6 +11,7 @@ import com.yihu.jw.wx.service.WxMenuService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
@ -32,7 +33,7 @@ public class WxMenuController extends EnvelopRestController {
    private WxMenuService wxMenuService;
    @PostMapping(value = WxContants.WxMenu.api_create, consumes = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ApiOperation(value = "创建微信菜单", notes = "创建微信菜单")
    @ApiOperation(value = "添加微信菜单", notes = "添加微信菜单")
    public Envelop createWxMenu(
            @ApiParam(name = "json_data", value = "", defaultValue = "")
            @RequestBody String jsonData) {
@ -128,4 +129,27 @@ public class WxMenuController extends EnvelopRestController {
        return Envelop.getSuccessList(WxContants.WxMenu.message_success_find_functions,mWxMenus);
    }
    /**
     * 创建微信公众号菜单
     *
     * @return
     */
    @ApiOperation(value = "创建微信公众号菜单", notes = "创建微信公众号菜单")
    @RequestMapping(value = WxContants.WxMenu.api_createMenu ,method = RequestMethod.GET)
    @ResponseBody
    public Envelop createWechatMenu(
            @ApiParam(name = "wechatCode", value = "", defaultValue = "")
            @RequestParam(value = "wechatCode", required = true)String wechatCode){
        try{
            JSONObject result = wxMenuService.createWechatMenu(wechatCode);
            if(result != null && result.get("errcode").toString().equals("0") && result.getString("errmsg").equals("ok")){
                return Envelop.getSuccess("创建成功",result );
            }else{
                return Envelop.getSuccess("创建失败",result );
            }
        }catch (Exception e){
            return Envelop.getSuccess("创建成功",e );
        }
    }
}

+ 30 - 1
svr/svr-base/src/main/java/com/yihu/jw/wx/controller/WxTemplateController.java

@ -5,11 +5,14 @@ import com.yihu.jw.restmodel.common.EnvelopRestController;
import com.yihu.jw.restmodel.exception.ApiException;
import com.yihu.jw.restmodel.wx.MWxTemplate;
import com.yihu.jw.restmodel.wx.WxContants;
import com.yihu.jw.wx.model.Miniprogram;
import com.yihu.jw.wx.model.WxTemplate;
import com.yihu.jw.wx.service.WxTemplateService;
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.*;
@ -32,7 +35,7 @@ public class WxTemplateController extends EnvelopRestController {
    @PostMapping(value = WxContants.WxTemplate.api_create, consumes = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ApiOperation(value = "创建微信模版", notes = "创建微信模版")
    public Envelop createWxTemplate(
            @ApiParam(name = "json_data", value = "", defaultValue = "")
            @ApiParam(name = "json_data", value = "微信模版json字符串")
            @RequestBody String jsonData) {
        try {
            WxTemplate WxTemplate = toEntity(jsonData, WxTemplate.class);
@ -125,4 +128,30 @@ public class WxTemplateController extends EnvelopRestController {
        List<MWxTemplate> mMWxTemplates = convertToModels(list, new ArrayList<>(list.size()), MWxTemplate.class, fields);
        return Envelop.getSuccessList(WxContants.WxTemplate.message_success_find_functions,mMWxTemplates);
    }
    @GetMapping(value = WxContants.WxTemplate.api_sendTemplateMessage)
    @ApiOperation(value = "发送微信模板消息")
    public Envelop sendTemplateMessage(
            @ApiParam(name="openid",value="微信用户的openid")
            @RequestParam String openid,
            @ApiParam(name="tempalteCode",value = "模板code")
            @RequestParam String templateCode,
            @ApiParam(name="url",value="模板跳转链接")
            @RequestParam(required = false) String url,
            @ApiParam(name="appid",value="所需跳转到的小程序appid(该小程序appid必须与发模板消息的公众号是绑定关联关系)")
            @RequestParam(required = false) String appid,
            @ApiParam(name="pagepath",value="所需跳转到小程序的具体页面路径,支持带参数,(示例index?foo=bar)")
            @RequestParam(required = false) String pagepath,
            @ApiParam(name="data",value="json字符串")
            @RequestParam String data
    ){
        Miniprogram miniprogram = null;
        if(StringUtils.isNotBlank(appid)&&StringUtils.isNotBlank(pagepath)){
            miniprogram = new Miniprogram();
            miniprogram.setAppid(appid);
            miniprogram.setPagepath(pagepath);
        }
        JSONObject jsonObject = wxTemplateService.sendTemplateMessage(openid, templateCode, url, data, miniprogram);
        return Envelop.getSuccess("成功",jsonObject);
    }
}

+ 26 - 1
svr/svr-base/src/main/java/com/yihu/jw/wx/dao/WxMenuDao.java

@ -5,11 +5,36 @@ import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.PagingAndSortingRepository;
import java.util.List;
/**
 * Created by Administrator on 2017/5/19 0019.
 */
public interface WxMenuDao  extends PagingAndSortingRepository<WxMenu, Long>, JpaSpecificationExecutor<WxMenu> {
    @Query("from WxMenu m where m.code = ?1")
    @Query("from WxMenu m where m.code = ?1 and m.status = 1")
    WxMenu findByCode(String code);
    @Query("from WxMenu m where m.wechatCode =?1 and m.status = 1 order  by m.supMenucode ,m.sort")
    List<WxMenu> findByWechatCode(String wechatCode);
    @Query("from WxMenu m where m.wechatCode = ?1 and  m.supMenucode= ?2 and m.status =1 order by m.sort")
    List<WxMenu> findChildMenus(String wechatCode, String sup_menucode);
    /**
     * 根据wechatCode判断父菜单的sort是否重复
     * @param wechatCode
     * @param sort
     */
    @Query("from WxMenu m where m.wechatCode = ?1 and m.status =1 and m.sort =?2 and m.supMenucode is null and m.code != ?3")
    WxMenu findByWechatCodeExcludeSortFromParent(String wechatCode, Integer sort,String code);
    /**
     * 根据wechatCode,supMenucode判断子菜单的sort是否重复
     * @param wechatCode
     * @param sort
     */
    @Query("from WxMenu m where m.wechatCode = ?1 and m.status =1 and m.sort =?2 and m.supMenucode =?3 and m.code != ?4")
    WxMenu findByWechatCodeExcludeSortFromChild(String wechatCode, Integer sort,String supMenucode,String code);
}

+ 30 - 0
svr/svr-base/src/main/java/com/yihu/jw/wx/model/Miniprogram.java

@ -0,0 +1,30 @@
package com.yihu.jw.wx.model;
import java.io.Serializable;
/**
 * Created by Administrator on 2017/5/24 0024.
 */
public class Miniprogram implements Serializable{
    private static final long serialVersionUID = -7963058957081033262L;
    private String appid;
    private String pagepath;
    public String getAppid() {
        return appid;
    }
    public void setAppid(String appid) {
        this.appid = appid;
    }
    public String getPagepath() {
        return pagepath;
    }
    public void setPagepath(String pagepath) {
        this.pagepath = pagepath;
    }
}

+ 58 - 0
svr/svr-base/src/main/java/com/yihu/jw/wx/model/WechatTemplate.java

@ -0,0 +1,58 @@
package com.yihu.jw.wx.model;
import java.io.Serializable;
import java.util.Map;
/**
 * 微信消息模板推送内容
 * @author George
 */
public class WechatTemplate implements Serializable {
	private static final long serialVersionUID = 3877107913397496785L;
    private String touser;//用户openId
    private String template_id;//模板消息id
    private String url;//URL置空,则在发送后,点击模板消息会进入一个空白页面(ios),或无法点击(android)
    private Miniprogram miniprogram;
    private Map<String,WechatTemplateData> data;//详细内容
    public Miniprogram getMiniprogram() {
        return miniprogram;
    }
    public void setMiniprogram(Miniprogram miniprogram) {
        this.miniprogram = miniprogram;
    }
    
    public String getTemplate_id() {
        return template_id;
    }
    public void setTemplate_id(String template_id) {
        this.template_id = template_id;
    }
    public String getTouser() {
        return touser;
    }
    public void setTouser(String touser) {
        this.touser = touser;
    }
    public String getUrl() {
        return url;
    }
    public void setUrl(String url) {
        this.url = url;
    }
    public Map<String, WechatTemplateData> getData() {
        return data;
    }
    public void setData(Map<String, WechatTemplateData> data) {
        this.data = data;
    }
    
}

+ 31 - 0
svr/svr-base/src/main/java/com/yihu/jw/wx/model/WechatTemplateData.java

@ -0,0 +1,31 @@
package com.yihu.jw.wx.model;
import java.io.Serializable;
/**
 * 微信消息模板
 * @author George
 */
public class WechatTemplateData implements Serializable {
	private static final long serialVersionUID = -7399054549159698617L;
	private String value;
    private String color;
    public String getValue() {
        return value;
    }
    public void setValue(String value) {
        this.value = value;
    }
    public String getColor() {
        return color;
    }
    public void setColor(String color) {
        this.color = color;
    }
}

+ 4 - 4
svr/svr-base/src/main/java/com/yihu/jw/wx/model/WxAccessToken.java

@ -18,14 +18,14 @@ public class WxAccessToken extends IdEntity implements java.io.Serializable {
	private String wechatCode;//关联的微信code 关联表 Wx_Wechat
	private String accessToken;//调用微信返回的accesstoken
	private long addTimestamp;//创建时间
	private Integer expiresIn;//凭证有效时间(秒)
	private long expiresIn;//凭证有效时间(秒)
	private Date czrq;//操作时间
	/** default constructor */
	public WxAccessToken() {
	}
	/** minimal constructor */
	public WxAccessToken(Long id, String accessToken, long addTimestamp,
			Integer expiresIn, Date czrq) {
			long expiresIn, Date czrq) {
		this.id = id;
		this.accessToken = accessToken;
		this.addTimestamp = addTimestamp;
@ -81,11 +81,11 @@ public class WxAccessToken extends IdEntity implements java.io.Serializable {
	}
	@Column(name = "expires_in", nullable = false)
	public Integer getExpiresIn() {
	public Long getExpiresIn() {
		return this.expiresIn;
	}
	public void setExpiresIn(Integer expiresIn) {
	public void setExpiresIn(Long expiresIn) {
		this.expiresIn = expiresIn;
	}

+ 35 - 34
svr/svr-base/src/main/java/com/yihu/jw/wx/model/WxGraphicMessage.java

@ -13,25 +13,29 @@ import java.util.Date;
public class WxGraphicMessage extends IdEntity implements java.io.Serializable {
    private String code;//业务code
    private String wechatCode;//关联的微信code 关联表 Wx_Wechat
    private String name;//名称
    private String value;//图文消息url值
    private String keyword;//关键字
    private String title;//标题
    private String description;//描述
    private String url;//图文消息url值
    private String picUrl;//图片地址
    private String createUser;//创建人
    private String createUserName;//创建人名
    private Date createTime;//创建时间
    private String updateUser;//修改人
    private String updateUserName;//修改人名称
    private Date updateTime;//修改时间
    private String remark;
    private Integer status; //状态 -1 已删除 0可用
    private String remark;//备注
    private Integer status;  //状态 -1删除 0 冻结 1可用
    public WxGraphicMessage(String code, String wechatCode, String name, String value, String keyword, String createUser, String createUserName, Date createTime, String updateUser, String updateUserName, Date updateTime, String remark, Integer status) {
    public WxGraphicMessage() {
    }
    public WxGraphicMessage(String code, String title, String description, String url, String picUrl, String createUser, String createUserName, Date createTime, String updateUser, String updateUserName, Date updateTime, String remark, Integer status) {
        this.code = code;
        this.wechatCode = wechatCode;
        this.name = name;
        this.value = value;
        this.keyword = keyword;
        this.title = title;
        this.description = description;
        this.url = url;
        this.picUrl = picUrl;
        this.createUser = createUser;
        this.createUserName = createUserName;
        this.createTime = createTime;
@ -42,9 +46,6 @@ public class WxGraphicMessage extends IdEntity implements java.io.Serializable {
        this.status = status;
    }
    public WxGraphicMessage() {
    }
    @Column(name = "code", length = 64)
    public String getCode() {
        return code;
@ -54,40 +55,40 @@ public class WxGraphicMessage extends IdEntity implements java.io.Serializable {
        this.code = code;
    }
    @Column(name = "wechat_code", length = 200)
    public String getWechatCode() {
        return wechatCode;
    @Column(name = "title", length = 200)
    public String getTitle() {
        return title;
    }
    public void setWechatCode(String wechatCode) {
        this.wechatCode = wechatCode;
    public void setTitle(String title) {
        this.title = title;
    }
    @Column(name = "name", length = 200)
    public String getName() {
        return name;
    @Column(name = "description", length = 2000)
    public String getDescription() {
        return description;
    }
    public void setName(String name) {
        this.name = name;
    public void setDescription(String description) {
        this.description = description;
    }
    @Column(name = "value", length = 2000)
    public String getValue() {
        return value;
    @Column(name = "url", length = 2000)
    public String getUrl() {
        return url;
    }
    public void setValue(String value) {
        this.value = value;
    public void setUrl(String url) {
        this.url = url;
    }
    @Column(name = "keyword", length = 100)
    public String getKeyword() {
        return keyword;
    @Column(name = "pic_url", length = 2000)
    public String getPicUrl() {
        return picUrl;
    }
    public void setKeyword(String keyword) {
        this.keyword = keyword;
    public void setPicUrl(String picUrl) {
        this.picUrl = picUrl;
    }
    @Column(name = "create_user", length = 200)

+ 45 - 4
svr/svr-base/src/main/java/com/yihu/jw/wx/model/WxMenu.java

@ -16,26 +16,34 @@ public class WxMenu extends IdEntity implements java.io.Serializable {
    private String code;//业务code
    private String wechatCode;//关联的微信code 关联表 Wx_Wechat
    private String supMenucode;//父菜单id 如果是一级菜单 此字段为空
    private String type;//菜单类型 1 view 2click
    private String type;//菜单类型
    private String name;//菜单名称
    private String key;//click等点击类型必须
    private Integer sort;//菜单排序 父菜单排序 不包含子菜单那
    private String url;//url
    private String mediaId;//点用新增永久素材接口返回的合法media_id
    private String appid;//小程序的appid
    private String pagepath;//小程序的页面程序
    private String updateUser;//更新人
    private Date updateTime;//更新时间
    private Date createTime;//创建时间
    private String createUser;//创建人
    private String remark;//备注
    private Integer status; //状态 -1 已删除 0可用
    private Integer status; //状态 -1删除 0 冻结 1可用
    public WxMenu(Long id, String code, String wechatCode, String supMenucode, String type, String name, Integer sort, String url, String updateUser, Date updateTime, Date createTime, String createUser, String remark, Integer status) {
        this.id = id;
    public WxMenu(String code, String wechatCode, String supMenucode, String type, String name, String key, Integer sort, String url, String mediaId, String appid, String pagepath, String updateUser, Date updateTime, Date createTime, String createUser, String remark, Integer status) {
        this.code = code;
        this.wechatCode = wechatCode;
        this.supMenucode = supMenucode;
        this.type = type;
        this.name = name;
        this.key = key;
        this.sort = sort;
        this.url = url;
        this.mediaId = mediaId;
        this.appid = appid;
        this.pagepath = pagepath;
        this.updateUser = updateUser;
        this.updateTime = updateTime;
        this.createTime = createTime;
@ -50,6 +58,39 @@ public class WxMenu extends IdEntity implements java.io.Serializable {
    public WxMenu() {
    }
    public String getKey() {
        return key;
    }
    public void setKey(String key) {
        this.key = key;
    }
    public String getMediaId() {
        return mediaId;
    }
    @Column(name = "media_id", length = 200)
    public void setMediaId(String mediaId) {
        this.mediaId = mediaId;
    }
    public String getAppid() {
        return appid;
    }
    public void setAppid(String appid) {
        this.appid = appid;
    }
    public String getPagepath() {
        return pagepath;
    }
    public void setPagepath(String pagepath) {
        this.pagepath = pagepath;
    }
    public String getCode() {
        return code;
    }

+ 45 - 46
svr/svr-base/src/main/java/com/yihu/jw/wx/model/WxTemplate.java

@ -13,12 +13,11 @@ import java.util.Date;
public class WxTemplate extends IdEntity implements java.io.Serializable {
    // Fields
    private String code;//模板code
    private String name;//模板名称
    private String title;//模板标题
    private String wechatCode;//关联的微信code 关联表 Wx_Wechat
    private String templateCode;//微信的模板code
    private String value;//模板值
    private String templateId;//微信模板id
    private String content;//模板内容
    private String createUser;//创建人
    private String createUserName;//创建人名
    private Date createTime;//创建时间
@ -26,15 +25,14 @@ public class WxTemplate extends IdEntity implements java.io.Serializable {
    private String updateUserName;//修改人名称
    private Date updateTime;//修改时间
    private String remark;
    private Integer status; //状态 -1 已删除 0可用
    private Integer status;  //状态 -1删除 0 冻结 1可用
    public WxTemplate(Long id, String code, String name, String wechatCode, String templateCode, String value, String createUser, String createUserName, Date createTime, String updateUser, String updateUserName, Date updateTime, String remark, Integer status) {
        this.id = id;
    public WxTemplate(String code, String title, String wechatCode, String templateId, String content, String createUser, String createUserName, Date createTime, String updateUser, String updateUserName, Date updateTime, String remark, Integer status) {
        this.code = code;
        this.name = name;
        this.title = title;
        this.wechatCode = wechatCode;
        this.templateCode = templateCode;
        this.value = value;
        this.templateId = templateId;
        this.content = content;
        this.createUser = createUser;
        this.createUserName = createUserName;
        this.createTime = createTime;
@ -51,6 +49,43 @@ public class WxTemplate extends IdEntity implements java.io.Serializable {
    public WxTemplate() {
    }
    @Column(name = "title")
    public String getTitle() {
        return title;
    }
    public void setTitle(String title) {
        this.title = title;
    }
    @Column(name="wechat_code")
    public String getWechatCode() {
        return wechatCode;
    }
    public void setWechatCode(String wechatCode) {
        this.wechatCode = wechatCode;
    }
    @Column(name="template_id")
    public String getTemplateId() {
        return templateId;
    }
    public void setTemplateId(String templateId) {
        this.templateId = templateId;
    }
    @Column(name="content")
    public String getContent() {
        return content;
    }
    public void setContent(String content) {
        this.content = content;
    }
    public String getUpdateUser() {
        return updateUser;
    }
@ -93,42 +128,6 @@ public class WxTemplate extends IdEntity implements java.io.Serializable {
        this.code = code;
    }
    @Column(name = "name", length = 200)
    public String getName() {
        return this.name;
    }
    public void setName(String name) {
        this.name = name;
    }
    @Column(name = "wechat_code", length = 64)
    public String getWechatCode() {
        return this.wechatCode;
    }
    public void setWechatCode(String wechatCode) {
        this.wechatCode = wechatCode;
    }
    @Column(name = "template_code", length = 100)
    public String getTemplateCode() {
        return this.templateCode;
    }
    public void setTemplateCode(String templateCode) {
        this.templateCode = templateCode;
    }
    @Column(name = "value", length = 2000)
    public String getValue() {
        return this.value;
    }
    public void setValue(String value) {
        this.value = value;
    }
    @Column(name = "create_user", length = 200)
    public String getCreateUser() {
        return this.createUser;

+ 1 - 12
svr/svr-base/src/main/java/com/yihu/jw/wx/model/WxWechat.java

@ -15,7 +15,6 @@ public class WxWechat extends IdEntity implements java.io.Serializable {
    // Fields
    private String code;//业务code
    private String saasId;//'saas配置id'
    private String weichatId;//微信的id
    private String name;//名称
    private String status;//'类型 -1 已删除 0待审核 1审核通过 2 审核不通过'
    private String type;//'1:服务号 2 订阅号
@ -30,10 +29,9 @@ public class WxWechat extends IdEntity implements java.io.Serializable {
    private Date updateTime;//'修改时间'
    private String remark;//'备注'
    public WxWechat(String code, String saasId, String weichatId, String name, String status, String type, String appId, String appSecret, String baseUrl, String createUser, String createUserName, Date createTime, String updateUser, String updateUserName, Date updateTime, String remark) {
    public WxWechat(String code, String saasId, String name, String status, String type, String appId, String appSecret, String baseUrl, String createUser, String createUserName, Date createTime, String updateUser, String updateUserName, Date updateTime, String remark) {
        this.code = code;
        this.saasId = saasId;
        this.weichatId = weichatId;
        this.name = name;
        this.status = status;
        this.type = type;
@ -74,15 +72,6 @@ public class WxWechat extends IdEntity implements java.io.Serializable {
        this.saasId = saasId;
    }
    @Column(name = "weichat_id", length = 50)
    public String getWeichatId() {
        return this.weichatId;
    }
    public void setWeichatId(String weichatId) {
        this.weichatId = weichatId;
    }
    @Column(name = "name", length = 200)
    public String getName() {
        return this.name;

+ 15 - 6
svr/svr-base/src/main/java/com/yihu/jw/wx/service/WechatService.java

@ -26,8 +26,14 @@ public class WechatService extends BaseJpaService<WxWechat, WechatDao> {
        if (StringUtils.isEmpty(wechat.getCode())) {
            throw new ApiException(WxContants.Wechat.message_fail_code_is_null, CommonContants.common_error_params_code);
        }
        if (StringUtils.isEmpty(wechat.getAppId())) {
            throw new ApiException(WxContants.Wechat.message_fail_appId_is_null, CommonContants.common_error_params_code);
        if (StringUtils.isEmpty(wechat.getStatus())) {
            throw new ApiException(WxContants.Wechat.message_fail_status_is_null, CommonContants.common_error_params_code);
        }
        if (StringUtils.isEmpty(wechat.getType())) {
            throw new ApiException(WxContants.Wechat.message_fail_type_is_null, CommonContants.common_error_params_code);
        }
        if (StringUtils.isEmpty(wechat.getAppSecret())) {
            throw new ApiException(WxContants.Wechat.message_fail_appSecret_is_null, CommonContants.common_error_params_code);
        }
        if (StringUtils.isEmpty(wechat.getAppSecret())) {
            throw new ApiException(WxContants.Wechat.message_fail_appSecret_is_null, CommonContants.common_error_params_code);
@ -44,14 +50,17 @@ public class WechatService extends BaseJpaService<WxWechat, WechatDao> {
        if (StringUtils.isEmpty(wechat.getCode())) {
            throw new ApiException(WxContants.Wechat.message_fail_code_is_null, CommonContants.common_error_params_code);
        }
        if (StringUtils.isEmpty(wechat.getAppId())) {
            throw new ApiException(WxContants.Wechat.message_fail_appId_is_null, CommonContants.common_error_params_code);
        if (StringUtils.isEmpty(wechat.getStatus())) {
            throw new ApiException(WxContants.Wechat.message_fail_status_is_null, CommonContants.common_error_params_code);
        }
        if (StringUtils.isEmpty(wechat.getType())) {
            throw new ApiException(WxContants.Wechat.message_fail_type_is_null, CommonContants.common_error_params_code);
        }
        if (StringUtils.isEmpty(wechat.getAppSecret())) {
            throw new ApiException(WxContants.Wechat.message_fail_appSecret_is_null, CommonContants.common_error_params_code);
        }
        if (StringUtils.isEmpty(wechat.getCode())) {
            throw new ApiException(WxContants.Wechat.message_fail_code_is_null, CommonContants.common_error_params_code);
        if (StringUtils.isEmpty(wechat.getAppSecret())) {
            throw new ApiException(WxContants.Wechat.message_fail_appSecret_is_null, CommonContants.common_error_params_code);
        }
        WxWechat wechatTem = wechatDao.findByAppIdExcludeCode(wechat.getAppId(),wechat.getCode());
        if(wechatTem!=null){

+ 52 - 20
svr/svr-base/src/main/java/com/yihu/jw/wx/service/WxAccessTokenService.java

@ -1,17 +1,18 @@
package com.yihu.jw.wx.service;
import com.yihu.jw.mysql.query.BaseJpaService;
import com.yihu.jw.restmodel.common.CommonContants;
import com.yihu.jw.restmodel.exception.ApiException;
import com.yihu.jw.restmodel.wx.WxContants;
import com.yihu.jw.util.HttpUtil;
import com.yihu.jw.wx.dao.WechatDao;
import com.yihu.jw.wx.dao.WxAccessTokenDao;
import com.yihu.jw.wx.model.WxAccessToken;
import com.yihu.jw.wx.model.WxWechat;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springside.modules.utils.Clock;
import java.util.List;
import java.util.UUID;
/**
 * Created by Administrator on 2017/5/18 0018.
@ -22,27 +23,58 @@ public class WxAccessTokenService extends BaseJpaService<WxAccessToken, WxAccess
    @Autowired
    private WxAccessTokenDao wxAccessTokenDao;
    @Autowired
    private WechatDao wechatDao;
    /**
     * 根据wechatCode查找最新一条
     * @param wechatCode
     * @return
     */
    public WxAccessToken getWxAccessTokenByCode(String wechatCode) {
        List<WxAccessToken> wxAccessTokens =  wxAccessTokenDao.getWxAccessTokenByCode(wechatCode);
        if(wxAccessTokens!=null&&wxAccessTokens.size()>0){
            return wxAccessTokens.get(0);
        }
        return null;
    }
    @Transactional
    public WxAccessToken createWxAccessToken(WxAccessToken wxAccessToken) {
        if (StringUtils.isEmpty(wxAccessToken.getWechatCode())) {
            throw new ApiException(WxContants.WxAccessToken.message_fail_wechatCode_is_null, CommonContants.common_error_params_code);
        }
        if (StringUtils.isEmpty(wxAccessToken.getExpiresIn())) {
            throw new ApiException(WxContants.WxAccessToken.message_fail_expiresIn_is_null, CommonContants.common_error_params_code);
        try {
            List<WxAccessToken> wxAccessTokens =  wxAccessTokenDao.getWxAccessTokenByCode(wechatCode);
            if(wxAccessTokens!=null&&wxAccessTokens.size()>0){
                for (WxAccessToken accessToken : wxAccessTokens) {
                    if ((System.currentTimeMillis() - accessToken.getAddTimestamp()) < (accessToken.getExpiresIn() * 1000)) {
                        return accessToken;
                    } else {
                        wxAccessTokenDao.delete(accessToken);
                        break;
                    }
                }
            }
            String token_url = "https://api.weixin.qq.com/cgi-bin/token";
            String appId="";
            String appSecret="";
            //根据wechatCode查找出appid和appSecret
            WxWechat wxWechat = wechatDao.findByCode(wechatCode);
            if(wxWechat==null){
                return null;
            }
            appId = wxWechat.getAppId();
            appSecret = wxWechat.getAppSecret();
            String params = "grant_type=client_credential&appid=" + appId + "&secret=" + appSecret;
            String result = HttpUtil.sendGet(token_url, params);
            JSONObject json = new JSONObject(result);
            if (json.has("access_token")) {
                String token = json.get("access_token").toString();
                String expires_in = json.get("expires_in").toString();
                WxAccessToken newaccessToken = new WxAccessToken();
                newaccessToken.setAccessToken(token);
                newaccessToken.setExpiresIn(Long.parseLong(expires_in));
                newaccessToken.setAddTimestamp(System.currentTimeMillis());
                newaccessToken.setCzrq(new Clock.DefaultClock().getCurrentDate());
                newaccessToken.setCode(UUID.randomUUID().toString().replace("-",""));
                newaccessToken.setWechatCode(wechatCode);
                wxAccessTokenDao.save(newaccessToken);
                return newaccessToken;
            } else {
                return null;
            }
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
        return wxAccessTokenDao.save(wxAccessToken);
    }
}

+ 107 - 4
svr/svr-base/src/main/java/com/yihu/jw/wx/service/WxGraphicMessageService.java

@ -4,6 +4,7 @@ import com.yihu.jw.mysql.query.BaseJpaService;
import com.yihu.jw.restmodel.common.CommonContants;
import com.yihu.jw.restmodel.exception.ApiException;
import com.yihu.jw.restmodel.wx.WxContants;
import com.yihu.jw.util.MessageUtil;
import com.yihu.jw.wx.dao.WxGraphicMessageDao;
import com.yihu.jw.wx.model.WxGraphicMessage;
import org.springframework.beans.factory.annotation.Autowired;
@ -11,6 +12,8 @@ import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import javax.persistence.Transient;
import javax.servlet.http.HttpServletRequest;
import java.util.*;
/**
 * Created by Administrator on 2017/5/20 0020.
@ -26,8 +29,8 @@ public class WxGraphicMessageService extends BaseJpaService<WxGraphicMessage, Wx
        if (StringUtils.isEmpty(wxGraphicMessage.getCode())) {
            throw new ApiException(WxContants.WxGraphicMessage.message_fail_code_is_null, CommonContants.common_error_params_code);
        }
        if (StringUtils.isEmpty(wxGraphicMessage.getValue())) {
            throw new ApiException(WxContants.WxGraphicMessage.message_fail_value_is_null, CommonContants.common_error_params_code);
        if (StringUtils.isEmpty(wxGraphicMessage.getStatus())) {
            throw new ApiException(WxContants.WxGraphicMessage.message_fail_status_is_null, CommonContants.common_error_params_code);
        }
        WxGraphicMessage wxGraphicMessageTem = wxGraphicMessageDao.findByCode(wxGraphicMessage.getCode());
        if (wxGraphicMessageTem != null) {
@ -41,8 +44,8 @@ public class WxGraphicMessageService extends BaseJpaService<WxGraphicMessage, Wx
        if (StringUtils.isEmpty(wxGraphicMessage.getCode())) {
            throw new ApiException(WxContants.WxGraphicMessage.message_fail_code_is_null, CommonContants.common_error_params_code);
        }
        if (StringUtils.isEmpty(wxGraphicMessage.getValue())) {
            throw new ApiException(WxContants.WxGraphicMessage.message_fail_value_is_null, CommonContants.common_error_params_code);
        if (StringUtils.isEmpty(wxGraphicMessage.getStatus())) {
            throw new ApiException(WxContants.WxGraphicMessage.message_fail_status_is_null, CommonContants.common_error_params_code);
        }
        return wxGraphicMessageDao.save(wxGraphicMessage);
    }
@ -61,4 +64,104 @@ public class WxGraphicMessageService extends BaseJpaService<WxGraphicMessage, Wx
        WxGraphicMessage.setStatus(-1);
        wxGraphicMessageDao.save(WxGraphicMessage);
    }
    private String replyNewsMessage(String toUser,String fromUser,List<Map<String,String>> articles) throws Exception {
        if(articles == null || articles.size() < 1){
            throw new Exception("图文信息不能为空!");
        }
        StringBuilder result = new StringBuilder();
        result.append("<xml>");
        result.append("<ToUserName>" + toUser + "</ToUserName>");
        result.append("<FromUserName>" + fromUser + "</FromUserName>");
        result.append("<CreateTime>" + new Date().getTime() + "</CreateTime>");
        result.append("<MsgType>news</MsgType>");
        result.append("<ArticleCount>" + articles.size() + "</ArticleCount>");
        result.append("<Articles>");
        for(Map<String,String>  article : articles){
            result.append("<item>");
            result.append("<Title>" +  article.get("Title") +"</Title>");
            result.append("<Description>" + article.get("Description") + "</Description>");
            result.append("<PicUrl>" + article.get("PicUrl") + "</PicUrl>");
            result.append("<Url>" + article.get("Url") + "</Url>");
            result.append("</item>");
        }
        result.append("</Articles>");
        result.append("</xml>");
        return result.toString();
    }
    /**
     * 发送图文消息
     * @param codes
     * @param request
     * @return
     */
    public String sendGraphicMessages(String codes, HttpServletRequest request) {
        try {
            // xml请求解析
            Map<String, String> requestMap = MessageUtil.parseXml(request);
            //用户openid
            String fromUserName = requestMap.get("FromUserName");
            //微信公众号
            String toUserName = requestMap.get("ToUserName");
            // 图文信息
            List<Map<String,String>> articles =  new ArrayList<>();
            if(codes!=null){
                String[] codeArray = codes.split(",");
                for(String code: codeArray){
                    WxGraphicMessage graphicMessage = findByCode(code);
                    Map<String,String> article = new HashMap<>();
                    article.put("Url",graphicMessage.getUrl());
                    article.put("Title", graphicMessage.getTitle());
                    article.put("Description",graphicMessage.getDescription());
                    article.put("PicUrl",graphicMessage.getPicUrl());
                    articles.add(article);
                }
            }
            // 构建回复消息XML
            return replyNewsMessage(fromUserName, toUserName, articles);
        } catch (Exception e) {
            e.printStackTrace();
            return e.getMessage();
        }
    }
    /**
     * 发送图文消息
     * @param codes
     * @param fromUserName   用户的openId
     * @param toUserName
     * @return
     */
    public String sendGraphicMessages(String codes, String fromUserName,String toUserName) {
        try {
        // 图文信息
            List<Map<String,String>> articles =  new ArrayList<>();
            if(codes!=null){
                String[] codeArray = codes.split(",");
                for(String code: codeArray){
                    WxGraphicMessage graphicMessage = findByCode(code);
                    Map<String,String> article = new HashMap<>();
                    article.put("Url",graphicMessage.getUrl());
                    article.put("Title", graphicMessage.getTitle());
                    article.put("Description",graphicMessage.getDescription());
                    article.put("PicUrl",graphicMessage.getPicUrl());
                    articles.add(article);
                }
            }
            // 构建回复消息XML
            return replyNewsMessage(fromUserName, toUserName, articles);
        } catch (Exception e) {
            e.printStackTrace();
            return e.getMessage();
        }
    }
}

+ 167 - 15
svr/svr-base/src/main/java/com/yihu/jw/wx/service/WxMenuService.java

@ -4,13 +4,18 @@ import com.yihu.jw.mysql.query.BaseJpaService;
import com.yihu.jw.restmodel.common.CommonContants;
import com.yihu.jw.restmodel.exception.ApiException;
import com.yihu.jw.restmodel.wx.WxContants;
import com.yihu.jw.util.HttpUtil;
import com.yihu.jw.wx.dao.WxMenuDao;
import com.yihu.jw.wx.model.WxAccessToken;
import com.yihu.jw.wx.model.WxMenu;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import javax.persistence.Transient;
import java.util.ArrayList;
import java.util.List;
/**
 * Created by Administrator on 2017/5/19 0019.
@ -21,28 +26,27 @@ public class WxMenuService extends BaseJpaService<WxMenu, WxMenuDao> {
    @Autowired
    private WxMenuDao wxMenuDao;
    @Autowired
    private WxAccessTokenService wxAccessTokenService;
    /**
     * 将菜单保存至数据库(微信未创建)
     * @param wxMenu
     * @return
     */
    public WxMenu createWxMenu(WxMenu wxMenu) {
        if (StringUtils.isEmpty(wxMenu.getWechatCode())) {
            throw new ApiException(WxContants.WxMenu.message_fail_wechatCode_is_null, CommonContants.common_error_params_code);
        }
        if (StringUtils.isEmpty(wxMenu.getName())) {
            throw new ApiException(WxContants.WxMenu.message_fail_wxMenuName_is_null, CommonContants.common_error_params_code);
        if(canSaveOrUpata(wxMenu)){
            return wxMenuDao.save(wxMenu);
        }
        return wxMenuDao.save(wxMenu);
        return null;
    }
    @Transient
    public WxMenu updateWxMenu(WxMenu wxMenu) {
        if (StringUtils.isEmpty(wxMenu.getWechatCode())) {
            throw new ApiException(WxContants.WxMenu.message_fail_code_is_null, CommonContants.common_error_params_code);
        }
        if (StringUtils.isEmpty(wxMenu.getName())) {
            throw new ApiException(WxContants.WxMenu.message_fail_name_is_null, CommonContants.common_error_params_code);
        }
        if (StringUtils.isEmpty(wxMenu.getId())) {
            throw new ApiException(WxContants.WxMenu.message_fail_id_is_null, CommonContants.common_error_params_code);
        if(canSaveOrUpata(wxMenu)){
            return wxMenuDao.save(wxMenu);
        }
        return wxMenuDao.save(wxMenu);
        return null;
    }
    @Transient
@ -51,6 +55,16 @@ public class WxMenuService extends BaseJpaService<WxMenu, WxMenuDao> {
        if (wxMenu == null) {
            throw new ApiException(WxContants.WxMenu.message_fail_code_no_exist, CommonContants.common_error_params_code);
        }
        String supMenucode = wxMenu.getSupMenucode();
        if(StringUtils.isEmpty(supMenucode)) {//如果是空,则为父菜单
            List<WxMenu> childMenus = findChildMenus(wxMenu.getWechatCode(), wxMenu.getSupMenucode());
            if(childMenus!=null){
                for(WxMenu wxmenu:childMenus){
                    wxmenu.setStatus(-1);
                    wxMenuDao.save(wxmenu);
                }
            }
        }
        wxMenu.setStatus(-1);
        wxMenuDao.save(wxMenu);
    }
@ -58,4 +72,142 @@ public class WxMenuService extends BaseJpaService<WxMenu, WxMenuDao> {
    public WxMenu findByCode(String code) {
        return wxMenuDao.findByCode(code);
    }
    /**
     * 根据wechatCode查找所有菜单
     * @param wechatCode
     * @return
     */
    public List<WxMenu> findByWechatCode(String wechatCode){
        return wxMenuDao.findByWechatCode(wechatCode);
    }
    /**
     * 根据wechatCode在微信公众号创建菜单
     * @param wechatCode
     * @return JSONObject
     */
    public JSONObject createWechatMenu(String wechatCode) {
        //首先根据wechatCode获取菜单,然后封装成json字符串
        List<WxMenu> menus = wxMenuDao.findByWechatCode(wechatCode);
        String menuJsonString = getMenuToString(menus, wechatCode);
        WxAccessToken wxAccessTokenByCode = wxAccessTokenService.getWxAccessTokenByCode(wechatCode);
        String token = wxAccessTokenByCode.getAccessToken();
        // 请求微信接口创建菜单
        String url = " https://api.weixin.qq.com/cgi-bin/menu/create?access_token=" + token;
        String jsonStr = HttpUtil.sendPost(url, menuJsonString);
        JSONObject result = new JSONObject(jsonStr);
        return result;
    }
    private String getMenuToString(List<WxMenu> menus,String wechatCode){
        String menuJsonStr = "";
        List<WxMenu> parentMenus = new ArrayList<WxMenu>();//存储父菜单
        if(menus!=null){
            menuJsonStr = "{\"button\":[{";
            for(WxMenu wxMenu:menus){
                if(StringUtils.isEmpty(wxMenu.getSupMenucode())){//说明是父菜单
                    parentMenus.add(wxMenu);
                }
            }
        }
        int j = 0;
        for(WxMenu menu:parentMenus){//遍历父菜单
            if(j==0){
                j++;
            }else{
                menuJsonStr += ",{";
            }
            menuJsonStr = getString(menuJsonStr, menu);
            //查找是否有子菜单
            List<WxMenu> childMenus = findChildMenus(wechatCode, menu.getCode());
            if(childMenus!=null){
                int i =0;
                menuJsonStr += ",\"sub_button\":[{";
                for(WxMenu childMenu:childMenus){
                    if(i==0){
                        i++;
                    }else{
                        menuJsonStr += ",{";
                    }
                    menuJsonStr = getString(menuJsonStr, childMenu);
                    menuJsonStr += "}";
                }
                menuJsonStr += "]}";
            }
        }
        menuJsonStr += "]}";
        return menuJsonStr;
    }
    private String getString(String menuJsonStr, WxMenu menu) {
        menuJsonStr += "\"name\":\""+ menu.getName()+"\"";
        if(!StringUtils.isEmpty(menu.getType())){
            menuJsonStr += ",\"type\":\"" + menu.getType()+"\"";
        }
        if(!StringUtils.isEmpty(menu.getKey())){
            menuJsonStr += ",\"key\":\"" + menu.getKey()+"\"";
        }
        if(!StringUtils.isEmpty(menu.getUrl())){
            menuJsonStr += ",\"url\":\"" + menu.getUrl()+"\"";
        }
        if(!StringUtils.isEmpty(menu.getMediaId())){
            menuJsonStr += ",\"media_id\":\"" + menu.getMediaId()+"\"";
        }
        if(!StringUtils.isEmpty(menu.getAppid())){
            menuJsonStr += ",\"appid\":\"" + menu.getAppid()+"\"";
        }
        if(!StringUtils.isEmpty(menu.getPagepath())){
            menuJsonStr += ",\"pagepath\":\"" + menu.getPagepath()+"\"";
        }
        return menuJsonStr;
    }
    /**
     * 查找子菜单
     * @param wechatCode
     * @param sup_menucode
     * @return
     */
    public List<WxMenu> findChildMenus(String wechatCode,String sup_menucode ){
        return wxMenuDao.findChildMenus(wechatCode,sup_menucode);
    }
    private boolean canSaveOrUpata(WxMenu wxMenu){
        if (StringUtils.isEmpty(wxMenu.getCode())) {
            throw new ApiException(WxContants.WxMenu.message_fail_code_is_null, CommonContants.common_error_params_code);
        }
        if (StringUtils.isEmpty(wxMenu.getWechatCode())) {
            throw new ApiException(WxContants.WxMenu.message_fail_wechatCode_is_null, CommonContants.common_error_params_code);
        }
        if (StringUtils.isEmpty(wxMenu.getName())) {
            throw new ApiException(WxContants.WxMenu.message_fail_name_is_null, CommonContants.common_error_params_code);
        }
        if(StringUtils.isEmpty(wxMenu.getType())){
            throw new ApiException(WxContants.WxMenu.message_fail_type_is_null, CommonContants.common_error_params_code);
        }
        if("click".equals(wxMenu.getType().toUpperCase())){
            String key = wxMenu.getKey();
            if(StringUtils.isEmpty(key)){
                throw new ApiException(WxContants.WxMenu.message_fail_wxMenuKey_is_null, CommonContants.common_error_params_code);
            }
            if(key.length()>128){
                throw new ApiException(WxContants.WxMenu.message_fail_wxMenuKey_is_toLong, CommonContants.common_error_params_code);
            }
        }
        if(StringUtils.isEmpty(wxMenu.getSort())){
            throw new ApiException(WxContants.WxMenu.message_fail_sort_is_null, CommonContants.common_error_params_code);
        }
        WxMenu wxMenuTemp = null;
        if(StringUtils.isEmpty(wxMenu.getSupMenucode())){//如果是空,则为父菜单
            //判断sort是否重复
            wxMenuTemp = wxMenuDao.findByWechatCodeExcludeSortFromParent(wxMenu.getWechatCode(), wxMenu.getSort(),wxMenu.getCode());
        }else{//子菜单
            wxMenuTemp = wxMenuDao.findByWechatCodeExcludeSortFromChild(wxMenu.getWechatCode(), wxMenu.getSort(), wxMenu.getSupMenucode(), wxMenu.getCode());
        }
        if(null!=wxMenuTemp){
            throw new ApiException(WxContants.WxMenu.message_fail_sort_is_repeat, CommonContants.common_error_params_code);
        }
        return true;
    }
}

+ 78 - 4
svr/svr-base/src/main/java/com/yihu/jw/wx/service/WxTemplateService.java

@ -1,15 +1,21 @@
package com.yihu.jw.wx.service;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.yihu.jw.mysql.query.BaseJpaService;
import com.yihu.jw.restmodel.common.CommonContants;
import com.yihu.jw.restmodel.exception.ApiException;
import com.yihu.jw.restmodel.wx.WxContants;
import com.yihu.jw.util.HttpUtil;
import com.yihu.jw.wx.dao.WxTemplateDao;
import com.yihu.jw.wx.model.WxTemplate;
import com.yihu.jw.wx.model.*;
import org.json.JSONObject;
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.
 */
@ -19,6 +25,9 @@ public class WxTemplateService extends BaseJpaService<WxTemplate, WxTemplateDao>
    @Autowired
    private WxTemplateDao wxTemplateDao;
    @Autowired
    private WxAccessTokenService wxAccessTokenService;
    public WxTemplate createWxTemplate(WxTemplate wxTemplate) {
        if (StringUtils.isEmpty(wxTemplate.getCode())) {
@ -27,6 +36,16 @@ public class WxTemplateService extends BaseJpaService<WxTemplate, WxTemplateDao>
        if (StringUtils.isEmpty(wxTemplate.getWechatCode())) {
            throw new ApiException(WxContants.WxTemplate.message_fail_wechatCode_is_null, CommonContants.common_error_params_code);
        }
        if (StringUtils.isEmpty(wxTemplate.getTemplateId())) {
            throw new ApiException(WxContants.WxTemplate.message_fail_templateid_is_null, CommonContants.common_error_params_code);
        }
        String content = wxTemplate.getContent().replace(" ","");
        if (StringUtils.isEmpty(content)) {
            throw new ApiException(WxContants.WxTemplate.message_fail_content_is_null, CommonContants.common_error_params_code);
        }
        if(!content.matches("\\{\\{.+\\.DATA\\}\\}")){//content必须还有 "{{.DATA}}"
            throw new ApiException(WxContants.WxTemplate.message_fail_content_format_is_not_right, CommonContants.common_error_params_code);
        }
        return wxTemplateDao.save(wxTemplate);
    }
@ -37,11 +56,17 @@ public class WxTemplateService extends BaseJpaService<WxTemplate, WxTemplateDao>
        if (StringUtils.isEmpty(wxTemplate.getWechatCode())) {
            throw new ApiException(WxContants.WxTemplate.message_fail_wechatCode_is_null, CommonContants.common_error_params_code);
        }
        if (StringUtils.isEmpty(wxTemplate.getId())) {
            throw new ApiException(WxContants.WxTemplate.message_fail_id_is_null, CommonContants.common_error_params_code);
        if (StringUtils.isEmpty(wxTemplate.getTemplateId())) {
            throw new ApiException(WxContants.WxTemplate.message_fail_templateid_is_null, CommonContants.common_error_params_code);
        }
        String content = wxTemplate.getContent().replace(" ","");
        if (StringUtils.isEmpty(content)) {
            throw new ApiException(WxContants.WxTemplate.message_fail_content_is_null, CommonContants.common_error_params_code);
        }
        if(!content.matches("\\{\\{.+\\.DATA\\}\\}")){//content必须还有 "{{.DATA}}"
            throw new ApiException(WxContants.WxTemplate.message_fail_content_format_is_not_right, CommonContants.common_error_params_code);
        }
        return wxTemplateDao.save(wxTemplate);
    }
    public void deleteWxTemplate(String code) {
@ -61,4 +86,53 @@ public class WxTemplateService extends BaseJpaService<WxTemplate, WxTemplateDao>
        return wxTemplate;
    }
    public JSONObject sendTemplateMessage(String openid, String templateCode, String url, String data,Miniprogram miniprogram) {
        try {
            //首先根据wechatTemplate获取微信模版
            WxTemplate wxTemplate = findByCode(templateCode);
            String wechatCode =  wxTemplate.getWechatCode();
            String content = wxTemplate.getContent().replaceAll(" ", "");//{{result.DATA}}领奖金额:{{withdrawMoney.DATA}   }领奖  时间:{ {withdrawTime.DATA} }银行信息:{ {cardInfo.DATA} }到账时间:{{arrivedTime.DATA}}{{remark.DATA}}
            String[] contentArray = content.split("\\{\\{");
            //将result,withdrawMoney,withdrawTime,cardInfo,arrivedTime等字符串放入contentList中
            List<String> contentList = new ArrayList<>();
            for(int i=1;i<contentArray.length;i++){
                contentList.add(contentArray[i].substring(0,contentArray[i].indexOf(".")));
            }
            ObjectMapper mapper = new ObjectMapper();
            ////将data转为对象
            Map<String, WechatTemplateData> dataMap = mapper.readValue(data, new TypeReference<LinkedHashMap<String, WechatTemplateData>>() {});
            Map<String, WechatTemplateData> newDataMap = new LinkedHashMap<String, WechatTemplateData>();
            int j = 0;
            for (Map.Entry<String, WechatTemplateData> entry : dataMap.entrySet()) {//(keyword1,WechatTemplateData)
                String key = entry.getKey();//keyword1   转为result
                newDataMap.put(contentList.get(j),entry.getValue());
                j++;
            }
            //将数据封装在WechatTemplate对象中
            WechatTemplate wechatTemplate = new WechatTemplate();
            wechatTemplate.setTouser(openid);
            wechatTemplate.setUrl(url);
            wechatTemplate.setTemplate_id(wxTemplate.getTemplateId());
            if(miniprogram!=null){
                wechatTemplate.setMiniprogram(miniprogram);
            }
            wechatTemplate.setData(newDataMap);
            String params = mapper.writeValueAsString(wechatTemplate);
            WxAccessToken wxAccessTokenByCode = wxAccessTokenService.getWxAccessTokenByCode(wechatCode);
            String token = wxAccessTokenByCode.getAccessToken();
            String token_url = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=" + token;
            String result = HttpUtil.sendPost(token_url, params);
            JSONObject jsonResult = new JSONObject(result);
            return jsonResult;
        } catch (Exception e) {
            e.printStackTrace();
            JSONObject jsonResult = new JSONObject(e);
            return jsonResult;
        }
    }
}

+ 105 - 0
web-gateway/src/main/java/com/yihu/jw/controller/base/wx/WechatController.java

@ -0,0 +1,105 @@
package com.yihu.jw.controller.base.wx;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty;
import com.yihu.jw.fegin.base.wx.WechatFegin;
import com.yihu.jw.restmodel.common.Envelop;
import com.yihu.jw.restmodel.wx.WxContants;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.sleuth.Tracer;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@RestController
@Api(description = "微信配置")
public class WechatController{
    private Logger logger= LoggerFactory.getLogger(WechatController.class);
    @Autowired
    private WechatFegin wechatFegin;
    @Autowired
    private Tracer tracer;
    @ApiOperation(value = "创建微信配置")
    @PostMapping(value = "/"+WxContants.Wechat.api_common+"/"+WxContants.Wechat.api_create)
    @HystrixCommand(commandProperties = {
            @HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds", value = "-1"),//超时时间
            @HystrixProperty(name = "execution.timeout.enabled", value = "false") })
    public Envelop createWechat(
            @ApiParam(name = "json_data", value = "", defaultValue = "") @RequestBody String jsonData) {
        tracer.getCurrentSpan().logEvent("开始调用微服务创建微信配置");
        Envelop wechat =wechatFegin.createWechat(jsonData);
        tracer.getCurrentSpan().logEvent("创建微信配置微服务结束");
        return wechat;
    }
    @ApiOperation(value = "更新微信配置")
    @PutMapping(value = "/"+WxContants.Wechat.api_common+"/"+WxContants.Wechat.api_update)
    @HystrixCommand(commandProperties = {
            @HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds", value = "-1"),//超时时间
            @HystrixProperty(name = "execution.timeout.enabled", value = "false") })
    public Envelop updateWechat(
            @ApiParam(name = "json_data", value = "", defaultValue = "")
            @RequestBody String jsonData) {
        Envelop wechat =wechatFegin.updateWechat(jsonData);
        return wechat;
    }
    @DeleteMapping(value = "/"+WxContants.Wechat.api_common+"/"+WxContants.Wechat.api_delete)
    @ApiOperation(value = "删除微信配置", notes = "删除微信配置")
    public Envelop deleteWechat(
            @ApiParam(name = "code", value = "code")
            @RequestParam(value = "code", required = true) String code) {
        Envelop wechat =wechatFegin.deleteWechat(code);
        return wechat;
    }
    @GetMapping(value = "/"+WxContants.Wechat.api_common+"/"+WxContants.Wechat.api_getByCode)
    @ApiOperation(value = "根据code查找微信配置", notes = "根据code查找微信配置")
    public Envelop findByCode(
            @ApiParam(name = "code", value = "code")
            @RequestParam(value = "code", required = true) String code
    ) {
       return wechatFegin.findByCode(code);
    }
    @RequestMapping(value = "/"+WxContants.Wechat.api_common+"/"+WxContants.Wechat.api_getWechats, method = RequestMethod.GET)
    @ApiOperation(value = "获取微信配置列表(分页)")
    public Envelop getWechats(
            @ApiParam(name = "fields", value = "返回的字段,为空返回全部字段", defaultValue = "id,code,name,saasId,appId,appSecret,baseUrl,remark")
            @RequestParam(value = "fields", required = false) String fields,
            @ApiParam(name = "filters", value = "过滤器,为空检索所有条件")
            @RequestParam(value = "filters", required = false) String filters,
            @ApiParam(name = "sorts", value = "排序,规则参见说明文档", defaultValue = "+name,+createTime")
            @RequestParam(value = "sorts", required = false) String sorts,
            @ApiParam(name = "size", value = "分页大小", defaultValue = "15")
            @RequestParam(value = "size", required = false) int size,
            @ApiParam(name = "page", value = "页码", defaultValue = "1")
            @RequestParam(value = "page", required = false) int page,
            HttpServletRequest request,
            HttpServletResponse response) throws Exception {
        Envelop envelop = wechatFegin.getWechats(fields,filters,sorts,size,page);
        return envelop;
    }
    @GetMapping(value = "/"+WxContants.Wechat.api_common+"/"+WxContants.Wechat.api_getWechatNoPage)
    @ApiOperation(value = "获取微信列表配置,不分页")
    public Envelop getWechatNoPage(
            @ApiParam(name = "fields", value = "返回的字段,为空返回全部字段", defaultValue = "id,code,name,saasId,appId,appSecret,baseUrl,remark")
            @RequestParam(value = "fields", required = false) String fields,
            @ApiParam(name = "filters", value = "过滤器,为空检索所有条件")
            @RequestParam(value = "filters", required = false) String filters,
            @ApiParam(name = "sorts", value = "排序,规则参见说明文档", defaultValue = "+name,+createTime")
            @RequestParam(value = "sorts", required = false) String sorts) throws Exception {
        return wechatFegin.getWechatNoPage(fields,filters,sorts);
    }
}

+ 37 - 0
web-gateway/src/main/java/com/yihu/jw/fegin/base/wx/WechatFegin.java

@ -0,0 +1,37 @@
package com.yihu.jw.fegin.base.wx;
import com.yihu.jw.fegin.fallbackfactory.base.wx.WechatFeginFallbackFactory;
import com.yihu.jw.restmodel.common.CommonContants;
import com.yihu.jw.restmodel.common.Envelop;
import com.yihu.jw.restmodel.wx.WxContants;
import org.springframework.cloud.netflix.feign.FeignClient;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
@FeignClient(
        name = CommonContants.svr_base // name值是eurika的实例名字
        ,fallbackFactory  = WechatFeginFallbackFactory.class
)
@RequestMapping(value = WxContants.Wechat.api_common)
public interface WechatFegin {
    @RequestMapping(value = WxContants.Wechat.api_create, method = RequestMethod.POST)
    Envelop createWechat( @RequestBody String jsonData);
    @RequestMapping(value = WxContants.Wechat.api_update, method = RequestMethod.PUT)
    Envelop updateWechat(String jsonData);
    @RequestMapping(value = WxContants.Wechat.api_delete,method = RequestMethod.DELETE)
    Envelop deleteWechat(String code);
    @RequestMapping(value = WxContants.Wechat.api_getByCode,method = RequestMethod.GET)
    Envelop findByCode(String code);
    @RequestMapping(value = WxContants.Wechat.api_getWechats ,method = RequestMethod.GET)
    Envelop getWechats(String fields, String filters, String sorts, int page, int size);
    @RequestMapping(value = WxContants.Wechat.api_getWechatNoPage,method = RequestMethod.GET )
    Envelop getWechatNoPage(String fields, String filters, String sorts);
}

+ 22 - 0
web-gateway/src/main/java/com/yihu/jw/fegin/fallback/base/wx/WechatFeginFallback.java

@ -0,0 +1,22 @@
package com.yihu.jw.fegin.fallback.base.wx;
import com.yihu.jw.fegin.PatientFegin;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestParam;
/**
 * Created by chenweida on 2017/5/13.
 */
@Component
public class WechatFeginFallback implements PatientFegin {
    private Logger logger = LoggerFactory.getLogger(WechatFeginFallback.class);
    @Override
    public String findByCode( @RequestParam(value = "code", required = true) String code) {
        logger.info("进入断路器");
        return "断路器启动";
    }
}

+ 48 - 0
web-gateway/src/main/java/com/yihu/jw/fegin/fallbackfactory/base/wx/WechatFeginFallbackFactory.java

@ -0,0 +1,48 @@
package com.yihu.jw.fegin.fallbackfactory.base.wx;
import com.yihu.jw.fegin.base.wx.WechatFegin;
import com.yihu.jw.restmodel.common.Envelop;
import feign.hystrix.FallbackFactory;
import org.springframework.stereotype.Component;
@Component
public class WechatFeginFallbackFactory implements FallbackFactory<WechatFegin> {
    @Override
    public WechatFegin create(Throwable e) {
        return new WechatFegin() {
            public Envelop createWechat(String jsonData) {
                Envelop envelop = new Envelop();
                envelop.getError(e.getMessage(),-1);
                return envelop;
            }
            public Envelop updateWechat(String jsonData) {
                Envelop envelop = new Envelop();
                envelop.getError(e.getMessage(),-1);
                return envelop;
            }
            public Envelop deleteWechat(String code){
                Envelop envelop = new Envelop();
                envelop.getError(e.getMessage(),-1);
                return envelop;
            }
            public Envelop findByCode(String code){
                Envelop envelop = new Envelop();
                envelop.getError(e.getMessage(),-1);
                return envelop;
            }
            public Envelop getWechats(String fields, String filters, String sorts, int page, int size){
                Envelop envelop = new Envelop();
                envelop.getError(e.getMessage(),-1);
                return envelop;
            }
            public Envelop getWechatNoPage(String fields, String filters, String sorts){
                Envelop envelop = new Envelop();
                envelop.getError(e.getMessage(),-1);
                return envelop;
            }
        };
    }
}