Simple use of Java to implement WeChat official account push template message

The following example is a simple use of Java code to implement WeChat official account push template message, does not include the code to jump to the applet webpage

1. Add dependency in pom.xml file

		<!-- lombok -->
		<dependency>
    		<groupId>org.projectlombok</groupId>
    		<artifactId>lombok</artifactId>
		</dependency>
		<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>
        <!-- json -->
        <dependency>
            <groupId>top.jfunc.json</groupId>
            <artifactId>json-fastjson</artifactId>
            <version>1.8.3</version>
        </dependency>

2. Entity class

@Getter
@Setter
public class DataEntity {
    
    	
	//内容
    private String value;
    //字体颜色
    private String color;
    
    public DataEntity(String value ,String color){
    
    
        this.value = value;
        this.color = color;
    }
}

3. Implementation class: The places with "XXX" need to be modified, other places can be left untouched. Application ID, key, template ID and other information can log in to the WeChat public account open platform to view the information corresponding to your company

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import org.springframework.stereotype.Component;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.gzds.entity.DataEntity;

@Component
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";
		//应用ID
		String appid = "XXXXXXXXXXXXXXXXXXX";
		//密钥
		String secret = "XXXXXXXXXXXXXXXXXXXXXXXXXX";
		// 接口地址拼接参数
		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 = "XXXXXXXXXXXXXX";
        //消息模板ID
        String template_id = "XXXXXXXXXXXXXXXXXXXXXX";
        //整体参数map
        Map<String, Object> paramMap = new HashMap<String, Object>();
        //消息主题显示相关map
        Map<String, Object> dataMap = new HashMap<String, Object>();
        //根据自己的模板定义内容和颜色
        dataMap.put("first",new DataEntity("详细内容XXXXXXX","#173177"));
        dataMap.put("keyword1",new DataEntity("私有化部署XXX","#173177"));
        dataMap.put("keyword2",new DataEntity("2020-08-18XXX" ,"#173177"));
        dataMap.put("remark",new DataEntity("申请成功XXX","#173177"));
        paramMap.put("touser", toUser);
        paramMap.put("template_id", template_id);
        paramMap.put("data", dataMap);
        paramMap.put("url",toUrl);
        //需要实现跳转网页的,可以添加下面一行代码实现跳转
        // paramMap.put("url","http://xxxxxx.html");
        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;
    }
}

4. Effect picture
Insert picture description here
If you have friends who don’t know how to obtain the user’s openId, you can try the method shown in the figure below: In the user management interface, press F12 to find the user id from the HTML page

Insert picture description here

Everyone is welcome to read. I have limited knowledge. It is inevitable that there are mistakes or omissions in the blog I wrote. I also hope that everyone will give me some advice. I would like to express my thanks

Your likes are my biggest encouragement

Guess you like

Origin blog.csdn.net/qq_41936224/article/details/108076005