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 }

 

posted @ 2019-11-13 13:31  yvioo  阅读(774)  评论(0编辑  收藏  举报