我的思路
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 {