引入依赖
<!-- WxJava公众号 -->
<dependency>
<groupId>com.github.binarywang</groupId>
<artifactId>weixin-java-mp</artifactId>
<version>3.6.0</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<optional>true</optional>
</dependency>
配置application.yml
wx:
appid: appid
secret: secret
token: token
aeskey: aeskey
实体类
package com.hxecm.entity;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
@Data
@Component
@ConfigurationProperties(prefix = "wx")
public class WxMpProperties {
/**
* 公众号appId
*/
private String appId;
/**
* 公众号appSecret
*/
private String secret;
/**
* 公众号token
*/
private String token;
/**
* 公众号aesKey
*/
private String aesKey;
}
配置Config
package com.hxecm.config;
import com.hxecm.entity.WxMpProperties;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.api.impl.WxMpServiceImpl;
import me.chanjar.weixin.mp.config.WxMpConfigStorage;
import me.chanjar.weixin.mp.config.impl.WxMpDefaultConfigImpl;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import javax.annotation.Resource;
@Configuration
public class WxConfig {
@Resource
private WxMpProperties wxMpProperties;
/**
* 微信客户端配置存储
*
* @return
*/
@Bean
public WxMpConfigStorage wxMpConfigStorage() {
WxMpDefaultConfigImpl configStorage = new WxMpDefaultConfigImpl();
// 公众号appId
configStorage.setAppId(wxMpProperties.getAppId());
// 公众号appSecret
configStorage.setSecret(wxMpProperties.getSecret());
// 公众号Token
configStorage.setToken(wxMpProperties.getToken());
// 公众号EncodingAESKey
configStorage.setAesKey(wxMpProperties.getAesKey());
return configStorage;
}
/**
* 声明实例
*
* @return
*/
@Bean
public WxMpService wxMpService() {
WxMpService wxMpService = new WxMpServiceImpl();
wxMpService.setWxMpConfigStorage(wxMpConfigStorage());
return wxMpService;
}
}
业务类
package com.hxecm.service.impl;
import com.hxecm.dto.AlarmMsgDto;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.template.WxMpTemplateData;
import me.chanjar.weixin.mp.bean.template.WxMpTemplateMessage;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;
@Slf4j
@Component
public class WxMsgPush {
/**
* 微信公众号API的Service
*/
@Resource
private WxMpService wxMpService;
/**
* 发送微信模板信息
*
* @param openId 接受者openId
* @return 是否推送成功
*/
public Boolean SendWxMsg(String openId, AlarmMsgDto alarmMsgDto) {
// 发送模板消息接口
WxMpTemplateMessage templateMessage = WxMpTemplateMessage.builder()
// 接收者openid
.toUser(openId)
// 模板id
.templateId("templateId")
// 模板跳转链接
// .url("http://www.baidu.com")
.build();
// 添加模板数据
templateMessage.addData(new WxMpTemplateData("first", "您好!", "#FF00FF"))
.addData(new WxMpTemplateData("keyword1", "test" , "#FF00FF"))
.addData(new WxMpTemplateData("keyword2", "test", "#FF00FF"))
.addData(new WxMpTemplateData("keyword3", "test", "#FF00FF"))
.addData(new WxMpTemplateData("keyword4", "test", "#FF00FF"))
.addData(new WxMpTemplateData("keyword5", "test", "#FF00FF"))
.addData(new WxMpTemplateData("remark", "test", "#000000"));
String msgId = null;
try {
// 发送模板消息
msgId = wxMpService.getTemplateMsgService().sendTemplateMsg(templateMessage);
} catch (WxErrorException e) {
e.printStackTrace();
}
// log.warn("推送微信模板信息:{}", msgId != null ? "成功" : "失败");
return msgId != null;
}
}
其中,涉及到openID,及关注公众号会产生一哥用户看不到的openid,用户给用户推送消息
@Slf4j
@Service
public class WeChatServiceImpl implements WeChatService {
@Resource
private WeChatUserService wechatUserService;
@Override
public Boolean getOpenId(String code) throws JsonProcessingException {
// openId
String openId = "";
// 封装获取openId的微信API
StringBuffer url = new StringBuffer();
url.append("https://api.weixin.qq.com/sns/oauth2/access_token?appid=")
.append("appid")
.append("&secret=")
.append("secret")
.append("&code=")
.append(code)
.append("&grant_type=authorization_code");
// 返回结果集
String result = "";
ObjectMapper objectMapper = new ObjectMapper();
try {
// 根据地址获取请求 // 这里发送get请求
HttpGet request = new HttpGet(url.toString());
// 获取当前客户端对象
HttpClient httpClient = HttpClients.createDefault();
// 通过请求对象获取响应对象
HttpResponse response = httpClient.execute(request);
// 判断网络连接状态码是否正常(0--200都数正常)
if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
result = EntityUtils.toString(response.getEntity(), "utf-8");
}
} catch (Exception e) {
e.printStackTrace();
}
Map map = objectMapper.readValue(result, Map.class);
openId = String.valueOf(map.get("openid"));
if (StringUtils.isEmpty(openId) || "null".equals(openId)) {
return false;
}
return true;
}
/**
* 获取AccessToken
* @return
* @throws JsonProcessingException
*/
public String getAccessToken() throws JsonProcessingException {
// 用户的语言,简体中文为zh_CN
String accessToken = "";
// 构造获取用户基本信息api
StringBuffer url = new StringBuffer();
url.append("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&")
.append("appid=").append("appid")
.append("&secret=").append("secret");
// 返回结果集
String result = "";
ObjectMapper objectMapper = new ObjectMapper();
try {
// 根据地址获取请求 // 这里发送get请求
HttpGet request = new HttpGet(url.toString());
// 获取当前客户端对象
HttpClient httpClient = HttpClients.createDefault();
// 通过请求对象获取响应对象
HttpResponse response = httpClient.execute(request);
// 判断网络连接状态码是否正常(0--200都数正常)
if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
result = EntityUtils.toString(response.getEntity(), "utf-8");
}
} catch (Exception e) {
e.printStackTrace();
}
Map map = objectMapper.readValue(result, Map.class);
if (map.get("access_token") == null){
return "";
}
accessToken = String.valueOf(map.get("access_token"));
return accessToken;
}
}