正常我们企业开发,实现微信模版消息推送,必须要有微信公众号,备案的网址,并且最麻烦的一点是要获取到用户的openid,作为个人,这些条件基本上都不具备。所以今天就来带大家注册微信开发测试账号,来轻松实现微信模版消息推送。
实现的三个步骤:
1.微信测试账号的申请
2.微信模版推送的配置
3.springboot实现java后台
一,首先我们要注册微信测试账号,并做相关配置
1,微信扫码登录下面网址
https://mp.weixin.qq.com/debug/cgi-bin/sandbox?t=sandbox/login
扫码登录成功后,就会给我们生成微信公号的appid和appsecret
2,微信扫码关注 测试号二维码,微信给我们返回我们的openid,这个openid在推送时特别重要。因为你推送肯定要知道推送给谁啊。这个openid就是我们要推送给那个用户的唯一标示。
3.找到下面新增测试模板,点击添加模板标题和内容,添加结束后如下图,拿到模板ID
拿到这些以后,我们就可以去实现微信推送了。推送的代码如下。
二,springboot创建java后台
1.在pom.xml文件里引入下面类库
<!--微信模版消息推送三方sdk--> <dependency> <groupId>com.github.binarywang</groupId> <artifactId>weixin-java-mp</artifactId> <version>3.3.0</version> </dependency>
2.写一个推送的controller
package com.example.wx.xiaochengxu.controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import me.chanjar.weixin.mp.api.WxMpInMemoryConfigStorage;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.api.impl.WxMpServiceImpl;
import me.chanjar.weixin.mp.bean.template.WxMpTemplateMessage;
@RestController
public class XcxController {
/*
* 微信测试账号推送
* */
@GetMapping("/push")
public void push() {
//1,配置
WxMpInMemoryConfigStorage wxStorage = new WxMpInMemoryConfigStorage();
wxStorage.setAppId("wxabb1b7910c1927dd");
wxStorage.setSecret("eb09a046fbc48b6d60ba044844e73d17");
WxMpService wxMpService = new WxMpServiceImpl();
wxMpService.setWxMpConfigStorage(wxStorage);
//2,推送消息
WxMpTemplateMessage templateMessage = WxMpTemplateMessage.builder()
.toUser("oeAC66bZTd6yFKSTAFw6mzHTS88Q")//要推送的用户openid
.templateId("aOHEn4P8_lQVaO5pBb6dBs9HVFG5FCgIHXw3XFgzUv4")//模版id
.url("https://30paotui.com/")//点击模版消息要访问的网址
.build();
//3,如果是正式版发送模版消息,这里需要配置你的信息
// templateMessage.addData(new WxMpTemplateData("name", "value", "#FF00FF"));
// templateMessage.addData(new WxMpTemplateData(name2, value2, color2));
try {
wxMpService.getTemplateMsgService().sendTemplateMsg(templateMessage);
} catch (Exception e) {
System.out.println("推送失败:" + e.getMessage());
e.printStackTrace();
}
}
}
启动访问接口,测试号接收到推送消息,效果如下图~