Java微信公众号推送消息
1、导入pom文件
<dependency>
<groupId>com.github.binarywang</groupId>
<artifactId>weixin-java-mp</artifactId>
<version>3.6.0</version>
</dependency>
2、编写yml文件
如果仅推送消息,只配置公众号的appid与secret
wx:
appid: xxxxxxxxxx
secret: xxxxxxxxxxx
3、配置文件
@Configuration
@ConfigurationProperties(prefix = "wx")
public class WxDto {
/**
* 公众号appId
*/
private String appId;
/**
* 公众号appSecret
*/
private String secret;
public String getAppId() {
return appId;
}
public void setAppId(String appId) {
this.appId = appId;
}
public String getSecret() {
return secret;
}
public void setSecret(String secret) {
this.secret = secret;
}
}
4、配置bean
主要实例化配置相关的APPID,secret等。
@Component
public class WxConfig {
private final WxDto wxProperties;
/**
* 构造
*
* @param wxMpProperties
*/
public WxConfig(WxDto wxProperties) {
this.wxProperties = wxProperties;
}
/**
* 微信客户端配置存储
*
* @return
*/
@Bean
public WxMpConfigStorage wxMpConfigStorage() {
WxMpDefaultConfigImpl configStorage = new WxMpDefaultConfigImpl();
// 公众号appId
configStorage.setAppId(wxProperties.getAppId());
// 公众号appSecret
configStorage.setSecret(wxProperties.getSecret());
return configStorage;
}
/**
* WxMpService多个实现类 声明一个实例
*
* @return
*/
@Bean
public WxMpService wxMpService() {
WxMpService wxMpService = new WxMpServiceImpl();
wxMpService.setWxMpConfigStorage(wxMpConfigStorage());
return wxMpService;
}
5、service 模板消息主要代码
@Service
public class WxMsgService {
/**
* 微信公众号API的Service
*/
@Resource
private WxMpService wxMpService;
public void sendWxMsg() {
WxMpTemplateMessage templateMessage = WxMpTemplateMessage.builder()
.toUser("xxxxxx") // 接收者openid
.templateId("xxxxxxx") // 模板id
.url("https://baidu.com/") //点击消息要访问的网址
.build();
templateMessage.addData(new WxMpTemplateData("first", "测试", "#FF00FF"))
.addData(new WxMpTemplateData("Topic", "这是测试", "#A9A9A9"))
.addData(new WxMpTemplateData("Time", "这又是测试", "#FF00FF"))
.addData(new WxMpTemplateData("Address", "这又又是测试", "#000000"))
.addData(new WxMpTemplateData("remark", "这还是测试", "#000000"));
String msgId = null;
try {
// 发送模板消息
msgId = wxMpService.getTemplateMsgService().sendTemplateMsg(templateMessage);
} catch (WxErrorException e) {
e.printStackTrace();
}
System.out.printf("推送微信模板信息", msgId != null ? "成功" : "失败");
}
}
6、外放接口测试
@RestController
@RequestMapping("/admin/send")
public class SendController {
@Resource
private WxMsgService wxmsg;
@GetMapping("/tosend")
public void tosend() {
wxmsg.sendWxMsg();
}
}
直接输入网址访问即可
注:
1、控制台报40164,解决方法:
进入微信开发者平台。在左侧菜单栏找到基本配置一项,将自己ip加到白名单里,问题解决
出现原因:公众号调用接口时都必须使用access_token
2、模板参数问题
一 一对应
// 模板key 内容 颜色
templateMessage.addData(new WxMpTemplateData("first", "测试", "#FF00FF"))
.addData(new WxMpTemplateData("Topic", "这是测试", "#A9A9A9"))