zoukankan      html  css  js  c++  java
  • JAVA微信公众号网页开发——通过接收人的openid发送模板消息

    TemplateData.java
    package com.weixin.weixin.template;
    
    public class TemplateData {
        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;
        }
    }
    

      

    WechatTemplate.java
    package com.weixin.weixin.template;
    
    import java.util.Map;
    
    public class WechatTemplate {
        private String touser; //接收人
    
        private String template_id;  //模板id
    
        private String url;  //跳转的url
    
        private Map<String, TemplateData> data; //内容中的参数数据
    
        public String getTouser() {
            return touser;
        }
    
        public void setTouser(String touser) {
            this.touser = touser;
        }
    
        public String getTemplate_id() {
            return template_id;
        }
    
        public void setTemplate_id(String template_id) {
            this.template_id = template_id;
        }
    
        public String getUrl() {
            return url;
        }
    
        public void setUrl(String url) {
            this.url = url;
        }
    
        public Map<String, TemplateData> getData() {
            return data;
        }
    
        public void setData(Map<String, TemplateData> data) {
            this.data = data;
        }
    }
    

      

    控制器类

    templateMsgAct.java
    package com.weixin.weixin.template;
    
    import com.weixin.weixin.template.TemplateData;
    import com.weixin.weixin.template.WechatTemplate;
    import org.apache.commons.lang.StringUtils;
    import org.apache.http.HttpEntity;
    import org.apache.http.HttpResponse;
    import org.apache.http.StatusLine;
    import org.apache.http.client.ClientProtocolException;
    import org.apache.http.client.HttpClient;
    import org.apache.http.client.HttpResponseException;
    import org.apache.http.client.ResponseHandler;
    import org.apache.http.client.methods.HttpGet;
    import org.apache.http.client.methods.HttpPost;
    import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
    import org.apache.http.entity.StringEntity;
    import org.apache.http.impl.client.CloseableHttpClient;
    import org.apache.http.impl.client.HttpClientBuilder;
    import org.apache.http.impl.client.HttpClients;
    import org.apache.http.util.EntityUtils;
    import org.json.JSONException;
    import org.json.JSONObject;
    import org.springframework.stereotype.Controller;
    import org.springframework.web.bind.annotation.RequestMapping;
    
    import javax.net.ssl.SSLContext;
    import javax.net.ssl.TrustManager;
    import javax.net.ssl.X509TrustManager;
    import java.io.IOException;
    import java.net.URI;
    import java.security.cert.CertificateException;
    import java.security.cert.X509Certificate;
    import java.util.HashMap;
    import java.util.Map;
    
    @Controller
    public class templateMsgAct {
    
        /**
         * 发送模板消息
         *官方文档地址:https://developers.weixin.qq.com/doc/offiaccount/Message_Management/Template_Message_Interface.html#5
         */
        @RequestMapping("/send_template_msg.do")
        public void sendTemplateMsg() {
            String token = getToken();//获取access_token
            String createMenuUrl = "https://api.weixin.qq.com/cgi-bin/message/template/send"; //微信提供的发送接口地址
            String url = createMenuUrl + "?access_token=" + token;
    
            //封装模板消息数据内容
            try {
    
                WechatTemplate wechatTemplate = new WechatTemplate();
                //模板id
                wechatTemplate.setTemplate_id("pYD-hJo7VwjQkoLXAcPeU3MignN0");
                //接收人的openid
                wechatTemplate.setTouser("okE7QwU7QRCBqBxTvP0");           
                //点击模板跳转的链接            
                wechatTemplate.setUrl("https://www.baidu.com")
                Map<String, TemplateData> mapdata = new HashMap<String, TemplateData>();
                // 封装模板数据
                TemplateData first = new TemplateData();
                first.setValue("{{first.DATA}}值");
                first.setColor("#173177");
                mapdata.put("first", first);
    
                TemplateData keyword1 = new TemplateData();
                keyword1.setValue("{{keyword1.DATA}}值");
                first.setColor("#173177");
                mapdata.put("keyword1", keyword1);
    
                TemplateData keyword2 = new TemplateData();
                keyword2.setValue("{{keyword2.DATA}}值");
                first.setColor("#173177");
                mapdata.put("keyword2", keyword2);
    
                TemplateData keyword3 = new TemplateData();
                keyword3.setValue("{{keyword3.DATA}}值");
                keyword3.setColor("#173177");
                mapdata.put("keyword3", keyword3);
    
                TemplateData remark = new TemplateData();
                remark.setValue("{{remark.DATA}}值");
                remark.setColor("#173177");
                mapdata.put("remark", remark);
    
                wechatTemplate.setData(mapdata);
                net.sf.json.JSONObject object= net.sf.json.JSONObject.fromObject(wechatTemplate);
    
                post(url, object.toString(), "application/json");
    
            } catch (Exception e) {
                e.printStackTrace();
            }
    
        }
    
    
        private String post(String url, String json, String contentType) {
            HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
            //HttpClient
            CloseableHttpClient client = httpClientBuilder.build();
            client = (CloseableHttpClient) wrapClient(client);
            HttpPost post = new HttpPost(url);
            try {
                StringEntity s = new StringEntity(json, "utf-8");
                if (StringUtils.isBlank(contentType)) {
                    s.setContentType("application/json");
                }
                s.setContentType(contentType);
                post.setEntity(s);
                HttpResponse res = client.execute(post);
                HttpEntity entity = res.getEntity();
                String str = EntityUtils.toString(entity, "utf-8");
                return str;
            } catch (Exception e) {
                e.printStackTrace();
            }
            return null;
        }
    
        private String filterCharacters(String txt) {
            if (StringUtils.isNotBlank(txt)) {
                txt = txt.replace("“", "“").replace("”", "”").replace(" ", " ");
            }
            return txt;
        }
    
        private static HttpClient wrapClient(HttpClient base) {
            try {
                SSLContext ctx = SSLContext.getInstance("TLSv1");
                X509TrustManager tm = new X509TrustManager() {
                    public void checkClientTrusted(X509Certificate[] xcs,
                                                   String string) throws CertificateException {
                    }
    
                    public void checkServerTrusted(X509Certificate[] xcs,
                                                   String string) throws CertificateException {
                    }
    
                    public X509Certificate[] getAcceptedIssuers() {
                        return null;
                    }
                };
                ctx.init(null, new TrustManager[]{tm}, null);
                SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(ctx, new String[]{"TLSv1"}, null,
                        SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);
                CloseableHttpClient httpclient = HttpClients.custom().setSSLSocketFactory(sslsf).build();
                return httpclient;
    
            } catch (Exception ex) {
                return null;
            }
        }
    
        public class CharsetHandler implements ResponseHandler<String> {
            private String charset;
    
            public CharsetHandler(String charset) {
                this.charset = charset;
            }
    
            public String handleResponse(HttpResponse response)
                    throws ClientProtocolException, IOException {
                StatusLine statusLine = response.getStatusLine();
                if (statusLine.getStatusCode() >= 300) {
                    throw new HttpResponseException(statusLine.getStatusCode(),
                            statusLine.getReasonPhrase());
                }
                HttpEntity entity = response.getEntity();
                if (entity != null) {
                    if (!StringUtils.isBlank(charset)) {
                        return EntityUtils.toString(entity, charset);
                    } else {
                        return EntityUtils.toString(entity);
                    }
                } else {
                    return null;
                }
            }
        }
    
        /**
         * 获取access_token
         * @return
         */
        public String getToken() {
            String tokenGetUrl="https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential";//微信提供获取access_token接口地址
            String appid="";
            String secret="";
    
            System.out.println("~~~~~appid:"+appid);
            System.out.println("~~~~~secret:"+secret);
            JSONObject tokenJson=new JSONObject();
            if(StringUtils.isNotBlank(appid)&&StringUtils.isNotBlank(secret)){
                tokenGetUrl+="&appid="+appid+"&secret="+secret;
                tokenJson=getUrlResponse(tokenGetUrl);
                System.out.println("~~~~~tokenJson:"+tokenJson.toString());
                try {
                    return (String) tokenJson.get("access_token");
                } catch (JSONException e) {
                    System.out.println("报错了");
                    return null;
                }
            }else{
                System.out.println("appid和secret为空");
                return null;
            }
        }
    
        private  JSONObject getUrlResponse(String url){
            CharsetHandler handler = new CharsetHandler("UTF-8");
            try {
                HttpGet httpget = new HttpGet(new URI(url));
                HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
                //HttpClient
                CloseableHttpClient client = httpClientBuilder.build();
                client = (CloseableHttpClient) wrapClient(client);
                return new JSONObject(client.execute(httpget, handler));
            } catch (Exception e) {
                e.printStackTrace();
                return null;
            }
        }
    
    }
    

      

  • 相关阅读:
    BDD
    linux 删除中文名称乱码的文件
    python代码调用linux命令
    linux 查看内存
    java学习day17--API-注解
    java学习day17--API-单例设计模式
    java学习day17--API-同步锁
    java学习day16--API-多线程创建两种方式
    java学习day16--API-多线程-->进程和线程
    java学习day15--API-Map-->HashMap
  • 原文地址:https://www.cnblogs.com/pxblog/p/11848284.html
Copyright © 2011-2022 走看看