公众号实现消息推送

2年前 (2022) 程序员胖胖胖虎阿
299 0 0

实现公众号模板消息

最终效果:
公众号实现消息推送

需要准备工作:

  1. 微信公众平台:申请小程序、公众号
    公众号:申请时选择服务号,模板消息接口需要微信认证后才能申请使用。
  2. 微信开放平台:需要认证开发者资质,绑定公众号和小程序后才会生成一致的unionId。

注: 公众号和微信开放平台认证时都需要花费300元。

实现步骤:

1. 修改基本配置

公众号实现消息推送
注:ip白名单配置时,需要换行不是用逗号分隔。

微信服务器会发送GET请求到填写的服务器配置的URL上,开发者通过检验signature对请求进行校验。
若确认此次GET请求来自微信服务器,请原样返回echostr参数内容,则接入生效,成为开发者成功,否则接入失败。
https://developers.weixin.qq.com/doc/offiaccount/Basic_Information/Access_Overview.html

2. 服务器校验代码实现:

public static void checkSignature(HttpServletRequest request, HttpServletResponse response) {

        // 1、验证消息的确来自微信服务器
        String signature = request.getParameter("signature");
        String timestamp = request.getParameter("timestamp");
        String nonce = request.getParameter("nonce");
        String echostr = request.getParameter("echostr");
        String token = WxConstants.WX_SERVER_TOKEN;

        String jiami = null;
        if (!UtilValidate.isEmpty(echostr) && !"".equals(echostr)){
            try {
                // 这里是对三个参数进行加密
                jiami = SHA1.getSHA1(token, timestamp, nonce, "");
            } catch (AesException e) {
                e.printStackTrace();
            }
            if (jiami.equals(signature)) {
                // 返回echostr给微信服务器
                OutputStream os = null;
                try {
                    os = response.getOutputStream();
                    os.write(URLEncoder.encode(echostr, "UTF-8").getBytes());
                    os.flush();
                } catch (IOException e) {
                    e.printStackTrace();
                } finally {
                    if (os != null) {
                        try {
                            os.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        }
    }
package woxiang.util;

/**
 * SHA1 class
 *
 * 计算公众平台的消息签名接口.
 */
public class SHA1 {

	/**
	 * 用SHA1算法生成安全签名
	 * 
	 * @param token
	 *            票据
	 * @param timestamp
	 *            时间戳
	 * @param nonce
	 *            随机字符串
	 * @param encrypt
	 *            密文
	 * @return 安全签名
	 * @throws AesException
	 */
	public static String getSHA1(String token, String timestamp, String nonce, String encrypt) throws AesException {
		try {
			String[] array = new String[] { token, timestamp, nonce, encrypt };
			StringBuffer sb = new StringBuffer();
			// 字符串排序
			Arrays.sort(array);
			for (int i = 0; i < 4; i++) {
				sb.append(array[i]);
			}
			String str = sb.toString();
			// SHA1签名生成
			MessageDigest md = MessageDigest.getInstance("SHA-1");
			md.update(str.getBytes());
			byte[] digest = md.digest();

			StringBuffer hexstr = new StringBuffer();
			String shaHex = "";
			for (int i = 0; i < digest.length; i++) {
				shaHex = Integer.toHexString(digest[i] & 0xFF);
				if (shaHex.length() < 2) {
					hexstr.append(0);
				}
				hexstr.append(shaHex);
			}
			return hexstr.toString();
		} catch (Exception e) {
			e.printStackTrace();
			throw new AesException(AesException.ComputeSignatureError);
		}
	}
}


package woxiang.exception;

@SuppressWarnings("serial")
public class AesException extends Exception {

	public final static int OK = 0;
	public final static int ValidateSignatureError = -40001;
	public final static int ParseXmlError = -40002;
	public final static int ComputeSignatureError = -40003;
	public final static int IllegalAesKey = -40004;
	public final static int ValidateAppidError = -40005;
	public final static int EncryptAESError = -40006;
	public final static int DecryptAESError = -40007;
	public final static int IllegalBuffer = -40008;
	// public final static int EncodeBase64Error = -40009;
	// public final static int DecodeBase64Error = -40010;
	// public final static int GenReturnXmlError = -40011;

	private int code;

	private static String getMessage(int code) {
		switch (code) {
		case ValidateSignatureError:
			return "签名验证错误";
		case ParseXmlError:
			return "xml解析失败";
		case ComputeSignatureError:
			return "sha加密生成签名失败";
		case IllegalAesKey:
			return "SymmetricKey非法";
		case ValidateAppidError:
			return "appid校验失败";
		case EncryptAESError:
			return "aes加密失败";
		case DecryptAESError:
			return "aes解密失败";
		case IllegalBuffer:
			return "解密后得到的buffer非法";
		// case EncodeBase64Error:
		// return "base64加密错误";
		// case DecodeBase64Error:
		// return "base64解密错误";
		// case GenReturnXmlError:
		// return "xml生成失败";
		default:
			return null; // cannot be
		}
	}

	public int getCode() {
		return code;
	}

	public AesException(int code) {
		super(getMessage(code));
		this.code = code;
	}

}


3. 公众号关注、取消关注,关注即订阅。获取公众号用户的openId

wx服务器会发送xml数据包到之前配置的服务器访问地址上,进行解析进行数据存储。
详细文档地址:https://developers.weixin.qq.com/doc/offiaccount/Message_Management/Receiving_event_pushes.html

 public static String processWxData(HttpServletRequest request, HttpServletResponse response){

        // 1. 服务器消息验证
        checkSignature(request, response);

        //  2. 处理xml数据包
        String wxXml = (String)request.getAttribute("paramBody");
        InputStream wxXmlInputStream = new ByteArrayInputStream(wxXml.getBytes(StandardCharsets.UTF_8));
        Map<String, String> xmlMap = WXUtil.xmlToMap(wxXmlInputStream);
 }
/**
     * xml数据包转 Map
     * @param is
     * @return
     */
    public static Map<String, String> xmlToMap(InputStream is) {
        Map<String,String> map=new HashMap();
        SAXReader reader=new SAXReader();
        try {
            Document document=reader.read(is);
            Element root=document.getRootElement();
            //root如下:org.dom4j.tree.DefaultElement@46c9c427 [Element: <xml attributes: []/>]
            List<Element> elements=root.elements();
            //elements中的内容包括请求道的xml数据包内容
            for(Element e:elements) {
                map.put(e.getName(), e.getStringValue());
            }
        } catch (DocumentException e) {
            e.printStackTrace();
        }
        return map;
    }

4. 根据公众号openid 获取用户的unionId


// 微信公众号获取用户基本信息
String WX_PUBLIC_USERINFO = "https://api.weixin.qq.com/cgi-bin/user/info";

public static String getMsgSubcribeState(String token,String openid){
        String url = WxConstants.WX_PUBLIC_USERINFO + "?access_token="+token+"&openid="+openid +"&lang=zh_CN";
        String unionid = null;
        String result = MyHttpclientUtil.get(url);
        try {
            unionid = JSONObject.parseObject(result).getString("unionid");
        }catch (Exception e){
            unionid = null;
            System.out.println(" =========== union获取失败!===========");
        }
        return unionid;
    }

5. 获取小程序的unionId


	//获取用户信息
    String WX_ACCOUNT_GET_USER_UNIONID_URL = "https://api.weixin.qq.com/sns/jscode2session";


 	/**
     * 获取用户openId
     * @param code
     * @return
     */
   private static HashMap<String, String> getUserOpenId(String code){

        String requestUrl = WxConstants.WX_ACCOUNT_GET_USER_UNIONID_URL +"?grant_type="+WxConstants.CRM_GRANT_TYPE+"&appid="+WxConstants.CRM_APPID+"&secret="+WxConstants.CRM_SECRET+"&js_code="+code;
        String result = MyHttpclientUtil.get(requestUrl);
       
        com.alibaba.fastjson.JSONObject openIdResultObject = com.alibaba.fastjson.JSONObject.parseObject(result);
        String openid = openIdResultObject.getString("openid");
        String unionid = openIdResultObject.getString("unionid");

       HashMap<String, String> map = new HashMap<>();
       map.put("openid",openid == null? null : openid);
       map.put("unionid",unionid == null? null : unionid);

       return map;
    }

6. 小程序unionId和公众号的unionId,如果一致就是同一个小程序的用户,从而进行消息推送。

SELECT 
	pu.META_OPEN_ID openid
FROM
	Meta_event_Msg mem
JOIN Meta_customer_Info mci ON (mci.Meta_customer_Info_Id = mem.Meta_customer_Info_Id AND mci.STATE = 'CREATE')
JOIN meta_wx_public_user pu ON ( mci.Meta_unionid = pu.META_UNIONID AND pu.META_SUBSCRIBE = '1' )

7. 选择消息模板,获取到模板id和公众号用户的openId进行消息推送。

公众号实现消息推送

public static void sendWxPublicContact(String openId,String msg){

        String crmToken = getToken();
        String url = WxConstants.WX_PUBLIC_SEND_MSG + "?access_token=" + crmToken;

        HashMap<String, Object> paramMap = new HashMap<>();
        paramMap.put("touser",openId);                                  //用户的openId
        paramMap.put("template_id",WxConstants.SENDCONTACT_TEMPLAT);    //消息模板id

        HashMap<Object, Object> valueMap = new HashMap<>();
        valueMap.put("appid","wx418ba469d7c4c317");                     //小程序appid
        valueMap.put("pagepath","pages/contacts/contacts");             //小程序url
        paramMap.put("miniprogram",valueMap);                           //小程序所需数据

        HashMap<Object, Object> map = new HashMap<>();

        HashMap<Object, Object> valueMap1 = new HashMap<>();
        valueMap1.put("value","您好,您的友浪人脉联系提醒已完成!");
        map.put("first",valueMap1); //日期

        HashMap<Object, Object> valueMap2 = new HashMap<>();
        valueMap2.put("value","人脉联系提醒服务");
        map.put("keyword1",valueMap2); //服务项目

        //消息推送时间
        Date nowDate = new Date();
        SimpleDateFormat timeSdf = new SimpleDateFormat("yyyy年MM月dd日 06:30");

        HashMap<Object, Object> valueMap3 = new HashMap<>();
        valueMap3.put("value",timeSdf.format(nowDate));
        map.put("keyword2",valueMap3); //日期

        HashMap<Object, Object> valueMap4 = new HashMap<>();
        valueMap4.put("value",msg);
        map.put("remark",valueMap4);//备注

        paramMap.put("data",map);
        String s = JSON.toJSONString(paramMap);
        String jsonData = HttpclientPostUtil.getJsonData(s, url);
    }

8. 消息推送后会发送推送状态xml数据包到服务器url,可以对发送状态进行数据存储。

版权声明:程序员胖胖胖虎阿 发表于 2022年9月19日 下午6:16。
转载请注明:公众号实现消息推送 | 胖虎的工具箱-编程导航

相关文章

暂无评论

暂无评论...