100字范文,内容丰富有趣,生活中的好帮手!
100字范文 > 微信公众号 java发送消息_微信公众号发送消息模板(java)

微信公众号 java发送消息_微信公众号发送消息模板(java)

时间:2020-04-29 12:59:04

相关推荐

微信公众号 java发送消息_微信公众号发送消息模板(java)

这段时间接触公众号开发,写下向用户发送消息模板的接口调用

先上接口代码

1 public staticJSONObject sendModelMessage(ServletContext context,JSONObject jsonMsg) {2 System.out.println("消息内容:"+jsonMsg);3 boolean result = false;4 try{5 getWX_AccessToken(context);6 } catch(Exception e) {7 //TODO Auto-generated catch block

8 e.printStackTrace();9 }10 //拼接请求地址

11 String requestUrl = "https://api./cgi-bin/message/template/send?access_token=ACCESS_TOKEN";12 requestUrl = requestUrl.replace("ACCESS_TOKEN", context.getAttribute(ContextTokenName).toString());1314 //发送客服消息

15 JSONObject jsonObject = getJsonByWX(requestUrl, context, "POST",jsonMsg, false);16

17 if (null !=jsonObject) {18 int errorCode = jsonObject.getInt("errcode");19 String errorMsg = jsonObject.getString("errmsg");20 if (0 ==errorCode) {21 result = true;22 System.out.println("模板消息发送成功 errcode:{} "+errorCode+"----"+errorMsg);23 } else{24 System.out.println("模板消息发送失败 errcode:{} "+errorCode+"----"+errorMsg);25 }26 }27

28 return null;29 }

15行那段getJsonByWX是统一调用微信接口的方法,每个项目都有自己的调用方法,我这里就不贴了。接口调用链接:https://api./cgi-bin/message/template/send?access_token=ACCESS_TOKEN

接下来就是建个bean类,里面写入一下颜色及值

1 privateString value;2 privateString color;3

4 publicString getValue() {5 returnvalue;6 }7

8 public voidsetValue(String value) {9 this.value =value;10 }11

12 publicString getColor() {13 returncolor;14 }15

16 public voidsetColor(String color) {17 this.color =color;18 }

在公众号里填写模板消息的对应格式

之后就是有个触发点,我选择发货后把发货信息发送给用户

PageData wechatTemplate = newPageData();

wechatTemplate.put("template_id", "填写你的模板id");

wechatTemplate.put("touser", userInfo.get("openid"));//获取用户的openid

Map mapdata = new HashMap<>();

TemplateMessageUtil first= newTemplateMessageUtil();

first.setColor("#173177");

first.setValue("发货通知");

mapdata.put("first", first);

TemplateMessageUtil text1= newTemplateMessageUtil();

text1.setColor("#173177");

text1.setValue("您好,您所购买的商品已发货。");

mapdata.put("text1", text1);

TemplateMessageUtil text2= newTemplateMessageUtil();

text2.setColor("#173177");

text2.setValue(expresser_name);

mapdata.put("text2", text2);

TemplateMessageUtil text3= newTemplateMessageUtil();

text3.setColor("#173177");

text3.setValue(expresser_phone);

mapdata.put("text3", text3);

TemplateMessageUtil remark= newTemplateMessageUtil();

remark.setColor("#173177");

remark.setValue("请保持电话畅通>>");

mapdata.put("remark", remark);

JSONObject json= newJSONObject();

json.put("data",mapdata);

json.putAll(wechatTemplate);//转为json

WXInterface.sendModelMessage(context,json);

之后手机就会收到信息了

整体思路是这样,也是参照百度而来,因为每个人的项目里方法都不一样,我就不详细贴上,既然做到发送模板消息了,统一调用微信接口的方法应每个人该也早写在工具类里了,每个人都不同,当应该都有,调用这个方法,把微信模板消息连接的条件access_token写进去就请求了,剩下的就是传入你要发送的消息,消息存入集合,集合转json才行,JSONObject类相信也都有,我也不贴了,每个人项目都不一样,没必要照搬过去,就照着自己原先已有的类改进。

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。