- 模板消息仅用于公众号向用户发送重要的服务通知,只能用于符合其要求的服务场景中,如信用卡刷卡通知,商品购买成功通知等
- 注意:
-
1、所有服务号都可以在功能->添加功能插件处看到申请模板消息功能的入口,但只有认证后的服务号才可以申请模板消息的使用权限并获得该权限; 2、需要选择公众账号服务所处的2个行业,每月可更改1次所选行业; 3、在所选择行业的模板库中选用已有的模板进行调用; 4、每个账号可以同时使用25个模板。 5、当前每个账号的模板消息的日调用上限为10万次,单个模板没有特殊限制。
-
- 请求接口
-
public interface UrlConfig { // 微信公众号发送模板消息 String WxSendMsg="https://api.weixin.qq.com/cgi-bin/message/template/send"; // 微信公众号获取token String access_token="https://api.weixin.qq.com/sns/oauth2/access_token"; // 根据token微信公众号获取用户资料 String Wxuserinfo="https://api.weixin.qq.com/sns/userinfo"; }
-
- 微信公众号发送模板通知,需要用户在公众号进行登录操作,然后获取用户openid
@GetMapping("/wxLogin")
public Result wxLogin(String code){
//获取用户 code
System.out.println("用户的code是——>" + code);
//获取用户 token和用户openid
String token = HttpRequest.sendGet("https://api.weixin.qq.com/sns/oauth2/access_token", "appid=wxaaead59f6f71a6b5&secret=3eaf4939c3df0ad5426e493b406dbf3f&code=" + code + "&grant_type=authorization_code");
JSONObject jsonObject = JSONObject.parseObject(token);
System.out.println("jsonObject:" + jsonObject);
Object access_token = jsonObject.get("access_token");
System.out.println("用户的token是——>" + access_token);
String openid = (String) jsonObject.get("openid");
System.out.println("用户的openid是——>" + openid);
//获取用户userInfo
String userInfo = HttpRequest.sendGet("https://api.weixin.qq.com/sns/userinfo", "access_token=" + access_token + "&openid=" + openid + "&lang=zh_CN");
System.out.println(userInfo);
JSONObject userJSon = JSONObject.parseObject(userInfo);
System.out.println(userJSon);
Object nickname = userJSon.get("nickname");
Object sex = userJSon.get("sex");
Object unionid = userJSon.get("unionid");
System.out.println("用户微信名是——>" + nickname);
System.out.println("用户性别是——>" + sex);
System.out.println("用户unionid是——>" + unionid);
return null;
}
- 在微信公众平台中,添加模板,这里要记录模板的id,和模板需要传入的参数
- 进行发送模板
/**
* 微信公众号发送模板消息
* @param touser 接收者id
* @param template_id 模板id
* @param url 回调地址
* @param topcolor 字体样式
* @param data 发送的内容JSON
* @return
*/
public static String wxSendMsg(String touser, String template_id, String url, String topcolor, JSON data){
net.sf.json.JSONObject json = new net.sf.json.JSONObject();
json.accumulate("touser",touser);
json.accumulate("template_id",template_id);
json.accumulate("url",url);
json.accumulate("topcolor",topcolor);
json.accumulate("data",data);
String msg = json.toString();
String result = HttpRequest.sendPost(UrlConfig.WxSendMsg, msg);
System.out.println(result);
return result;
}
- 发送结果
-
点击模板可以选择跳转到网页或者小程序
-
如有问题请浏览,一起讨论