1. 程式人生 > >微信公眾號推送模板訊息

微信公眾號推送模板訊息

微信支付成功之後需要將一些訂單相關的資訊傳送到使用者的微信上,這時候就需要使用微信【模板訊息】

建立模板訊息

進入【微信·公眾平臺】在【功能】->【新增功能外掛】中找到【模板訊息】,之後填入相關的資訊並通過稽核之後即可使用微信模板訊息
這裡寫圖片描述
先從【模板庫】選擇一個合適模板,之後新增到【我的模板】中
這裡寫圖片描述
可以看到模板ID,接下來我們就需要使用這個ID去給指定的使用者推送模板訊息了

為指定的使用者推送模板訊息

執行此操作之前需要使用者的openid和要用到的模板需要什麼引數,這點可以通過模板的【詳情】進行檢視,我這裡的模板需要三個引數first、orderMoneySum、orderProductName
這裡寫圖片描述


接下來就需要進行推送資訊了,首先我們需要獲取使用者的openid、模板ID、模板引數資料,將它們以JSON的格式放在String中,之後以POST的方式將這個String提交到https://api.weixin.qq.com/cgi-bin/message/template/send中,程式碼實現如下

//對該購買使用者進行推送微信訊息
//要推送的使用者openId
String openId = tenant.getOpenId();
//訂單支付成功推送資訊模板ID
String templateId = "這是你的模板ID";
//點選之後的跳轉頁面,為空安卓不跳轉、IOS空白頁面
String url = "";
//首行資訊-以下是一些推送資訊
String first = "公寓房間【"+addr.getName()+room.getName()+"】訂房成功";
//支付金額
String orderMoneySum = ""+indent.getMoney();
//商品資訊
String startTime = (rent.getStartTime()+"");
startTime = startTime.substring(0, startTime.length()-2);
String endTime = rent.getEndTime() + "";
endTime = endTime.substring(0, endTime.length()-2);
//在推送資訊中如果需要換行可以使用\\
n(雙斜槓n)來實現 String orderProductName = addr.getName()+room.getName()+"\\n大門密碼:" + doorLock.getLockPwd() + "#\\n" + "房門密碼:" + roomLock.getLockPwd() + "#\\n" + "密碼有效期:" + startTime + "至" + endTime + "\\n" + "還可以在這裡寫一些其他東西"; //將相關資訊 String wxText = "{\"touser\":\""+openId+"\",\"template_id\"
:\""+templateId+"\",\"url\":\""+url+"\",\"data\":{\"first\":{\"value\":\""+first+"\",\"color\":\"#000000\"},\"orderMoneySum\":{\"value\":\""+orderMoneySum+"\",\"color\":\"#000000\"},\"orderProductName\":{\"value\":\""+orderProductName+"\",\"color\":\"#000000\"}}}"; //獲取微信access_token String accessToken = WxUtils.getAccess_token(); //傳送post請求 String resultWx = AppTool.postJSON("https://api.weixin.qq.com/cgi-bin/message/template/send?access_token="+accessToken, wxText);

實現效果
這裡寫圖片描述