1.导入jar包
<dependency>
<groupId>com.github.binarywang</groupId>
<artifactId>weixin-java-miniapp</artifactId>
<version>4.0.0</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>com.github.binarywang</groupId>
<artifactId>weixin-java-mp</artifactId>
<version>3.9.0</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>com.github.binarywang</groupId>
<artifactId>weixin-java-pay</artifactId>
<version>3.3.0</version>
<scope>compile</scope>
</dependency>
2.小程序推送消息
2.1 微信授权小程序
@Autowired
private WxMaProperties properties; // 小程序配置
/**
* 微信授权
*/
@GetMapping("/wxLogin")
public AjaxResult wxLogin(String code, HttpServletRequest request) throws WxErrorException {
String appid = properties.getConfigs().get(0).getAppid();
final WxMaService wxService = WxMaConfiguration.getMaService(appid);
WxMaJscode2SessionResult session =
wxService.getUserService().getSessionInfo(code);
String openid = session.getOpenid();
JyUser jyUser = jyUserService.selectJyUserByUserOpenId(openid);
if (jyUser == null){ // 新建一个账号
jyUser = new JyUser();
jyUser.setOpenid(openid);
jyUser.setJyLoginTime(new Date());
jyUserService.insertJyUser(jyUser);
}
return AjaxResult.success(jyUser);
}
@Autowired
private WxMaProperties properties; // 小程序配置
@GetMapping("/wxToTeacherUser")
public AjaxResult wxToTeacherUser(String code, HttpServletRequest request) {
try {
// 获取登录
LoginTeacherVo session2 =
(LoginTeacherVo) SessionUtils.getSession(SessionUtils.TEACHER_LOGINS, request);
String appid = properties.getConfigs().get(1).getAppid();
final WxMaService wxService = WxMaConfiguration.getMaService(appid);
WxMaJscode2SessionResult session =
wxService.getUserService().getSessionInfo(code);
String openid = session.getOpenid();
ThAppTeacherUser user = new ThAppTeacherUser();
user.setAppUserId(session2.getAppUserId());
user.setOpenid(openid);
iThAppTeacherUserService.updateThAppTeacherUser(user);
return AjaxResult.success("绑定好");
} catch (RuntimeException | WxErrorException re) {
return AjaxResult.error(re.toString());
}
}
2.2发送消息
@Autowired
private WxMaProperties properties; // 小程序配置APPID和secret
@Value("${templateIds2}")
private String templateIds2;
public void send( TYcxUser user) {
/**
* {{name1.DATA}}
*
* 投递时间
* {{date4.DATA}}
*
* 职位名称
* {{thing5.DATA}}
*
* 工作经验
* {{thing11.DATA}}
*/
String appid = properties.getConfigs().get(0).getAppid();
final WxMaService wxService = WxMaConfiguration.getMaService(appid);
// 添加数据
List<WxMaSubscribeMessage.Data> data = new ArrayList<>();
WxMaSubscribeMessage.Data data1 = new WxMaSubscribeMessage.Data();
data1.setName("name1");
data1.setValue(user.getJpRealName());
data.add(data1);
WxMaSubscribeMessage.Data data3 = new WxMaSubscribeMessage.Data();
data3.setName("thing5");
data3.setValue(jssJobInfos.get(0).getJjiJobName());
data.add(data3);
WxMaSubscribeMessage.Data data2 = new WxMaSubscribeMessage.Data();
data2.setName("date4");
data2.setValue(datestr);
data.add(data2);
WxMaSubscribeMessage.Data data4 = new WxMaSubscribeMessage.Data();
data4.setName("thing11");
data4.setValue(resume.getJprWorkYearStr());
data.add(data4);
WxMaSubscribeMessage wxMaSubscribeMessage = WxMaSubscribeMessage.builder()
.templateId(templateIds2) // 模板id
.toUser(user.getOpenid()) // 消息推送给谁
.data(data)
.build();
try { // 发送消息
wxService.getMsgService().sendSubscribeMsg(wxMaSubscribeMessage);
} catch (WxErrorException e) {
log.error("【微信订阅消息】发送失败, {}", e.getMessage());
thYtong.setThytStatus(0);
thYtong.setThytOther("【微信订阅消息】发送失败:"+e.getMessage());// 失败原因
}
}
3公众号发布消息
3.1 微信公众号授权
配置信息
wechat:
mp:
appid: wx1------------
#公众号授权跳转地址
api-auth: https://open.weixin.qq.com/connect/oauth2/authorize?appid=APPID&redirect_uri=REDIRECT_URI&response_type=code&scope=SCOPE&state=STATE#wechat_redirect
#回调地址
auth_call_back: https://-------.com/api/wxApi/authCallBack
#公众号秘钥
secret: 06f47b---------------036c
#获取微信授权的access-token的接口地址
api-auth-access-token: https://api.weixin.qq.com/sns/oauth2/access_token?appid=APPID&secret=SECRET&code=CODE&grant_type=authorization_code
#获取微信用户信息接口地址
api-userinfo: https://api.weixin.qq.com/sns/userinfo?access_token=ACCESS_TOKEN&openid=OPENID&lang=zh_CN
#发送模板消息
api-send: https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=ACCESS_TOKEN
配置类
@Data
@Component
@ConfigurationProperties(prefix = "wechat.mp")
public class WechatMpProperties {
private String appId;
private String secret;
private String authCallBack;
private String apiAuth;
private String apiAuthAccessToken;
private String apiUserinfo;
private String apiSend;
}
发送公众号授权请求
@Autowired
private WechatMpProperties wechatMpProperties; 公众号配置
@GetMapping("/getWeChatClient")
public String getWeChatClient(HttpServletResponse response,String type, String studentNumber, String authSucceedSkipUrl) throws IOException {
String uRLEncoderAuthCallBack = null;
try {
// 获取配置信息的回调地址
uRLEncoderAuthCallBack =
URLEncoder.encode(wechatMpProperties.getAuthCallBack(), "utf-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
// 用户授权跳转地址
String apiAuthUrl = wechatMpProperties.getApiAuth()
.replace("APPID", wechatMpProperties.getAppId()) // appid
.replace("REDIRECT_URI", uRLEncoderAuthCallBack) // 回调地址
.replace("SCOPE", "snsapi_userinfo") // 类型:请求用户信息
.replace("STATE", studentNumber + "," + authSucceedSkipUrl+","+type); // 自定义参数
try {
response.sendRedirect(apiAuthUrl); // 重定向
} catch (IOException e) {
e.printStackTrace();
}
return "redirect:" + apiAuthUrl;
}
回调添加公众号的用户openid
@Autowired
private WechatMpProperties wechatMpProperties; // 公众号配置
/**
* 微信授权回调接口
*
* @param code 临时票据
* @param state 上个接口的自定义参数
* @return
* @throws IOException
*/
@GetMapping("/authCallBack")
public String authCallBack(HttpServletResponse response,String code, String state) throws IOException {
if (StringUtils.isEmpty(code)) {
// return AjaxResult.error(202,"参数不对");
}
//获取微信授权access_token
String apiAuthAccessTokenUrl = wechatMpProperties.getApiAuthAccessToken()
.replace("APPID", wechatMpProperties.getAppId())
.replace("SECRET", wechatMpProperties.getSecret())
.replace("CODE", code);
String result = HttpUtils.sendGet2(apiAuthAccessTokenUrl);
HashMap<String, String> wechatAuthTokenMap = JSON.parseObject(result, HashMap.class);
String accessToken = wechatAuthTokenMap.get("access_token");
String openid = wechatAuthTokenMap.get("openid");
//如果微信的返回access_token为空
if (StringUtils.isBlank(accessToken)) {
// return AjaxResult.error(202,"异常");
}
//调用微信通过OPENID和ACCESS_TOKEN获取用户信息接口
String apiUserinfoUrl = wechatMpProperties.getApiUserinfo()
.replace("ACCESS_TOKEN", accessToken)
.replace("OPENID", openid);
//获取微信用户信息
// String resultUserinfo = HttpUtils.sendGet2(apiUserinfoUrl);
String[] stateArr = state.split(",");
long id = Long.parseLong(stateArr[0]);// id
if("student".equals(stateArr[2])){ // 学生的保存公众号的openid
ThChildren thChildren = new ThChildren();
thChildren.setOpenidPublic(openid);
thChildren.setThcId(id);
iThChildrenService.updateThChildren(thChildren);
}else if("teacher".equals(stateArr[2])){ // 老师的保存公众号的openid
ThTeacher thTeacher = new ThTeacher();
thTeacher.setOpenidPublic(openid);
thTeacher.setThtId(id);
thTeacherService.updateThTeacher(thTeacher);
}
try {
response.sendRedirect(stateArr[1]);
} catch (IOException e) {
e.printStackTrace();
}
// 返回成功也的地址
return "redirect:" +stateArr[1];
}
公众号给某个用户推送消息
@Autowired
private WxMaProperties wxMaProperties; // 小程序配置类
@Override
public void sendStudent(TbQjInfo tbQjInfo) {
/**
* 详细内容
* {{first.DATA}}
*
* 教师姓名
* {{keyword1.DATA}}
*
* 请假时间
* {{keyword2.DATA}}
*
* 审核结果
* {{keyword3.DATA}}
*
* 审核教师
* {{keyword4.DATA}}
*
* 查看信息明细内容请点击“详情”
* {{remark.DATA}}
*
*/
ThChildren thChildren = thChildrenService.selectThChildrenByThcId(tbQjInfo.getChildrenId());
ThTeacher thTeacher = thTeacherService.selectThTeacherAndClassByThtId(tbQjInfo.getTearcherId());
String s = DateUtils.parseDateToStr("yyyy-MM-dd HH:mm", tbQjInfo.getQjStartTime());
String s2 = DateUtils.parseDateToStr("yyyy-MM-dd HH:mm", tbQjInfo.getQjEndTime());
// 填写数据模板
List<WxMpTemplateData> wxMpTemplateData = Arrays.asList(new WxMpTemplateData("first", "您好" + tbQjInfo.getQjChildrenName() + "教师已回复您的请假申请"),
new WxMpTemplateData("keyword1", thTeacher.getThtName()),
new WxMpTemplateData("keyword2", s + " -- " + s2),
new WxMpTemplateData("keyword3", "1".equals(tbQjInfo.getQjStatus()) ? "同意" : "拒绝"),
new WxMpTemplateData("keyword4", thTeacher.getThtName())
, new WxMpTemplateData("remark", "查看信息明细内容请点击'详情'"));
// 小程序参数配置
WxMpTemplateMessage.MiniProgram miniProgram = new WxMpTemplateMessage.MiniProgram(wxMaProperties.getConfigs().get(0).getAppid(),"小程序跳转的页面地址",false);
WxMpTemplateMessage build = WxMpTemplateMessage.builder()
.templateId("zv-----------------o4OkCc") // 模板id
.toUser(thChildren.getOpenidPublic()) // 推送个谁的openid
.data(wxMpTemplateData) // 模板数据
.miniProgram(miniProgram) // 小程序跳转 (不传不跳转)
.build();
try {
// 发送消息
WxMpService bean = SpringUtils.getBean(WxMpService.class);
bean.getTemplateMsgService().sendTemplateMsg(build);
} catch (WxErrorException e) {
log.error("【微信订阅消息】发送失败, {}", e.getMessage());
}
}