JAVA 微信公众号模板消息发送:wxMpService 代码示例
JAVA 微信公众号模板消息发送:wxMpService 代码示例
本文提供一个简单的 JAVA controller 代码示例,演示如何使用 wxMpService 库向微信公众号用户发送模板消息。
代码示例
import me.chanjar.weixin.common.exception.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.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller
public class WeixinTemplateController {
@Autowired
private WxMpService wxMpService;
@RequestMapping(value = "/sendTemplateMsg", method = RequestMethod.POST)
@ResponseBody
public String sendTemplateMsg(@RequestParam('openId') String openId,
@RequestParam('templateId') String templateId,
@RequestParam('url') String url,
@RequestParam('data') String data) {
try {
WxMpTemplateMessage templateMessage = WxMpTemplateMessage.builder()
.toUser(openId)
.templateId(templateId)
.url(url)
.build();
// 解析数据
JSONObject jsonObject = JSONObject.parseObject(data);
for (String key : jsonObject.keySet()) {
templateMessage.addData(new WxMpTemplateData(key, jsonObject.getString(key)));
}
wxMpService.getTemplateMsgService().sendTemplateMsg(templateMessage);
return "success";
} catch (WxErrorException e) {
// 记录错误日志
return "error";
}
}
}
代码解释
- 注入 WxMpService:使用
@Autowired注解注入WxMpService实例,该实例用于与微信公众号进行交互。 - 创建
sendTemplateMsg方法:该方法接收四个参数:openId:用户的 openIdtemplateId:模板消息 IDurl:点击模板消息后跳转的 URLdata:模板消息数据,以 JSON 字符串形式传入
- 创建
WxMpTemplateMessage对象:使用WxMpTemplateMessage.builder()创建一个模板消息对象,并设置toUser、templateId和url属性。 - 解析数据:使用
JSONObject.parseObject(data)解析传入的 JSON 数据,并将数据添加到模板消息对象中。 - 发送模板消息:使用
wxMpService.getTemplateMsgService().sendTemplateMsg(templateMessage)发送模板消息。 - 返回结果:如果发送成功,则返回 "success",否则返回 "error"。
注意
- 此代码示例仅供参考,实际实现可能会有所不同。
- 需要配置微信公众号的模板消息功能,并获取模板消息 ID。
- 使用此代码发送模板消息前,请确保用户已授权您的公众号获取其 openId。
更多信息
- 微信公众平台文档:https://developers.weixin.qq.com/doc/offiaccount/Message_Management/Template_Message_Interface.html
- wxMpService 文档:https://github.com/Wechat-Group/weixin-java-mp
原文地址: https://www.cveoy.top/t/topic/oOwA 著作权归作者所有。请勿转载和采集!