java 实现微信公众号模板消息推送到指定用户的openid

实现微信公众号模板消息推送

  • 控制层
  • 实体类
  • 官方文档地址:

控制层

package com.zjht.resourceserver.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.JSONObject;
import com.zjht.currentserver.model.po.SResourceActivity;
import com.zjht.resourceserver.service.ResourceActivityService;
import com.zjht.resourceserver.vo.TemplateData;
import com.zjht.resourceserver.vo.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.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

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.Map;
import java.util.Optional;
import java.util.TreeMap;

@Component
public class TemplateMsgAct {

    @Autowired
    private ResourceActivityService resourceActivityService;

    public final static String token_url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET";

    /**
     * 发送模板消息
     *官方文档地址:https://developers.weixin.qq.com/doc/offiaccount/Message_Management/Template_Message_Interface.html#5
     */
   // @RequestMapping("/sendTemplateMsg")
    public void sendTemplateMsg(String openid,Integer activityId) {
        String token = getToken();//获取access_token
        String createMenuUrl = "https://api.weixin.qq.com/cgi-bin/message/template/send"; //微信提供的发送接口地址
        String url = createMenuUrl + "?access_token=" + token;

        //根据活动id 获取活动名称
        Optional byId = resourceActivityService.findById(activityId);
        if (byId.isPresent()) {

        //封装模板消息数据内容
        try {
            WechatTemplate wechatTemplate =  new WechatTemplate();
           //接收人的openid
            wechatTemplate.setTouser(openid);
            //模板id
            wechatTemplate.setTemplate_id("0QHGjrzVczIubRwvGd7zTpDTmBAHjKyaWxPEwXLhm04");
            //详情跳转的路径
            wechatTemplate.setUrl("https://www.baidu.com/" ) ;
            Map mapdata = new TreeMap();
            // 封装模板数据
            TemplateData first = new TemplateData();
            first.setValue(byId.get().getTitle());
            first.setColor("#173177");
            mapdata.put("first", first);
 
            TemplateData keyword1 = new TemplateData();
            keyword1.setValue(byId.get().getTitle());
            first.setColor("#173177");
            mapdata.put("keyword1", keyword1);
 
            TemplateData keyword2 = new TemplateData();
            keyword2.setValue(byId.get().getHoldstartdate());
            first.setColor("#173177");
            mapdata.put("keyword2", keyword2);
 
            TemplateData remark = new TemplateData();
             remark.setValue("您报名的活动已审核通过,请您携带有效证件准时参加,如有疑问请联系活动负责人。");
            

            remark.setColor("#173177");
            mapdata.put("remark", remark);
 
            wechatTemplate.setData(mapdata);

            String jsonString = JSON.toJSONString(wechatTemplate);
            String str=post(url, jsonString, "application/json");
            System.out.println("模板请求结束:"+ str);

        } 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 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 {
        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="wx234523452345";
        String secret="12344564523452345232452345";
        JSONObject tokenJson=new JSONObject();
        if(StringUtils.isNotBlank(appid)&&StringUtils.isNotBlank(secret)){
            tokenGetUrl+="&appid="+appid+"&secret="+secret;
            tokenJson = JSONObject.parseObject(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  String 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);
            String execute = client.execute(httpget, handler);
            return execute;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
 
}

实体类

package com.zjht.resourceserver.vo;
 
import java.util.Map;
 
public class WechatTemplate {
    private String touser; //接收人
 
    private String template_id;  //模板id
 
    private String url;  //跳转的url
 
    private Map 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 getData() {
        return data;
    }
 
    public void setData(Map data) {
        this.data = data;
    }
}
package com.zjht.resourceserver.vo;

public class Token {

//接口访问凭证
private String accessToken;
//接口有效期,单位:秒
private int expiresIn;

public String getAccessToken() {
return accessToken;
}
public void setAccessToken(String accessToken) {
this.accessToken = accessToken;
}
public int getExpiresIn() {
return expiresIn;
}
public void setExpiresIn(int expiresIn) {
this.expiresIn = expiresIn;
}

}
package com.zjht.resourceserver.vo;
 
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;
    }
}

官方文档地址:

https://developers.weixin.qq.com/doc/offiaccount/Message_Management/Template_Message_Interface.html#5

你可能感兴趣的:(微信公众号开发,模板消息推送)