以下是一个简单的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";
        }
    }
}

在上面的代码中,我们首先使用@Autowired注释注入WxMpService。然后,我们定义了一个sendTemplateMsg方法,该方法接受用户的openId、模板id、URL和数据。在方法中,我们首先创建一个WxMpTemplateMessage对象,并设置其属性。然后,我们解析数据并将其添加到模板消息中。最后,我们使用wxMpService发送模板消息。

请注意,此示例代码仅供参考,实际实现可能会有所不同

JAVA中微信公众号给用户发送模板信息使用wxMpService给出具体controller代码

原文地址: http://www.cveoy.top/t/topic/hlIK 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录