我的思路
1、首先实现能够给某个用户推送消息
2、获取关注该公众号的所有用户的openid
3、使用一个for循环,推送给每个用户消息
需要的东西
1、认证的服务号
2、申请模板,有一个合适的模板
3、我们需要公众号的appid、密钥、模板id
服务器配置,需要把项目部署到服务器上,才能配置,不然会提示错误!
配置服务器的代码如下
package com.example.demo.control;import com.example.demo.token.SignUtil;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RequestMethod;import org.springframework.web.bind.annotation.RestController;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;@RestController@RequestMapping("/weixin")public class TokenControl {/*** 微信消息接收和token验证*/@RequestMapping(value = "/token", method = RequestMethod.GET)public String get(HttpServletRequest request, HttpServletResponse response) throws Exception {System.out.println("----------------验证微信服务号信息开始----------");request.setCharacterEncoding("UTF-8");response.setCharacterEncoding("UTF-8");// 微信加密签名String signature = request.getParameter("signature");// 时间戳String timestamp = request.getParameter("timestamp");// 随机数String nonce = request.getParameter("nonce");// 随机字符串String echostr = request.getParameter("echostr");// 通过检验signature对请求进行校验,若校验成功则原样返回echostr,表示接入成功,否则接入失败if (SignUtil.checkSignature(signature, timestamp, nonce)) {System.out.println("----验证服务号结束.........");return echostr;}else{return null;}}//public}
package com.example.demo.token;import java.security.MessageDigest;import java.security.NoSuchAlgorithmException;import java.util.Arrays;public class SignUtil {private static String token = "token";/*** 校验签名* @param signature 签名* @param timestamp 时间戳* @param nonce 随机数* @return 布尔值*/public static boolean checkSignature(String signature,String timestamp,String nonce){String checktext = null;if (null != signature) {//对ToKen,timestamp,nonce 按字典排序String[] paramArr = new String[]{token,timestamp,nonce};Arrays.sort(paramArr);//将排序后的结果拼成一个字符串String content = paramArr[0].concat(paramArr[1]).concat(paramArr[2]);try {MessageDigest md = MessageDigest.getInstance("SHA-1");//对接后的字符串进行sha1加密byte[] digest = md.digest(content.toString().getBytes());checktext = byteToStr(digest);} catch (NoSuchAlgorithmException e){e.printStackTrace();}}//将加密后的字符串与signature进行对比return checktext !=null ? checktext.equals(signature.toUpperCase()) : false;}/*** 将字节数组转化我16进制字符串* @param byteArrays 字符数组* @return 字符串*/private static String byteToStr(byte[] byteArrays){String str = "";for (int i = 0; i < byteArrays.length; i++) {str += byteToHexStr(byteArrays[i]);}return str;}/*** 将字节转化为十六进制字符串* @param myByte 字节* @return 字符串*/private static String byteToHexStr(byte myByte) {char[] Digit = {'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'};char[] tampArr = new char[2];tampArr[0] = Digit[(myByte >>> 4) & 0X0F];tampArr[1] = Digit[myByte & 0X0F];String str = new String(tampArr);return str;}}
打包成war包或者jar包以后,然后放在服务器上,把这个后台的访问地址填写在微信公众号的服务器配置这里;
记住,我的令牌是token,如果你设置成其他的,记住在代码里更改一下!!
把你的域名ip地址加入到白名单里面,直接复制ip地址到白名单里面就可以了!!
如果你没有域名,就算了!!!不用做了!!
现在我们再来看一下推送消息的代码
进入后端的第一个入口
package com.example.demo.control;import com.example.demo.getall.GetOpenIdAct;import me.mon.error.WxErrorException;import me.chanjar.weixin.mp.api.WxMpInMemoryConfigStorage;import me.chanjar.weixin.mp.api.WxMpService;import me.chanjar.weixin.mp.api.impl.WxMpServiceImpl;import me.chanjar.weixin.mp.bean.template.WxMpTemplateData;import me.chanjar.weixin.mp.bean.template.WxMpTemplateMessage;import java.text.SimpleDateFormat;import java.util.Date;import java.util.List;public class PushControl {public void sendWxInfo(String json) {// 获取模板IdString templateId= "zKZclU4ic42_sHcapwgctaIBRTEbb1wh5SQpM-Quc7s";// 需要跳转的url----点击消息推送时需要跳转的地址String url = "http://**************/index";//获取关注该公众号的所有openidList<String> oplist=new GetOpenIdAct().getWeixinUser();//获取关注该公众号的所有openidWxMpInMemoryConfigStorage wxStorage = new WxMpInMemoryConfigStorage();wxStorage.setAppId("公众号appid");wxStorage.setSecret("公众号密钥");WxMpService wxMpService = new WxMpServiceImpl();wxMpService.setWxMpConfigStorage(wxStorage);// 发送模板消息接口WxMpTemplateMessage templateMessage=new WxMpTemplateMessage();templateMessage.setUrl(url);templateMessage.setTemplateId(templateId);//String time=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());// 添加模板数据templateMessage.addData(new WxMpTemplateData("first","尊敬的客户,您的设备出发报警")).addData(new WxMpTemplateData("keyword1",json)).addData(new WxMpTemplateData("keyword2","某某公司")).addData(new WxMpTemplateData("keyword3","监测到挖掘机工作")).addData(new WxMpTemplateData("keyword4",time)).addData(new WxMpTemplateData("remark","查看报警具体位置"));String msgId = null;try {// 发送模板消息for (String uids:oplist){templateMessage.setToUser(uids);msgId = wxMpService.getTemplateMsgService().sendTemplateMsg(templateMessage);}} catch (WxErrorException e) {e.printStackTrace();}}}
获取该公众号的所有用户openid
package com.example.demo.getall;import mons.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.conn.ssl.SSLConnectionSocketFactory;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.JSONArray;import org.json.JSONException;import org.json.JSONObject;import .ssl.SSLContext;import .ssl.TrustManager;import .ssl.X509TrustManager;import java.io.IOException;import .URI;import java.security.cert.CertificateException;import java.security.cert.X509Certificate;import java.util.*;public class GetOpenIdAct {public List<String> getWeixinUser(){String access_token=getToken();List<String> openIds=getUsers(access_token);//openIds为所有关注用户的openidSystem.out.println("===========获取关注该公众号的openid========");for(int i=0;i<openIds.size();i++){System.out.println(openIds.get(i));}return openIds;}/*** 获取微信公众号关注用户* 官方接口文档:https://developers./doc/offiaccount/User_Management/Getting_a_User_List.html* @param access_token* @return*/public List<String> getUsers(String access_token) {String usersGetUrl="https://api./cgi-bin/user/get";usersGetUrl+="?access_token="+access_token;JSONObject data=getUrlResponse(usersGetUrl);List<String> openIds=new ArrayList<String>();Integer total=0,count=0;try {total=(Integer) data.get("total");count=(Integer) data.get("count");//总关注用户数超过默认一万if(count<total){openIds.addAll(getUsers(openIds,usersGetUrl, access_token, (String)data.get("next_openid")));}else{//有关注者 json才有data参数if(count>0){JSONObject openIdData=(JSONObject) data.get("data");JSONArray openIdArray= (JSONArray) openIdData.get("openid");for(int i=0;i<openIdArray.length();i++){openIds.add((String) openIdArray.get(i));}}}} catch (JSONException e) {e.printStackTrace();}return openIds;}/*** 获取access_token** @return*/public String getToken() {String tokenGetUrl = "https://api./cgi-bin/token?grant_type=client_credential";//微信提供获取access_token接口地址String appid = "wx062d6112471220d0";String secret = "0c5757f9b36aa4384a10c52c7456fce7";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 List<String> getUsers(List<String> openIds,String url,String access_token,String next_openid) {JSONObject data=getUrlResponse(url);try {Integer count=(Integer) data.get("count");String nextOpenId=(String) data.get("next_openid");if(count>0){JSONObject openIdData=(JSONObject) data.get("data");JSONArray openIdArray= (JSONArray) openIdData.get("openid");for(int i=0;i<openIdArray.length();i++){openIds.add((String) openIdArray.get(i));}}if(StringUtils.isNotBlank(nextOpenId)){return getUsers(openIds,url, access_token, nextOpenId);}} catch (JSONException e) {e.printStackTrace();}return openIds;}private JSONObject getUrlResponse(String url) {CharsetHandler handler = new CharsetHandler("UTF-8");try {HttpGet httpget = new HttpGet(new URI(url));HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();//HttpClientCloseableHttpClient client = httpClientBuilder.build();client = (CloseableHttpClient) wrapClient(client);return new JSONObject(client.execute(httpget, handler));} 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;}}private 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;}}}}
当然还有一些依赖
<!--微信模版消息推送三方sdk--><dependency><groupId>com.github.binarywang</groupId><artifactId>weixin-java-mp</artifactId><version>3.3.0</version></dependency><dependency><groupId>com.alibaba</groupId><artifactId>fastjson</artifactId><version>1.2.7</version></dependency><dependency><groupId>net.sf.json-lib</groupId><artifactId>json-lib</artifactId><version>2.4</version><classifier>jdk15</classifier></dependency><!--微信模版消息推送三方sdk-->