赞
踩
使用自己微信号登录即可
<button type="default" bindtap="sendDYMsg">订阅模板消息</button>
,
sendDYMsg: function(e) {
wx.requestSubscribeMessage({
tmplIds: ['6Bci11EozQriga8JK4X56GqUtbpdhBtJHxvyJk56ygw'],
success(res) {
console.log("可以给用户推送一次消息了。。。");
}
})
}
<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.4.4</version> <relativePath/> <!-- lookup parent from repository --> </parent> <groupId>com.study.wechat</groupId> <artifactId>applet</artifactId> <version>0.0.1-SNAPSHOT</version> <name>applet</name> <description>Demo project for Spring Boot</description> <properties> <java.version>1.8</java.version> </properties> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>com.github.binarywang</groupId> <artifactId>weixin-java-miniapp</artifactId> <version>3.8.0</version> </dependency> <!-- https://mvnrepository.com/artifact/org.projectlombok/lombok --> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <version>1.18.12</version> <scope>provided</scope> </dependency> <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger2</artifactId> <version>2.9.2</version> </dependency> <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger-ui</artifactId> <version>2.9.2</version> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build> </project>
wx: miniapp: appId: 'wx63f8318b2deb08c8' appSecret: '3051cb6494712466bac822472aa230d5' templates: - id: '' type: 'releaseWithoutSignIn' stationDetails: '' bookingTime: '' bookingStaff: '' checkInTime: '' tipInstruction: '' page: '' - id: '6Bci11EozQriga8JK4X56GqUtbpdhBtJHxvyJk56ygw' type: 'sensorRelease' stationDetails: 'character_string7' bookingTime: 'thing8' bookingStaff: 'thing10' checkInTime: 'thing12' tipInstruction: 'character_string14' page: '' server: port: 8080
package com.study.wechat.applet.config; import java.util.List; import lombok.Data; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.stereotype.Component; @Data @Component @ConfigurationProperties(prefix = "wx.miniapp") public class WxConfig { private String appId; private String appSecret; private List<Template> templates; @Data public static class Template { /** * 模板id */ private String id; /** * 模板类型 */ private String type; /** * 工位详情 */ private String stationDetails; /** * 预订时间 */ private String bookingTime; /** * 预订人员 */ private String bookingStaff; /** * 签到时间 */ private String checkInTime; /** * 提示说明 */ private String tipInstruction; /** * 跳转到哪个页面 */ private String page; } }
package com.study.wechat.applet.config; import com.study.wechat.applet.config.WxConfig.Template; import com.study.wechat.applet.utils.SendMiniAppUtils; import java.util.HashMap; import java.util.Map; import java.util.stream.Collectors; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; /** * @author wenjun * @date 2021/3/19 18:30 */ @Configuration public class WxAppletsConfig { @Autowired private WxConfig wxConfig; public static Map<String, Template> wxTemplates = new HashMap<>(); @Bean public SendMiniAppUtils sendMiniAppUtils() { wxTemplates = wxConfig.getTemplates().stream() .collect(Collectors.toMap(Template::getType, template -> template)); return new SendMiniAppUtils(wxConfig.getAppId(), wxConfig.getAppSecret()); } }
package com.study.wechat.applet.config; /** * @author wenjun * @date 2021/3/19 20:44 */ import io.swagger.annotations.ApiOperation; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import springfox.documentation.builders.RequestHandlerSelectors; import springfox.documentation.spi.DocumentationType; import springfox.documentation.spring.web.plugins.Docket; import springfox.documentation.swagger2.annotations.EnableSwagger2; @Configuration @EnableSwagger2 public class SwaggerConfig { @Bean public Docket swaggerSpringMvcPlugin() { return new Docket(DocumentationType.SWAGGER_2).select() .apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class)).build(); } }
package com.study.wechat.applet.manager; import com.study.wechat.applet.config.WxConfig; import com.study.wechat.applet.config.WxConfig.Template; import java.util.HashMap; import java.util.Map; import java.util.stream.Collectors; import javax.annotation.PostConstruct; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; /** * @author wenjun * @date 2021/3/20 14:18 */ @Component @Slf4j public class WeChatManager { @Autowired private WxConfig config; public static Map<String, Template> wxTemplates = new HashMap<>(); @PostConstruct public void init() { wxTemplates = config.getTemplates().stream() .collect(Collectors.toMap(Template::getType, template -> template)); } public Template getTemplateByType(String type) { return wxTemplates.get(type); } }
package com.study.wechat.applet.utils; import cn.binarywang.wx.miniapp.api.WxMaMsgService; import cn.binarywang.wx.miniapp.api.impl.WxMaServiceImpl; import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult; import cn.binarywang.wx.miniapp.bean.WxMaSubscribeMessage; import cn.binarywang.wx.miniapp.bean.WxMaSubscribeMessage.Data; import cn.binarywang.wx.miniapp.config.impl.WxMaDefaultConfigImpl; import java.util.List; import me.chanjar.weixin.common.error.WxErrorException; import org.springframework.util.StringUtils; /** * @author wenjun * @date 2021/3/13 16:13 */ public class SendMiniAppUtils { private WxMaMsgService msgService; private WxMaServiceImpl wxMaService; /** * description: 构造函数(初始化配置) param: wxMpConfig 配置内容 */ public SendMiniAppUtils(String appId, String appSercret) { if (StringUtils.isEmpty(appId)) { throw new RuntimeException("appId不能为空"); } if (StringUtils.isEmpty(appSercret)) { throw new RuntimeException("secret不能为空"); } WxMaDefaultConfigImpl config = new WxMaDefaultConfigImpl(); config.setAppid(appId); config.setSecret(appSercret); wxMaService = new WxMaServiceImpl(); wxMaService.setWxMaConfig(config); msgService = wxMaService.getMsgService(); } /** * 根据code获取openID */ public String getOpenIdByCode(String code) { WxMaJscode2SessionResult session = null; try { session = wxMaService.getUserService().getSessionInfo(code); return session.getOpenid(); } catch (WxErrorException e) { e.printStackTrace(); } return null; } /** * description: 发送订阅消息 param: openId 用户的openid param: templateId 模板id param: dataParam 参数内容 */ public void sendSubscribeMsg(String openId, String templateId, List<Data> dataParam) throws WxErrorException { // 3.8.0版本使用的使用WxMaSubscribeMessage WxMaSubscribeMessage.WxMaSubscribeMessageBuilder builder = WxMaSubscribeMessage.builder(); builder.toUser(openId);//推送消息的目标对象openId builder.templateId(templateId); //这里填写的就是在后台申请添加的模板ID builder.data(dataParam);//添加请求参数 WxMaSubscribeMessage msg = builder.build(); msgService.sendSubscribeMsg(msg); } /** * description: 发送订阅消息 param: openId 用户的openid param: templateId 模板id param: dataParam 参数内容 param: * page 跳转链接 */ public void sendSubscribeMsg(String openId, String templateId, List<WxMaSubscribeMessage.Data> dataParam, String page) throws WxErrorException { // 3.8.0版本使用的使用WxMaSubscribeMessage WxMaSubscribeMessage.WxMaSubscribeMessageBuilder builder = WxMaSubscribeMessage.builder(); builder.toUser(openId);//推送消息的目标对象openId builder.templateId(templateId); //这里填写的就是在后台申请添加的模板ID builder.data(dataParam);//添加请求参数 builder.page(page); //添加跳转链接,如果目标用户点击了推送的消息,则会跳转到小程序主页 WxMaSubscribeMessage msg = builder.build(); msgService.sendSubscribeMsg(msg); } }
package com.study.wechat.applet.controller; import cn.binarywang.wx.miniapp.bean.WxMaSubscribeMessage.Data; import com.study.wechat.applet.config.WxConfig.Template; import com.study.wechat.applet.manager.WeChatManager; import com.study.wechat.applet.utils.SendMiniAppUtils; import io.swagger.annotations.Api; import io.swagger.annotations.ApiImplicitParam; import io.swagger.annotations.ApiImplicitParams; import io.swagger.annotations.ApiOperation; import java.util.ArrayList; import java.util.List; import lombok.extern.slf4j.Slf4j; import me.chanjar.weixin.common.error.WxErrorException; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.RestController; /** * @author wenjun * @date 2021/3/22 17:16 */ @Api("微信小程序订阅消息推送接口") @RestController @RequestMapping("/wx/msg/") @Slf4j public class WxAppletsController { @Autowired SendMiniAppUtils sendMiniAppUtils; @Autowired private WeChatManager weChatManager; @ApiOperation(value = "微信小程序推送订阅消息", notes = "微信小程序推送订阅消息") @ApiImplicitParams({ @ApiImplicitParam(name = "code", value = "用户code", dataType = "String", paramType = "query")}) @GetMapping(value = "/getOpenIdByCode") @ResponseBody public Object getOpenIdByCode(String code) { String openIdByCode = sendMiniAppUtils.getOpenIdByCode(code); log.info("openID:{}", openIdByCode); return openIdByCode; } /** * 微信小程序推送订阅消息 create By KingYiFan on 2020/01/06 */ @ApiOperation(value = "微信小程序推送订阅消息", notes = "微信小程序推送订阅消息") @ApiImplicitParams({ @ApiImplicitParam(name = "openId", value = "openId", dataType = "String", paramType = "query")}) @GetMapping(value = "/sendDYTemplateMessage") @ResponseBody public Object sendDYTemplateMessage(String openId) { Template template = weChatManager.getTemplateByType("sensorRelease"); List<Data> dataList = new ArrayList<>(); Data data = new Data(); data.setName(template.getStationDetails()); data.setValue("01 08 09 13 16 33+01"); dataList.add(data); Data data1 = new Data(); data1.setName(template.getBookingTime()); data1.setValue("最终开奖结果请已彩票官网为准"); dataList.add(data1); Data data2 = new Data(); data2.setName(template.getBookingStaff()); data2.setValue("孙先生"); dataList.add(data2); Data data3 = new Data(); data3.setName(template.getCheckInTime()); data3.setValue("2020-05-26前"); dataList.add(data3); Data data4 = new Data(); data4.setName(template.getTipInstruction()); data4.setValue("202009182021331001"); dataList.add(data4); try { /* String openIdByCode = sendMiniAppUtils.getOpenIdByCode(code); log.info("openID:{}",openIdByCode);*/ sendMiniAppUtils .sendSubscribeMsg(openId, template.getId(), dataList, template.getPage()); log.info("推送成功!!!"); } catch (WxErrorException e) { log.error("错误消息:{}", e.getMessage()); e.printStackTrace(); } return "推送失败"; } }
到这里就可以了!!!,使用postMan发送微信就可以接受到消息了
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。