1.首先需要在微信开放平台订阅消息中生成自己的模板。
生成模板后获取到对应的 template_id
对于客户端来说,主要的工作就是诱导 用户给予推送权限
服务端则负责向微信开放平台请求推送
代码如下:
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import org.springframework.stereotype.Service;
@Service
public class MessageUtil {
//用来获取access_token
public String getAccessToken() {
//这两个都是开发者平台来的,一定要对应上
String appId = "";
String appSecret = "";
//这是请求的接口路径,这个是不变的
String result = cn.hutool.http.HttpUtil.get("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + appId + "&secret=" + appSecret);
JSONObject jsonObject = JSONUtil.parseObj(result);
return jsonObject.getStr("access_token");
}
public String send(String openId,String template_id,JSONObject json){
JSONObject body=new JSONObject();
//用户openId
body.set("touser",openId);
//模板Id,就是你申请的那个模板
body.set("template_id",template_id);
//方法中传进来,下面会具体讲解这是啥
body.set("data",json);
//发送
String accessToken= getAccessToken();
System.out.println("accessToken:"+accessToken);
//向开放平台申请发送推送
String post = cn.hutool.http.HttpUtil.post("https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=" + accessToken, body.toString());
System.out.println("post:"+post);
return "ok";
}
}
下面举个使用的例子,我这里是支付成功后,发送订阅消息
@RequestMapping(value = "/weChatReturnCommodity")
public void weChatReturnCommodity(HttpServletRequest request, HttpServletResponse response) throws Exception {
//前面为支付代码
//发送订阅
Calendar now = Calendar.getInstance();
String date= now.get(Calendar.YEAR)+"年"+now.get(Calendar.MONTH)+"月"+now.get(Calendar.DAY_OF_MONTH)+"日";
JSONObject json=new JSONObject();
//这下面是封装json 下面的character_string1 thing2 amount4 是根据自己申请的填的,记住有对应的string 类型啥的,开发文档中有标注,别填错了
json.set("character_string1",new JSONObject().set("value",oId));
json.set("thing2",new JSONObject().set("value", mallRevenue.getCommodity().getCommodityName()));
json.set("amount4",new JSONObject().set("value",mallRevenue.getMoney()));
json.set("thing5",new JSONObject().set("value", mallRevenue.getPoint()));
json.set("time9",new JSONObject().set("value",date));
//模板Id
String template_id="";
//发送推送
messageUtil.send(indexUser.getOpenid(),template_id,json);
}
完成