最近同时在做微信的公众号和小程序,公众号要求用户消费后给推送消费信息 ,去微信看开发文档,做完后发现一直返回不成功,最后一看看错文档了,开发公众号看的小程序的文档,这里列出两个文档点击直接进去:公众号接口文档;小程序接口文档。
两个接口的最大区别在模板发送模板消息时的请求地址和参数,开发的时候要注意小程序多了一个form_id的参数。两个接口的整体流程一样都是先获取access_token,具体怎么申请模板、获取access_token、发送请求看文档就可以了,下面是我用java在写的例子供其参考。
1、获取access_token:
public String getAccessToken(String value,String color){
String token=HttpRequest.sendGet("https://api.weixin.qq.com/cgi-bin/token",
"grant_type=client_credential&appid=公众号appid&secret=公众号appsecret");
Map<String, Object> map = JSON.parseObject(token, new TypeReference<Map<String, Object>>() {});
String access_token = map.get("access_token").toString();
return access_token;
}
2、获取access_token:
我没有用文档的获取模板那几步,而是直接在公众号平台复制的模板id,所以直接进入发送模板消息。
//模板内容赋值
public Map<String, Object> getKeyword(String value,String color){
Map<String, Object> hm = new HashMap<>();
hm.put("value",value);
hm.put("color",color);
return hm;
}
//发送模板消息
public String sendTemplateMessage(){
String access_token = getAccessToken();
Map<String, Object> hm = new HashMap<>();
Map<String, Object> hm1 = new HashMap<>();
hm1.put("first",getKeyword("first",""));
hm1.put("keyword1",getKeyword("1",""));
hm1.put("keyword2",getKeyword("2",""));
hm1.put("keyword3",getKeyword("3",""));
hm1.put("remark",getKeyword("remark",""));
hm.put("touser","oqU2k0uYB0mQx***u5NyVHw");//用户openid
hm.put("template_id","8viZctSEUi1Pw*****btWWebMgKgrPPc8r0");//模板id
hm.put("url","http://weixin.qq.com/download");//调转页面
hm.put("data",hm1);
String dataJson = JSON.toJSONString(hm);
String data=HttpRequest.sendPost("https://api.weixin.qq.com/cgi-bin/message/template/send?access_token="+access_token,dataJson);
return data;
}