JAVA springMVC框架下使用 weixin-java-common-3.3.0 weixin-java-mp-3.3.0 两个jar做授权登陆与服务号消息推送
微信开发的话里面功能基本很全,可以参考 开发文档
使用步骤:
首先下好以上两个jar到自己项目中。在resource 目录下建一个 properties 文件 》》wx.properties
然后在properties文件中写上配置信息
wx_appid= APPID
wx_appsecret=appsecret
wx_token=token
wx_aeskey=如果是明文模式,这里不必填写。相反填入自己的key
然后我们需要建一个WxMpConfig.java文件
package com.hnzh.config;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
/**
* @author
*/
@Configuration
public class WxMpConfig {
@Value("#{wxProperties.wx_token}")
private String token;
@Value("#{wxProperties.wx_appid}")
private String appid;
@Value("#{wxProperties.wx_appsecret}")
private String appSecret;
@Value("#{wxProperties.wx_aeskey}")
private String aesKey;
public String getToken() {
return this.token;
}
public String getAppid() {
return this.appid;
}
public String getAppSecret() {
return this.appSecret;
}
public String getAesKey() {
return this.aesKey;
}
}
在spring xml文件中添加一下代码
例:
再建一个WeixinService.java文件 在使用时初始化配置信息
package com.hnzh.jzt.wechat.service;
import java.util.Date;
import javax.annotation.PostConstruct;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.hnzh.config.WxMpConfig;
import com.hnzh.handler.SubscribeHandler;
import com.hnzh.handler.UnsubscribeHandler;
import com.jeeplus.common.config.Global;
import me.chanjar.weixin.common.api.WxConsts.EventType;
import me.chanjar.weixin.common.api.WxConsts.XmlMsgType;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpInMemoryConfigStorage;
import me.chanjar.weixin.mp.api.WxMpMessageRouter;
import me.chanjar.weixin.mp.api.impl.WxMpServiceImpl;
import me.chanjar.weixin.mp.bean.kefu.WxMpKefuMessage;
import me.chanjar.weixin.mp.bean.message.WxMpXmlMessage;
import me.chanjar.weixin.mp.bean.message.WxMpXmlOutMessage;
import me.chanjar.weixin.mp.bean.template.WxMpTemplateData;
import me.chanjar.weixin.mp.bean.template.WxMpTemplateMessage;
/**
* @author Binary Wang
*/
@Service
public class WeixinService extends WxMpServiceImpl {
private final Logger logger = LoggerFactory.getLogger(this.getClass());
@Autowired
private WxMpConfig wxConfig;
@Autowired
private UnsubscribeHandler unsubscribeHandler;
@Autowired
private SubscribeHandler subscribeHandler;
private WxMpMessageRouter router;
@PostConstruct
public void init() {
final WxMpInMemoryConfigStorage config = new WxMpInMemoryConfigStorage();
// 设置微信公众号的appid
config.setAppId(this.wxConfig.getAppid());
// 设置微信公众号的app corpSecret
config.setSecret(this.wxConfig.getAppSecret());
// 设置微信公众号的token
config.setToken(this.wxConfig.getToken());
// 设置消息加解密密钥
config.setAesKey(this.wxConfig.getAesKey());
super.setWxMpConfigStorage(config);
this.refreshRouter();
}
private void refreshRouter() {
final WxMpMessageRouter newRouter = new WxMpMessageRouter(this);
// 关注事件
newRouter.rule().async(false).msgType(XmlMsgType.EVENT)
.event(EventType.SUBSCRIBE).handler(this.subscribeHandler)
.end();
// 取消关注事件
newRouter.rule().async(false).msgType(XmlMsgType.EVENT)
.event(EventType.UNSUBSCRIBE).handler(this.unsubscribeHandler)
.end();
this.router = newRouter;
}
public WxMpXmlOutMessage route(WxMpXmlMessage message) {
try {
return this.router.route(message);
} catch (Exception e) {
this.logger.error(e.getMessage(), e);
}
return null;
}
/**
* 发送模板消息
* @param openid
* @param name
* @param idCard
* @param createDate
* @param place
* @param source
* @param detailsId
* @param pushStateId
*/
public void sendTemplateMsg(String openid,String name,String idCard,String createDate,String place,String source,String detailsId,String pushStateId){
//模板消息跳转路径
String msgPushUrl = Global.getConfig("WechatMsgPush");
WxMpTemplateMessage templateMessage = WxMpTemplateMessage.builder()
.toUser(openid) //推送用户
.templateId(Global.getConfig("WXPushMsgTemp")) //发送的消息模板ID
.url(msgPushUrl.replace("DetailsId", String.valueOf(detailsId)).replace("openId", openid)) //点击跳转路径
.build();
templateMessage.addData(new WxMpTemplateData("first", "最新通知\n", "#999"));
templateMessage.addData(new WxMpTemplateData("keyword1", place +"\n", "#999"));
templateMessage.addData(new WxMpTemplateData("keyword2", name +"\n", "#999"));
templateMessage.addData(new WxMpTemplateData("keyword3", idCard +"\n", "#999"));
templateMessage.addData(new WxMpTemplateData("keyword4", DateFormatUtils.format(new Date(), "yyyy-MM-dd HH:mm:ss") +"\n", "#999"));
templateMessage.addData(new WxMpTemplateData("keyword5", source +"\n", "#999"));
templateMessage.addData(new WxMpTemplateData("remark", "\n请所在区域同志做好相应工作!", "#999"));
try {
getTemplateMsgService().sendTemplateMsg(templateMessage);
} catch (WxErrorException e) {
logger.error("模板消息发送失败");
e.printStackTrace();
} finally {
//处理发送记录
}
}
/**
* 图文消息推送方法
* @param openId
* @param name
* @param idCard
* @param createDate
* @param place
* @param source
* @param detailsId
* @param pushStateId
* @param picurl
*/
public void sendImgMsg(String openId,String name,String idCard,String createDate,String place,String source,String detailsId,String pushStateId,String picurl){
WxMpKefuMessage.WxArticle article1 = new WxMpKefuMessage.WxArticle();
article1.setUrl(Global.getConfig("WechatMsgPush").replace("DetailsId", String.valueOf(detailsId)).replace("openId", openId));
article1.setPicUrl(picurl); //封面图片
article1.setDescription(name+" "+idCard + " " + place);
article1.setTitle("消息通知");
WxMpKefuMessage build = WxMpKefuMessage.NEWS()
.toUser(openId)
.addArticle(article1)
.build();
try {
getKefuService().sendKefuMessage(build);
} catch (WxErrorException e) {
logger.error("客服消息发送失败");
e.printStackTrace();
} finally {
//处理发送记录
}
}
}
如果不需要消息推送的功能可以删除其中的推送消息方法
WeixinService.java 所依赖的java 文件,其中包括各种事件,如:接收客服会话管理事件,门店审核事件,点击菜单连接事件
关注事件,取消关注事件等。如果不需要可以将其对应的代码和JAVA文件删掉
我的为例 :builder包下三个java文件
AbstractBuilder
package com.hnzh.builder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.hnzh.jzt.wechat.service.WeixinService;
import me.chanjar.weixin.mp.bean.message.WxMpXmlMessage;
import me.chanjar.weixin.mp.bean.message.WxMpXmlOutMessage;
/**
* @author Binary Wang
*/
public abstract class AbstractBuilder {
protected final Logger logger = LoggerFactory.getLogger(getClass());
public abstract WxMpXmlOutMessage build(String content,
WxMpXmlMessage wxMessage, WeixinService service);
}
ImageBuilder
package com.hnzh.builder;
import com.hnzh.jzt.wechat.service.WeixinService;
import me.chanjar.weixin.mp.bean.message.WxMpXmlMessage;
import me.chanjar.weixin.mp.bean.message.WxMpXmlOutImageMessage;
import me.chanjar.weixin.mp.bean.message.WxMpXmlOutMessage;
/**
* @author Binary Wang
*/
public class ImageBuilder extends AbstractBuilder {
@Override
public WxMpXmlOutMessage build(String content, WxMpXmlMessage wxMessage,
WeixinService service) {
WxMpXmlOutImageMessage m = WxMpXmlOutMessage.IMAGE().mediaId(content)
.fromUser(wxMessage.getToUser()).toUser(wxMessage.getFromUser())
.build();
return m;
}
}
TextBuilder
package com.hnzh.builder;
import com.hnzh.jzt.wechat.service.WeixinService;
import me.chanjar.weixin.mp.bean.message.WxMpXmlMessage;
import me.chanjar.weixin.mp.bean.message.WxMpXmlOutMessage;
import me.chanjar.weixin.mp.bean.message.WxMpXmlOutTextMessage;
/**
* @author Binary Wang
*/
public class TextBuilder extends AbstractBuilder {
@Override
public WxMpXmlOutMessage build(String content, WxMpXmlMessage wxMessage,
WeixinService service) {
WxMpXmlOutTextMessage m = WxMpXmlOutMessage.TEXT().content(content)
.fromUser(wxMessage.getToUser()).toUser(wxMessage.getFromUser())
.build();
return m;
}
}
config 包下
package com.hnzh.config;
public class NewArticle {
private String url;
private String picUrl;
private String description;
private String title;
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getPicUrl() {
return picUrl;
}
public void setPicUrl(String picUrl) {
this.picUrl = picUrl;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
}
-------------------------------------------------------------------------------------------------------------------------------------------------------------------------
授权登陆Controller 获取用户微信信息实例,其中包括openId
package com.hnzh.jzt.wechat.web;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import com.hnzh.jzt.cameraly.entity.CameraLy;
import com.hnzh.jzt.cameraly.service.CameraLyService;
import com.hnzh.jzt.temp.entity.TempDetails;
import com.hnzh.jzt.userly.entity.UserLy;
import com.hnzh.jzt.userly.service.UserLyService;
import com.hnzh.jzt.wechat.service.WeixinService;
import com.jeeplus.common.config.Global;
import com.jeeplus.common.utils.MyBeanUtils;
import com.jeeplus.common.utils.StringUtils;
import com.jeeplus.common.web.BaseController;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.mp.bean.result.WxMpOAuth2AccessToken;
import me.chanjar.weixin.mp.bean.result.WxMpUser;
import net.sf.json.JSONObject;
/**
* 微信控制器
* @author Administrator
*
*/
@Controller
@RequestMapping(value = "${frontPath}/weChat")
public class WeChatController extends BaseController{
@Resource
private WeixinService wxMpService;
@RequestMapping("/login")
public String login(String code,HttpServletRequest request,HttpServletResponse response,Model model){
WxMpUser wxMpUser = null;
WxMpOAuth2AccessToken oauth2getAccessToken = null;
String echostr = request.getParameter("echostr");
if (!StringUtils.isBlank(echostr)) {
checkUrl(echostr,response);
}else{
if(StringUtils.isNoneBlank(code)){
try {
oauth2getAccessToken = wxMpService.oauth2getAccessToken(code);
if(wxMpService.oauth2validateAccessToken(oauth2getAccessToken)){
oauth2getAccessToken = wxMpService.oauth2refreshAccessToken(oauth2getAccessToken.getRefreshToken());
}
wxMpUser = wxMpService.oauth2getUserInfo(oauth2getAccessToken, null);
} catch (WxErrorException e) {
logger.error("获取AccessToken失败,code已使用(微信服务器第二次调用)");
if(e.getMessage().startsWith("{\"errcode\":40163")){
return null;
}else{
logger.error("获取AccessToken失败");
e.printStackTrace();
}
}
}
}
//wxMpUser 微信返回的用户信息
/.... 业务逻辑 ....../
return "/mobile/modules/jzt/wechat/registerLy";
}
}
授权地址:回调地址 REDIRECT_URI 需要URL转码
https://open.weixin.qq.com/connect/oauth2/authorize?appid=APPID&redirect_uri=REDIRECT_URI&response_type=code&scope=SCOPE&state=STATE#wechat_redirect