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
按照惯例,开头总得写点感想 ------------------------------------------------------------------ 业务流程 这个微信官网说的还是很详细的 ...
随机推荐
- [SCOI2009] windy 数 (数位dp)
题目 算法 应该是一道很经典的数位dp题 我们设dp[i][j]是填到第i位此时第i位的数是j的方案数 然后进行转移(代码注释) 代码 #include<iostream> #includ ...
- 51nod 1709 复杂度分析
51nod 1709 复杂度分析 考虑定义 $ F(x) $ 为 \(x\) 为根的子树所有点与 $ x $ 的深度差(其实就是 $ x $ 到每个子树内点的距离)的 1 的个数和. 注意,$ F(x ...
- [R]在dplyr基础上编写函数-(2)substitute和quote
关于这两个函数,官方是这么定义的: substitute returns the parse tree for the (unevaluated) expression expr, substitut ...
- PHP非对称加密-RSA
对称加密算法是在加密和解密时使用同一个密钥.与对称加密算法不同,非对称加密算法需要两个密钥--公开密钥(public key)和私有密钥(private key)进行加密和解密.公钥和密钥是一对,如果 ...
- 《手把手教你》系列技巧篇(四十六)-java+ selenium自动化测试-web页面定位toast-下篇(详解教程)
1.简介 终于经过宏哥的不懈努力,偶然发现了一个toast的web页面,所以直接就用这个页面来夯实一下,上一篇学过的知识-处理toast元素. 2.安居客 事先声明啊,宏哥没有收他们的广告费啊,纯粹是 ...
- UE4打包启动失败:RunUAT.bat ERROR: AutomationTool failed to compile.
打包配置正常的情况下,出现下面Log: RunUAT.bat ERROR: AutomationTool failed to compile. 基本上,可以先排查下任务管理器中是不是有UE4Edito ...
- 【模板】二分图最大权完美匹配(KM算法)/洛谷P6577
题目链接 https://www.luogu.com.cn/problem/P6577 题目大意 给定一个二分图,其左右点的个数各为 \(n\),带权边数为 \(m\),保证存在完美匹配. 求一种完美 ...
- day13 grep命令
day13 grep命令 linux三剑客之grep命令 介绍 grep(global search regular expression(RE) and print out the line,全面搜 ...
- MyBatis(4):使用limit实现分页
用limit实现分页,首先要创建一个Maven项目,搭建好mybatis的实验环境,并且连接好数据库 代码 1,编写dao接口 UserMapper //查询全部用户实现分页 List<User ...
- 【Java多线程】CompletionService
什么是CompletionService? 当我们使用ExecutorService启动多个Callable时,每个Callable返回一个Future,而当我们执行Future的get方法获取结果时 ...