最新需要在微信公众号菜单中做一个点击产生发送图片的功能。大概流程如下:
- 增加菜单入口
- 上传图片素材到微信服务端。
- 点击菜单,微信会推送消息,根据推送消息的key确定是否是该点击事件,如果是,返回微信包含素材id的报文。
- 微信推送图片给用户微信公众号。
- 引入jar包
<dependency>
<groupId>com.github.binarywang</groupId>
<artifactId>weixin-java-mp</artifactId>
<version>${weixin-java-mp.version}</version>
</dependency>
- 增加菜单入口(代码)
@PostMapping("/createMenuJson/{appid}")
public String menuCreate(@PathVariable String appid, @RequestBody String json) throws WxErrorException {
return this.wxMpService.switchoverTo(appid).getMenuService().menuCreate(json);
}
- 增加菜单入口(菜单)
{
"button":[
{
"name":"借款",
"sub_button":[
{
"type":"click",
"name":"test",
"key":"push_pic_1"
}]
},{
"name":"优惠",
"sub_button":[
{
"type":"click",
"name":"推荐红包",
"key":"push_pic_2"
}]
},
{
"name":"我的",
"sub_button":[
{
"type":"click",
"name":"公司简介",
"key":"push_pic_3"
}
]
}]
}
- 上传图片素材到微信服务端
@PostMapping("/uploadImageToWc")
public AjaxResult uploadImageToWc(HttpServletRequest request, @RequestParam(value = "picFile") MultipartFile picFile, @RequestParam(value = "picKey") String picKey) {
String mediaId = "";
if (picFile != null) {
WxMpMaterial wxMpMaterial = new WxMpMaterial();
WxMpMaterialUploadResult result = null;
try {
String storeFilePath = creditAppProperties.getStoreFilePath() ;
if (!storeFilePath.endsWith("/")) {
storeFilePath += "/";
}
String picName = UUID.fastUUID().toString();
String storeDir = storeFilePath + "wx/pushPic/";
File file = new File(storeDir);
if(!file.isDirectory()){
file.mkdirs();
}
File f1 = new File(file + picName + ".jpeg");
FileUtils.copyInputStreamToFile(picFile.getInputStream(), f1);
wxMpMaterial.setFile(f1);
wxMpMaterial.setName("push_pic" + picName);
result = this.wxMpService.getMaterialService().materialFileUpload(WxConsts.MaterialType.IMAGE, wxMpMaterial);
log.info("获取微信素材id= {}", JSON.toJSONString(result));
//说明,这里需要先插入一条记录到字典表中,这里只要更新mediaId字段即可。
sysParamsConfMapper.updateValByParamKey(picKey, result.getMediaId());
mediaId = result.getMediaId();
} catch (Exception e) {
log.error("操作失败", e);
return AjaxResult.error();
}
}
return AjaxResult.success(mediaId);
}
- 微信会推送消息,根据推送消息的key确定是否是该点击事件,如果是,返回微信包含素材id的报文
@Slf4j
@Component
public class MsgHandler extends AbstractHandler {
@Override
public WxMpXmlOutMessage handle(WxMpXmlMessage wxMessage,
Map<String, Object> context, WxMpService weixinService,
WxSessionManager sessionManager) {
if(wxMessage != null && "click".equalsIgnoreCase(wxMessage.getEvent()) && wxMessage.getEventKey() != null) {
SysParamsConf sysParamsConf = sysParamsConfMapper.selectByParamKey(wxMessage.getEventKey());
if(sysParamsConf != null && sysParamsConf.getParamVal() != null) {
return new ImageBuilder().build(sysParamsConf.getParamVal(), wxMessage, weixinService);
}
return new ImageBuilder().build("默认mediaId", wxMessage, weixinService);
}
}
}