Java中实现微信公众号模板消息推送
2019-10-24 本文已影响0人
闲置的Programmer
主要流程:
1、在微信公众测试平台上注册账号,关注测试公众号,新增消息模板
2、拿到需要的参数openId appId appsecret 模板Id后进行开发
微信公众平台测试号管理地址 https://mp.weixin.qq.com/debug/cgi-bin/sandboxinfo?action=showinfo&t=sandbox/index
微信开放文档地址 https://developers.weixin.qq.com/doc/offiaccount/Basic_Information/Get_access_token.html
微信模板消息接口文档1 https://developers.weixin.qq.com/doc/offiaccount/Message_Management/Template_Message_Interface.html
微信模板消息接口文档2 https://mp.weixin.qq.com/debug/cgi-bin/readtmpl?t=tmplmsg/faq_tmpl
微信获取Access_token接口文档 https://developers.weixin.qq.com/doc/offiaccount/Basic_Information/Get_access_token.html
如上所示3、消息参数定义规则
消息参数定义规则
4、完了之后就只需简单的在Java中调用外部第三方接口了,完整代码如下
目录结构pom.xml
<dependency>
<groupId>org.wso2.apache.httpcomponents</groupId>
<artifactId>httpmime</artifactId>
<version>4.3.1.wso2v1</version>
</dependency>
<dependency>
<groupId>org.wso2.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.3.1.wso2v1</version>
</dependency>
<!-- https://mvnrepository.com/artifact/top.jfunc.json/json-fastjson -->
<dependency>
<groupId>top.jfunc.json</groupId>
<artifactId>json-fastjson</artifactId>
<version>1.8.3</version>
</dependency>
/**
* create by pengyouqi
* 2019/10/24 10:49:13
*/
public class DataEntity {
private String value;
private String color;
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
public String getColor() {
return color;
}
public void setColor(String color) {
this.color = color;
}
public DataEntity(String value ,String color){
this.value = value;
this.color = color;
}
}
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
/**
* create by pengyouqi
* 2019/10/24 10:15:33
*/
public class wechatMsg {
public static void main(String[] args) {
wechatMsg wm = new wechatMsg();
wm.SendWeChatMsg(wm.getToken());
}
/**
* 获取token
* @return token
*/
public String getToken(){
//授予形式
String grant_type = "client_credential";
String appid = "XXXXXXXXXXXXXXXXXX";
String secret = "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";
//接口地址拼接参数
String getTokenApi = "https://api.weixin.qq.com/cgi-bin/token?grant_type="+grant_type+"&appid="+appid+"&secret="+secret;
String tokenJsonStr = doGetPost(getTokenApi,"GET",null);
JSONObject tokenJson = JSONObject.parseObject(tokenJsonStr);
String token = tokenJson.get("access_token").toString();
System.out.println("获取到的TOKEN : "+token);
return token;
}
/***
* 发送消息
* @param token
*/
public void SendWeChatMsg(String token ){
//接口地址
String sendMsgApi = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token="+token;
//openId
String toUser = "oBH8O0kmvQ5nXiDN0JWQ_79gfP1g";
//消息模板ID
String template_id = "dMprAMJa_FA6KuimBWNonuyFtyp43_SJw8Um3jyeuZM";
String toUrl = "http://weixin.qq.com/download";
//整体参数map
Map<String, Object> paramMap = new HashMap<String, Object>();
//点击消息跳转相关参数map
Map<String, String> miniprogramMap = new HashMap<String, String>();
//消息主题显示相关map
Map<String, Object> dataMap = new HashMap<String, Object>();
miniprogramMap.put("appid","");
miniprogramMap.put("pagepath","");
dataMap.put("params1",new DataEntity("从不超田","#173177"));
dataMap.put("params2",new DataEntity("喜欢发癫","#173177"));
dataMap.put("params3",new DataEntity("七彩螺旋","#173177"));
dataMap.put("params4",new DataEntity("憨牛上天","#173177"));
paramMap.put("touser", toUser);
paramMap.put("template_id", template_id);
paramMap.put("url", toUrl);
paramMap.put("miniprogram", miniprogramMap);
paramMap.put("data", dataMap);
System.out.println(doGetPost(sendMsgApi,"POST",paramMap));
}
/**
* 调用接口 post
* @param apiPath
*/
public String doGetPost(String apiPath,String type,Map<String,Object> paramMap){
OutputStreamWriter out = null;
InputStream is = null;
String result = null;
try{
URL url = new URL(apiPath);// 创建连接
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setUseCaches(false);
connection.setInstanceFollowRedirects(true);
connection.setRequestMethod(type) ; // 设置请求方式
connection.setRequestProperty("Accept", "application/json"); // 设置接收数据的格式
connection.setRequestProperty("Content-Type", "application/json"); // 设置发送数据的格式
connection.connect();
if(type.equals("POST")){
out = new OutputStreamWriter(connection.getOutputStream(), "UTF-8"); // utf-8编码
out.append(JSON.toJSONString(paramMap));
out.flush();
out.close();
}
// 读取响应
is = connection.getInputStream();
int length = (int) connection.getContentLength();// 获取长度
if (length != -1) {
byte[] data = new byte[length];
byte[] temp = new byte[512];
int readLen = 0;
int destPos = 0;
while ((readLen = is.read(temp)) > 0) {
System.arraycopy(temp, 0, data, destPos, readLen);
destPos += readLen;
}
result = new String(data, "UTF-8"); // utf-8编码
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return result;
}
}