JAVA微信公众号网页开发——通过接收人的openid发送模板消息
TemplateData.java
1 package com.weixin.weixin.template;
2
3 public class TemplateData {
4 private String value; //值
5 private String color; //展示的颜色
6
7 public String getValue() {
8 return value;
9 }
10
11 public void setValue(String value) {
12 this.value = value;
13 }
14
15 public String getColor() {
16 return color;
17 }
18
19 public void setColor(String color) {
20 this.color = color;
21 }
22 }
WechatTemplate.java
1 package com.weixin.weixin.template;
2
3 import java.util.Map;
4
5 public class WechatTemplate {
6 private String touser; //接收人
7
8 private String template_id; //模板id
9
10 private String url; //跳转的url
11
12 private Map<String, TemplateData> data; //内容中的参数数据
13
14 public String getTouser() {
15 return touser;
16 }
17
18 public void setTouser(String touser) {
19 this.touser = touser;
20 }
21
22 public String getTemplate_id() {
23 return template_id;
24 }
25
26 public void setTemplate_id(String template_id) {
27 this.template_id = template_id;
28 }
29
30 public String getUrl() {
31 return url;
32 }
33
34 public void setUrl(String url) {
35 this.url = url;
36 }
37
38 public Map<String, TemplateData> getData() {
39 return data;
40 }
41
42 public void setData(Map<String, TemplateData> data) {
43 this.data = data;
44 }
45 }
控制器类
TemplateMsgAct.java
1 package com.weixin.weixin.template;
2
3 import com.weixin.weixin.template.TemplateData;
4 import com.weixin.weixin.template.WechatTemplate;
5 import org.apache.commons.lang.StringUtils;
6 import org.apache.http.HttpEntity;
7 import org.apache.http.HttpResponse;
8 import org.apache.http.StatusLine;
9 import org.apache.http.client.ClientProtocolException;
10 import org.apache.http.client.HttpClient;
11 import org.apache.http.client.HttpResponseException;
12 import org.apache.http.client.ResponseHandler;
13 import org.apache.http.client.methods.HttpGet;
14 import org.apache.http.client.methods.HttpPost;
15 import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
16 import org.apache.http.entity.StringEntity;
17 import org.apache.http.impl.client.CloseableHttpClient;
18 import org.apache.http.impl.client.HttpClientBuilder;
19 import org.apache.http.impl.client.HttpClients;
20 import org.apache.http.util.EntityUtils;
21 import org.json.JSONException;
22 import org.json.JSONObject;
23 import org.springframework.stereotype.Controller;
24 import org.springframework.web.bind.annotation.RequestMapping;
25
26 import javax.net.ssl.SSLContext;
27 import javax.net.ssl.TrustManager;
28 import javax.net.ssl.X509TrustManager;
29 import java.io.IOException;
30 import java.net.URI;
31 import java.security.cert.CertificateException;
32 import java.security.cert.X509Certificate;
33 import java.util.HashMap;
34 import java.util.Map;
35
36 @Controller
37 public class TemplateMsgAct {
38
39 /**
40 * 发送模板消息
41 *官方文档地址:https://developers.weixin.qq.com/doc/offiaccount/Message_Management/Template_Message_Interface.html#5
42 */
43 @RequestMapping("/send_template_msg.do")
44 public void sendTemplateMsg() {
45 String token = getToken();//获取access_token
46 String sendUrl = "https://api.weixin.qq.com/cgi-bin/message/template/send"; //微信提供的发送接口地址
47 String url = sendUrl + "?access_token=" + token;
48
49 //封装模板消息数据内容
50 try {
51
52 WechatTemplate wechatTemplate = new WechatTemplate();
53 //模板id
54 wechatTemplate.setTemplate_id("pYD-hJo7VwjQkoLXAcPeU3MignN0");
55 //接收人的openid
56 wechatTemplate.setTouser("okE7QwU7QRCBqBxTvP0");
57 //点击模板跳转的链接
58 wechatTemplate.setUrl("https://www.baidu.com")
59 Map<String, TemplateData> mapdata = new HashMap<String, TemplateData>();
60 // 封装模板数据
61 TemplateData first = new TemplateData();
62 first.setValue("{{first.DATA}}值");
63 first.setColor("#173177");
64 mapdata.put("first", first);
65
66 TemplateData keyword1 = new TemplateData();
67 keyword1.setValue("{{keyword1.DATA}}值");
68 first.setColor("#173177");
69 mapdata.put("keyword1", keyword1);
70
71 TemplateData keyword2 = new TemplateData();
72 keyword2.setValue("{{keyword2.DATA}}值");
73 first.setColor("#173177");
74 mapdata.put("keyword2", keyword2);
75
76 TemplateData keyword3 = new TemplateData();
77 keyword3.setValue("{{keyword3.DATA}}值");
78 keyword3.setColor("#173177");
79 mapdata.put("keyword3", keyword3);
80
81 TemplateData remark = new TemplateData();
82 remark.setValue("{{remark.DATA}}值");
83 remark.setColor("#173177");
84 mapdata.put("remark", remark);
85
86 wechatTemplate.setData(mapdata);
87 net.sf.json.JSONObject object= net.sf.json.JSONObject.fromObject(wechatTemplate);
88
89 post(url, object.toString(), "application/json");
90
91 } catch (Exception e) {
92 e.printStackTrace();
93 }
94
95 }
96
97
98 private String post(String url, String json, String contentType) {
99 HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
100 //HttpClient
101 CloseableHttpClient client = httpClientBuilder.build();
102 client = (CloseableHttpClient) wrapClient(client);
103 HttpPost post = new HttpPost(url);
104 try {
105 StringEntity s = new StringEntity(json, "utf-8");
106 if (StringUtils.isBlank(contentType)) {
107 s.setContentType("application/json");
108 }
109 s.setContentType(contentType);
110 post.setEntity(s);
111 HttpResponse res = client.execute(post);
112 HttpEntity entity = res.getEntity();
113 String str = EntityUtils.toString(entity, "utf-8");
114 return str;
115 } catch (Exception e) {
116 e.printStackTrace();
117 }
118 return null;
119 }
120
121 private String filterCharacters(String txt) {
122 if (StringUtils.isNotBlank(txt)) {
123 txt = txt.replace("“", "“").replace("”", "”").replace(" ", " ");
124 }
125 return txt;
126 }
127
128 private static HttpClient wrapClient(HttpClient base) {
129 try {
130 SSLContext ctx = SSLContext.getInstance("TLSv1");
131 X509TrustManager tm = new X509TrustManager() {
132 public void checkClientTrusted(X509Certificate[] xcs,
133 String string) throws CertificateException {
134 }
135
136 public void checkServerTrusted(X509Certificate[] xcs,
137 String string) throws CertificateException {
138 }
139
140 public X509Certificate[] getAcceptedIssuers() {
141 return null;
142 }
143 };
144 ctx.init(null, new TrustManager[]{tm}, null);
145 SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(ctx, new String[]{"TLSv1"}, null,
146 SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);
147 CloseableHttpClient httpclient = HttpClients.custom().setSSLSocketFactory(sslsf).build();
148 return httpclient;
149
150 } catch (Exception ex) {
151 return null;
152 }
153 }
154
155 public class CharsetHandler implements ResponseHandler<String> {
156 private String charset;
157
158 public CharsetHandler(String charset) {
159 this.charset = charset;
160 }
161
162 public String handleResponse(HttpResponse response)
163 throws ClientProtocolException, IOException {
164 StatusLine statusLine = response.getStatusLine();
165 if (statusLine.getStatusCode() >= 300) {
166 throw new HttpResponseException(statusLine.getStatusCode(),
167 statusLine.getReasonPhrase());
168 }
169 HttpEntity entity = response.getEntity();
170 if (entity != null) {
171 if (!StringUtils.isBlank(charset)) {
172 return EntityUtils.toString(entity, charset);
173 } else {
174 return EntityUtils.toString(entity);
175 }
176 } else {
177 return null;
178 }
179 }
180 }
181
182 /**
183 * 获取access_token
184 * @return
185 */
186 public String getToken() {
187 String tokenGetUrl="https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential";//微信提供获取access_token接口地址
188 String appid=""; //公众号的apppId
189 String secret=""; //公众号的appsecert
190
191 System.out.println("~~~~~appid:"+appid);
192 System.out.println("~~~~~secret:"+secret);
193 JSONObject tokenJson=new JSONObject();
194 if(StringUtils.isNotBlank(appid)&&StringUtils.isNotBlank(secret)){
195 tokenGetUrl+="&appid="+appid+"&secret="+secret;
196 tokenJson=getUrlResponse(tokenGetUrl);
197 System.out.println("~~~~~tokenJson:"+tokenJson.toString());
198 try {
199 return (String) tokenJson.get("access_token");
200 } catch (JSONException e) {
201 System.out.println("报错了");
202 return null;
203 }
204 }else{
205 System.out.println("appid和secret为空");
206 return null;
207 }
208 }
209
210 private JSONObject getUrlResponse(String url){
211 CharsetHandler handler = new CharsetHandler("UTF-8");
212 try {
213 HttpGet httpget = new HttpGet(new URI(url));
214 HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
215 //HttpClient
216 CloseableHttpClient client = httpClientBuilder.build();
217 client = (CloseableHttpClient) wrapClient(client);
218 return new JSONObject(client.execute(httpget, handler));
219 } catch (Exception e) {
220 e.printStackTrace();
221 return null;
222 }
223 }
224
225 }
JAVA微信公众号网页开发——通过接收人的openid发送模板消息的更多相关文章
- JAVA微信公众号网页开发 —— 用户授权获取openid
官方文档:https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1421140842 HttpClientUtil.java packa ...
- JAVA微信公众号网页开发——获取公众号关注的所有用户(微信公众号粉丝)
package com.weixin.sendmessage; import org.apache.commons.lang.StringUtils; import org.apache.http.H ...
- JAVA微信公众号网页开发——将接收的消息转发到微信自带的客服系统
如果公众号处于开发模式,普通微信用户向公众号发消息时,微信服务器会先将消息POST到开发者填写的url上,无法直接推送给微信自带的客服功能.如果需要把用户推送的普通消息推送到客服功能中,就需要进行代码 ...
- JAVA微信公众号网页开发 —— 接收微信服务器发送的消息
WeixinMessage.java package com.test; import java.io.Serializable; /** * This is an object that conta ...
- JAVA微信公众号网页开发——生成自定义微信菜单(携带参数)
官网接口地址:https://developers.weixin.qq.com/doc/offiaccount/Custom_Menus/Creating_Custom-Defined_Menu.ht ...
- JAVA微信公众号网页开发——将文章群发到微信公众号中(文章使用富文本,包含图片)
SendTextToAllUserAct.java package com.weixin.sendmessage; import org.apache.commons.lang.StringUtils ...
- 微信公众号网页开发-jssdk config配置参数生成(Java版)
一.配置参数 参考官方文档:http://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1421141115&token=&la ...
- C#开发微信公众号——网页开发之微信网页授权
首先咱们先看下公众号的文档里面的介绍 上述图片的文字描述就是讲述了网页授权有什么用,就是为了获取微信用户的基本信息:授权回调域名的规范,说到域名回调的事情就不得不提一下设置网页授权域名 最好将这三个域 ...
- 微信公众号支付开发全过程 --JAVA
按照惯例,开头总得写点感想 ------------------------------------------------------------------ 业务流程 这个微信官网说的还是很详细的 ...
随机推荐
- azkaban执行任务长时间无法结束
问题显示: 由于一次执行较多的任务,导致azkaban的web程序崩溃,此时,关闭azkaban服务,重新启动azkaban 但是由于azkaban的exec程序无法关闭,这里采用kill的方式关掉e ...
- Linux 安装和使用 RAR工具
RAR 安装 方法一.通过apt命令安装 rar 和 unrar 未安装 unrar 的情况下,提取 RAR 文件会报出"未能提取"错误 Ubuntu 安装 rar和 unrar( ...
- 【GS模型】使用R包sommer进行基因组选择的GBLUP和RRBLUP分析?
目录 简介 GS示例代码 简介 R包sommer内置了C++,运算速度还是比较快的,功能也很丰富,可求解各种复杂模型.语法相比于lme4包也要好懂一些. 建议查看文档:vignette("v ...
- Genscan指南
Genscan指南 GenScan是一个gene识别软件,主要是通过已知生物的基因结构特征来识别新的基因(parse).所利用的基因特征请参看readme文件. 特点: 只考虑编码蛋白的基因. 模型考 ...
- Linux-设置终端界面的字体颜色和自定义常用快捷功能
.bashrc是一个隐藏的文件,要打开并修改该文件需要: (0)命令:cd ~ (1)命令:ls -a 找到文件 .bashrc: (2) 命令 vim ~/.bashrc 进入到文件: (3) 直接 ...
- 搭建zabbix服务器常见问题解析处理
1. 找不到url 2. 服务器无法处理当前请求,PHP解析出错 3. 服务器无法处理当前请求,权限不足 1. 找不到url 浏览器报错:The requested URL /zabbix/ was ...
- 基于python win32setpixel api 实现计算机图形学相关操作
最近读研期间上了计算机可视化的课,老师也对计算机图形学的实现布置了相关的作业.虽然我没有系统地学过图形可视化的课,但是我之前逆向过一些游戏引擎,除了保护驱动之外,因为要做透视,接触过一些计算机图形学的 ...
- day01互联网架构理论
- day04 Linux基础命令
day04 Linux基础命令 查看帮助信息命令 1.man命令:man命令的功能是查看指定命令的详细解释. 格式:man [具体需要被查看的命令] [root@localhost ~]# man r ...
- SpringCloud微服务实战——搭建企业级开发框架(三十二):代码生成器使用配置说明
一.新建数据源配置 因考虑到多数据源问题,代码生成器作为一个通用的模块,后续可能会为其他工程生成代码,所以,这里不直接读取系统工程配置的数据源,而是让用户自己维护. 参数说明 数据源名称:用于查找区分 ...