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
按照惯例,开头总得写点感想 ------------------------------------------------------------------ 业务流程 这个微信官网说的还是很详细的 ...
随机推荐
- CF1575G GCD Festival
\(\sum\sum gcd(i,j) \times gcd(a_i,a_j)\) 考虑枚举这个 \(gcd(i,j)\) . \(\sum_d \varphi(d)\sum_{i|d}\sum_{j ...
- 贪心/构造/DP 杂题选做
本博客将会收录一些贪心/构造的我认为较有价值的题目,这样可以有效的避免日后碰到 P7115 或者 P7915 这样的题就束手无策进而垫底的情况/dk 某些题目虽然跟贪心关系不大,但是在 CF 上有个 ...
- 【BZOJ 4668 冷战】
题目: [BZOJ 4668 冷战] 思路: 因为考虑强制在线,我们是肯定要维护形状的 我们发现如果\((u,v)\)这条边如果\(u,v\)已经连上,那么对于最终答案这条边是没有贡献的 所以我们发现 ...
- VS调用别人的COM组件的问题
调用第三方的COM组件,记得要先在管理员cmd执行:regsvr32 xxxx.dll 没执行之前运行 HRESULT hr = pComm.CreateInstance("xxxx.Com ...
- Anaconda 镜像配置
镜像源 清华大学: https://mirrors.tuna.tsinghua.edu.cn/help/anaconda/ 北京外国语大学: https://mirrors.bfsu.edu.cn/h ...
- plyr包使用
#-------------------------------- # plyr包使用# 建议直接保存为R文件到Rstudio中运行 #-------------------------------- ...
- 半主机模式和_MICROLIB 库
半主机是这么一种机制,它使得在ARM目标上跑的代码,如果主机电脑运行了调试器,那么该代码可以使用该主机电脑的输入输出设备. 这点非常重要,因为开发初期,可能开发者根本不知道该 ARM 器件上有什么 ...
- 26-Palindrome Number
回文数的判定,不使用额外的空间 Determine whether an integer is a palindrome. Do this without extra space. 思路:将一个整数逆 ...
- 1.TwoSum-Leetcode
#include<iostream> #include<algorithm> #include<map> using namespace std; class So ...
- Hadoop入门 运行环境搭建
模板虚拟机 目录 模板虚拟机 1 硬件 2 操作系统 3 IP地址和主机名称 vm windows10 Hadoop100服务器 远程访问工具 其他准备 克隆虚拟机 克隆 修改主机名/ip 安装jdk ...