java集成微信公众号推送

122 阅读2分钟

1.获取openId

package com.zz.weixin.controller;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSON;
import com.zz.common.utils.PropertyUtil;
import com.zz.common.utils.StringUtils;
import com.zz.weixin.data.WeiXinUserCodeResult;

import weixin.popular.api.SnsAPI;
import weixin.popular.bean.sns.SnsToken;
import weixin.popular.bean.user.User;
import weixin.popular.support.expirekey.DefaultExpireKey;

@Controller
@RequestMapping({ "/weixin" })
public class WxController {

	private static Logger log = LoggerFactory.getLogger(WxController.class);

	private static DefaultExpireKey expirekey = new DefaultExpireKey(60);

	@Autowired
	private HttpServletRequest request;

	@RequestMapping({ "/index", "/" })
	public String index(ModelMap map) {
		log.info("portal load");
		String appId = PropertyUtil.getValueByKey(PropertyUtil.COMMON, "weixin.appid");
		String baseUrl = PropertyUtil.getValueByKey(PropertyUtil.COMMON, "root.base.url");
		String redirectUrl = PropertyUtil.getValueByKey(PropertyUtil.COMMON, "app.redirect.url");
		boolean isWx = isWeiXinBrowserType(request);
		Object o = request.getSession(true).getAttribute("wxOpenIdData");
		Object did = request.getSession(true).getAttribute("didOnce");
		User wxOpenIdData = null;
		if (o != null) {
			wxOpenIdData = (User) o;
			log.info("info" + JSON.toJSONString(wxOpenIdData));
		}
		Boolean didOnce = false;
		if (o != null) {
			didOnce = (Boolean) did;
		}
		map.put("user", wxOpenIdData);
		if (isWx) {
			if (!didOnce && (wxOpenIdData == null || StringUtils.isEmpty(wxOpenIdData.getOpenid()))) {
				String redirectUri = baseUrl + "/weixin/openid";
				String url = "redirect:" + SnsAPI.connectOauth2Authorize(appId, redirectUri, true, null);
				return url;
			}
			else {
				return "redirect:" + redirectUrl + "?openId=" + wxOpenIdData.getOpenid();
			}
		}
		return "redirect:" + redirectUrl;
	}

	@RequestMapping(value = "/openid", method = RequestMethod.GET)
	public ModelAndView openid(WeiXinUserCodeResult result, ModelMap model) {
		String appId = PropertyUtil.getValueByKey(PropertyUtil.COMMON, "weixin.appid");
		String secret = PropertyUtil.getValueByKey(PropertyUtil.COMMON, "weixin.appsecret");
		request.getSession(true).setAttribute("didOnce", true);
		if (StringUtils.isEmpty(result.getCode())) {
			return new ModelAndView("redirect:/portal/");
		}
		else if (!expirekey.exists(result.getCode())) {
			expirekey.add(result.getCode());
			SnsToken snsToken = SnsAPI.oauth2AccessToken(appId, secret, result.getCode());
			String page = result.getState();
			if (StringUtils.isEmpty(page)) {
				page = "index";
			}

			User wxUser = SnsAPI.userinfo(snsToken.getAccess_token(), snsToken.getOpenid(), "zh_CN");
			wxUser.setOpenid(snsToken.getOpenid());
			request.getSession(true).setAttribute("wxOpenIdData", wxUser);
			ModelAndView mav = new ModelAndView("redirect:/weixin/" + page);
			return mav;
		}
		else {
			return new ModelAndView("redirect:/weixin/");
		}
	}

	private final static String[] AGENTS_MOBILE = { "Android", "iPhone", "iPod", "iPad", "Windows Phone", "MQQBrowser" };

	protected boolean checkAgentIsMobile(HttpServletRequest request) {
		String ua = request.getHeader("User-Agent");
		boolean flag = false;
		if (!ua.contains("Windows NT") || (ua.contains("Windows NT") && ua.contains("compatible; MSIE 9.0;"))) {
			if (!ua.contains("Windows NT") && !ua.contains("Macintosh")) {
				for (String item : AGENTS_MOBILE) {
					if (ua.contains(item)) {
						flag = true;
						break;
					}
				}
			}
		}
		return flag;
	}

	protected boolean isWeiXinBrowserType(HttpServletRequest req) {
		String s = req.getHeader("user-agent");
		if (s == null)
			return false;
		if (s.toLowerCase().indexOf("micromessenger") > -1)
			return true;
		return false;
	}
}

