以下是JAVA中微信公众号发送模板信息具体controller的代码:

@Controller
@RequestMapping("/wechat")
public class WechatController {
 
    @Autowired
    private WechatService wechatService;
 
    /**
     * 发送模板消息
     */
    @RequestMapping(value = "/sendTemplateMessage", method = RequestMethod.GET)
    @ResponseBody
    public Result sendTemplateMessage(@RequestParam("openid") String openid, @RequestParam("templateId") String templateId) {
        Result result = new Result();
        try {
            // 获取accessToken
            String accessToken = wechatService.getAccessToken();
 
            // 组装模板消息
            Map<String, Object> map = new HashMap<>();
            map.put("touser", openid);
            map.put("template_id", templateId);
            map.put("url", "http://www.example.com");
            Map<String, Object> data = new HashMap<>();
            Map<String, Object> first = new HashMap<>();
            first.put("value", "您好,您有一条新消息。");
            first.put("color", "#173177");
            data.put("first", first);
            Map<String, Object> keyword1 = new HashMap<>();
            keyword1.put("value", "消息标题");
            keyword1.put("color", "#173177");
            data.put("keyword1", keyword1);
            Map<String, Object> keyword2 = new HashMap<>();
            keyword2.put("value", "消息内容");
            keyword2.put("color", "#173177");
            data.put("keyword2", keyword2);
            Map<String, Object> remark = new HashMap<>();
            remark.put("value", "感谢您的关注。");
            remark.put("color", "#173177");
            data.put("remark", remark);
            map.put("data", data);
 
            // 发送模板消息
            String resultJson = HttpUtil.post("https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=" + accessToken, JsonUtil.toJson(map));
            JSONObject jsonObject = JSONObject.parseObject(resultJson);
            if (jsonObject.containsKey("errcode") && jsonObject.getInteger("errcode") != 0) {
                result.setCode(ResultCode.FAIL).setMsg("发送模板消息失败:" + jsonObject.getString("errmsg"));
            } else {
                result.setCode(ResultCode.SUCCESS).setMsg("发送模板消息成功");
            }
        } catch (Exception e) {
            result.setCode(ResultCode.FAIL).setMsg("发送模板消息失败:" + e.getMessage());
            e.printStackTrace();
        }
        return result;
    }
}

注:以上代码仅供参考,实际应用中需要根据具体情况进行调整

JAVA中微信公众号发送模板信息具体controller的代码

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

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