先注册一个微信公众号;或者申请接口测试号来进行开发;
接口测试号申请链接:
https://mp.weixin.qq.com/debug/cgi-bin/sandbox?t=sandbox/login
这里先介绍测试号的开发;
点击链接进入页面,会看到y一个二维码,用微信扫描后就会分配给你一个微信公众测试账号;
然后找到如下这个位置,点击“新增测试模板”按钮,填写
下面是相关代码;
@Test public void sendTemplate(){ postTemplateMsg("appid","appSecret", "openId");//这里替换成你自己的信息 } public String sendTemplateMessage(String openId){ TemplateMsg tm=new TemplateMsg(); tm.setTouser(openId); tm.setTemplate_id("模板Id"); 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("您好,您有一个流程待办需要处理:"); 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("爱你一万年"); 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("再加一万年"); m.put("remark", remark); //about data end tm.setData(m); String jsonString = JSONObject.fromObject(tm).toString(); System.out.println("jsonString:"+jsonString); return jsonString; } /** * 发送模板消息 * appId 公众账号的唯一标识 * appSecret 公众账号的密钥 * openId 用户标识 */ 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("模板消息发送成功!"); } else { String errorMsg = jsonObject.getString("errmsg"); System.out.println("模板消息发送失败,错误码是:"+errorCode+",错误信息是:"+errorMsg); } } }
/** * 类名: CommonUtil </br> * 描述: 通用工具类 </br> * 发布版本:V1.0 </br> */ public class CommonUtil { // 凭证获取(GET) public final static String token_url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET"; /** * 发送https请求 * * @param requestUrl 请求地址 * @param requestMethod 请求方式(GET、POST) * @param outputStr 提交的数据 * @return JSONObject(通过JSONObject.get(key)的方式获取json对象的属性值) */ public static JSONObject httpsRequest(String requestUrl, String requestMethod, String outputStr) { JSONObject jsonObject = null; try { // 创建SSLContext对象,并使用我们指定的信任管理器初始化 TrustManager[] tm = { new MyX509TrustManager() }; SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE"); sslContext.init(null, tm, new java.security.SecureRandom()); // 从上述SSLContext对象中得到SSLSocketFactory对象 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); // 设置请求方式(GET/POST) conn.setRequestMethod(requestMethod); // 当outputStr不为null时向输出流写数据 if (null != outputStr) { OutputStream outputStream = conn.getOutputStream(); // 注意编码格式 outputStream.write(outputStr.getBytes("UTF-8")); outputStream.close(); } // 从输入流读取返回内容 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); } // 释放资源 bufferedReader.close(); inputStreamReader.close(); inputStream.close(); inputStream = null; conn.disconnect(); jsonObject = JSONObject.fromObject(buffer.toString()); } catch (ConnectException ce) { System.out.println("连接超时:"+ ce); } catch (Exception e) { System.out.println("https请求异常:"+ e); } return jsonObject; } /** * 获取接口访问凭证 * * @param appid 凭证 * @param appsecret 密钥 * @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); // 发起GET请求获取凭证 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; // 获取token失败 System.out.println("获取token失败 errcode:"+jsonObject.getInt("errcode")+"errmsg:"+jsonObject.getString("errmsg")); } } return token; } /** * URL编码(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!