相应配置参数

weixin.appid=wxd62df626ccaaf6c4

weixin.appsecret=d77bd7e49cc4d7a676cc4f09b63c9f15

weixin.template.id=3DfRBtj5T1fpKoAevl-36UxJdMcUFpeEIA1xM3ab7PI

root.base.url=http://dev.woodare.com/zz

app.redirect.url=http://47.105.36.112:25636/h5/#/

app.notify.url=http://47.105.36.112:25636/h5/#/invite/%s/%d/1

2.推送集成

/******************************************************************************
 *                                                                             
 *                      Woodare PROPRIETARY INFORMATION                        
 *                                                                             
 *          The information contained herein is proprietary to Woodare         
 *           and shall not be reproduced or disclosed in whole or in part      
 *                    or used for any design or manufacture                    
 *              without direct written authorization from FengDa.              
 *                                                                             
 *            Copyright (c) 2013 by Woodare.  All rights reserved.             
 *                                                                             
 *****************************************************************************/
package com.zz.weixin.service;

import java.util.Date;
import java.util.LinkedHashMap;

import org.springframework.stereotype.Service;

import com.zz.common.utils.PropertyUtil;
import com.zz.common.utils.StringUtils;

import weixin.popular.api.MessageAPI;
import weixin.popular.api.TokenAPI;
import weixin.popular.bean.message.templatemessage.TemplateMessage;
import weixin.popular.bean.message.templatemessage.TemplateMessageItem;
import weixin.popular.bean.message.templatemessage.TemplateMessageResult;
import weixin.popular.bean.token.Token;

/**
 * ClassName: WeixinService
 * 
 * @description
 * @author Xinxing Jiang
 * @Date 2020年7月11日
 */
public class WeixinService {

	private static String accessToken;
	private static Date expirDate;

	private static String getWeiXinAccessToken() {
		if (accessToken == null || expirDate.before(new Date())) {
			String appId = PropertyUtil.getValueByKey(PropertyUtil.COMMON, "weixin.appid");
			String appSecret = PropertyUtil.getValueByKey(PropertyUtil.COMMON, "weixin.appsecret");
			Token token = TokenAPI.token(appId, appSecret);
			if (token != null && StringUtils.isNotEmpty(token.getAccess_token())) {
				accessToken = token.getAccess_token();
				expirDate = new Date(new Date().getTime() + token.getExpires_in() * 3000);
			}
		}
		return accessToken;
	}

	/**
	 * {{first.DATA}}
	 * 设备编号:{{keyword1.DATA}}
	 * 开始时间:{{keyword2.DATA}}
	 * 结束时间:{{keyword3.DATA}}
	 * 总时长:{{keyword4.DATA}}
	 * {{remark.DATA}}
	 */
	public static TemplateMessageResult sendMessage(String openId, String name, String token, Integer action, String sn, String title, String startDate, String finishDate, String timeFrame, String remark) {
		if (StringUtils.isNotEmpty(openId)) {
			TemplateMessage tMessage = new TemplateMessage();
			String templateId = PropertyUtil.getValueByKey(PropertyUtil.COMMON, "weixin.template.id");
			String notifyUrl = PropertyUtil.getValueByKey(PropertyUtil.COMMON, "app.notify.url");
			// http:// localhost:8081/#/invite/aa429af6-e634-4aed-8060-20a065abe6ed/0/1
			notifyUrl = String.format(notifyUrl, token, action);
			tMessage.setUrl(notifyUrl);
			tMessage.setTemplate_id(templateId);
			tMessage.setTouser(openId);
			LinkedHashMap<String, TemplateMessageItem> data = new LinkedHashMap<String, TemplateMessageItem>();
			data.put("first", new TemplateMessageItem(name + "您好! 邀请您参加" + title, "#414141"));
			data.put("keyword1", new TemplateMessageItem(sn, "#414141"));
			data.put("keyword2", new TemplateMessageItem(startDate, "#414141"));
			data.put("keyword3", new TemplateMessageItem(finishDate, "#414141"));
			data.put("keyword4", new TemplateMessageItem(timeFrame, "#414141"));
			data.put("remark", new TemplateMessageItem(remark != null ? remark : "", "#666666"));
			tMessage.setData(data);
			TemplateMessageResult result = MessageAPI.messageTemplateSend(getWeiXinAccessToken(), tMessage);
			return result;
		}
		return null;
	}
}