WeChat public account message push - template message sending

First register a WeChat public account; or apply for an interface test account for development;

Interface test number application link:

https://mp.weixin.qq.com/debug/cgi-bin/sandbox?t=sandbox/login

Here we first introduce the development of the test number;

Click on the link to enter the page, and you will see a QR code. After scanning with WeChat, you will be assigned a WeChat public test account;

Then find the following location, click the "Add Test Template" button, and fill in

 

Below is the relevant code;

       @Test
	public void sendTemplate(){
		postTemplateMsg("appid","appSecret", "openId");//Replace with your own information here
	}
	
	public  String  sendTemplateMessage(String openId){
		
	TemplateMsg tm=new TemplateMsg();
        tm.setTouser(openId);
        tm.setTemplate_id("TemplateId");
        tm.setUrl("https://wwww.baidu.com");
        
        //about data start
        Map<String,Object> m = new HashMap<String,Object>();  
    	TemplateData first = new TemplateData();  
    	first.setColor("#000000");    
    	first.setValue("Hello, you have a process to do to process:");    
    	m.put("first", first);  
    	  
    	TemplateData keyword1 = new TemplateData();    
    	keyword1.setColor("#000000");    
    	keyword1.setValue("11111111111111");    
    	m.put("keyword1", keyword1);  
    	  
    	TemplateData keyword2 = new TemplateData();    
    	keyword2.setColor("#000000");    
    	keyword2.setValue("Love you ten thousand years");    
    	m.put("keyword2", keyword2);  
    	  
    	TemplateData keyword3 = new TemplateData();    
    	keyword3.setColor("#000000");    
    	keyword3.setValue("2018.04.27 09:51:30");    
    	m.put("keyword3", keyword3);  
    	  
    	TemplateData keyword4 = new TemplateData();    
    	keyword4.setColor("#000000");    
    	keyword4.setValue("不够");    
    	m.put("keyword4", keyword4);  
    	  
    	TemplateData remark = new TemplateData();    
    	remark.setColor("#000000");    
    	remark.setValue("Add another 10,000 years");    
    	m.put("remark", remark);  
    	//about data end
        
	tm.setData(m);
		
	String jsonString = JSONObject.fromObject(tm).toString();
		
	System.out.println("jsonString:"+jsonString);
		
	return jsonString;
	}
	
	/**
     * Send template message
     * appId The unique identifier of the public account
     * appSecret public account key
     * openId User ID
     */
	public  void postTemplateMsg(String appId, String appSecret, String openId){
		Token token = CommonUtil.getToken(appId, appSecret);
        String access_token = token.getAccessToken();
        String requestUrl = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token="+access_token;

        System.out.println("requestUrl:"+requestUrl);
        
        String jsonString = sendTemplateMessage(openId);
        
        JSONObject jsonObject = CommonUtil.httpsRequest(requestUrl, "POST", jsonString);
		
        System.out.println("jsonObject="+jsonObject);    
        if (null != jsonObject) {  
            int errorCode = jsonObject.getInt("errcode");         
            if (0 == errorCode) {  
                System.out.println("Template message sent successfully!");  
            } else {  
                String errorMsg = jsonObject.getString("errmsg");  
                System.out.println("The template message failed to send, the error code is: "+errorCode+", the error message is: "+errorMsg);  
            }  
        }  
   }

  

/**
* class name: CommonUtil </br>
* Description: General tool class</br>
* Release version: V1.0 </br>
 */
public class CommonUtil {

    // Credential acquisition (GET)
    public final static String token_url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET";

    /**
     * Send https request
     *
     * @param requestUrl request address
     * @param requestMethod request method (GET, POST)
     * @param outputStr Submitted data
     * @return JSONObject (get the attribute value of the json object by JSONObject.get(key))
     */
    public static JSONObject httpsRequest(String requestUrl, String requestMethod, String outputStr) {
        JSONObject jsonObject = null;
        try {
            // Create an SSLContext object and initialize it with our specified trust manager
            TrustManager[] tm = { new MyX509TrustManager() };
            SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");
            sslContext.init(null, tm, new java.security.SecureRandom());
            // Get the SSLSocketFactory object from the above SSLContext object
            SSLSocketFactory ssf = sslContext.getSocketFactory();

            URL url = new URL(requestUrl);
            HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
            conn.setSSLSocketFactory(ssf);
            
            conn.setDoOutput(true);
            conn.setDoInput(true);
            conn.setUseCaches(false);
            // Set the request method (GET/POST)
            conn.setRequestMethod(requestMethod);

            // Write data to the output stream when outputStr is not null
            if (null != outputStr) {
                OutputStream outputStream = conn.getOutputStream();
                // Note the encoding format
                outputStream.write(outputStr.getBytes("UTF-8"));
                outputStream.close();
            }

            // Read the return content from the input stream
            InputStream inputStream = conn.getInputStream();
            InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");
            BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
            String str = null;
            StringBuffer buffer = new StringBuffer();
            while ((str = bufferedReader.readLine()) != null) {
                buffer.append(str);
            }

            // release resources
            bufferedReader.close();
            inputStreamReader.close();
            inputStream.close();
            inputStream = null;
            conn.disconnect();
            jsonObject = JSONObject.fromObject(buffer.toString());
        } catch (ConnectException ce) {
            System.out.println("Connection timed out: "+ce);
        } catch (Exception e) {
            System.out.println("https request exception: "+ e);
        }
        return jsonObject;
    }

    /**
     * Get interface access credentials
     *
     * @param appid credentials
     * @param appsecret key
     * @return
     */
    public static Token getToken(String appid, String appsecret) {
        Token token = null;
        String requestUrl = token_url.replace("APPID", appid).replace("APPSECRET", appsecret);
        
        
        System.out.println("requestUrl:"+requestUrl);
        
        
        //Initiate a GET request to get the credentials
        JSONObject jsonObject = httpsRequest(requestUrl, "GET", null);

        if (null != jsonObject) {
            try {
                token = new Token();
                token.setAccessToken(jsonObject.getString("access_token"));
                token.setExpiresIn(jsonObject.getInt("expires_in"));
            } catch (JSONException e) {
                token = null;
                // Failed to get token
                System.out.println("获取token失败 errcode:"+jsonObject.getInt("errcode")+"errmsg:"+jsonObject.getString("errmsg"));
            }
        }
        return token;
    }

    /**
     * URL encoding (utf-8)
     * @param source
     * @return
     */
    public static String urlEncodeUTF8(String source) {
        String result = source;
        try {
            result = java.net.URLEncoder.encode(source, "utf-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace ();
        }
        return result;
    }
    
    public static void main(String args[]) {
        //https://1d488f5d.ngrok.io/WeiXinProject/
        String source="https://565b4dad.ngrok.io/WeChatPublicNumber/oauthServlet";
        System.out.println(CommonUtil.urlEncodeUTF8(source));
        
    }
}

 over!

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324932594&siteId=291194637