1. 程式人生 > 其它 >微信公眾號開發之傳送模板訊息

微信公眾號開發之傳送模板訊息

訂閱專欄
在我們做微信公眾號開發時,傳送模板訊息往往是必不可少的功能。今天我們就來說說吧!

1、申請模板訊息
首先我們應該知道,模板訊息是需要申請的。這個申請就其本身來說是很easy的(我前一天晚上申請的,顯示需要2--3個工作日,結果第二天早上就發現已經開通了,所以說騰訊官方還是比較給力的哈)。

但是我們在申請時還是有一些東西要注意,這個在官方的文件有非常詳細的說明。

這個我建議你好好看看。選擇行業的時候可要謹慎些,因為這個一個月只可以修改一次。

那麼,我們來看看在哪裡申請?

這裡我已經申請過了。

申請之後就耐心等待,稽核通過之後再功能這一欄裡就會出現模板訊息的選單。你可以看看我上面的截圖,就在第三項。

2、新增模板訊息
稽核通過之後,我們就可以新增模板訊息,進行開發了。

這個很簡單:

我們點選模板訊息進入後,直接在模板庫中選擇你需要的訊息模板新增就可以了,新增之後就會在我的模板中。會有一個模板id,這個模板id在我們傳送訊息的時候會用到。

3、訊息傳送功能開發
接下來我們就看看如何傳送模板訊息:

這個是官方文件:https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1433751277

我呢,也來說說我的實現吧。為了更方便,我會直接將相關程式碼貼出來。

文件中我們可以看到介面地址如下:

http請求方式: POST
https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=ACCESS_TOKEN
這裡我們首先需要的就是access_token了,這個在這裡就不多說了。通過你的appid和secret就可以獲取。

【獲取access_token : https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1421140183】

關於相關引數,我直接就將官方文件貼來了(文件寫的很清楚):

POST資料示例如下:

{
"touser":"OPENID",
"template_id":"ngqIpbwh8bUfcSsECmogfXcV14J0tQlEpBO27izEYtY",
"url":"http://weixin.qq.com/download",
"miniprogram":{
"appid":"xiaochengxuappid12345",
"pagepath":"index?foo=bar"
},
"data":{
"first": {
"value":"恭喜你購買成功!",
"color":"#173177"
},
"keyword1":{
"value":"巧克力",
"color":"#173177"
},
"keyword2": {
"value":"39.8元",
"color":"#173177"
},
"keyword3": {
"value":"2014年9月22日",
"color":"#173177"
},
"remark":{
"value":"歡迎再次購買!",
"color":"#173177"
}
}
}
引數說明

引數 是否必填 說明
touser 是 接收者openid
template_id 是 模板ID
url 否 模板跳轉連結(海外帳號沒有跳轉能力)
miniprogram 否 跳小程式所需資料,不需跳小程式可不用傳該資料
appid 是 所需跳轉到的小程式appid(該小程式appid必須與發模板訊息的公眾號是繫結關聯關係,暫不支援小遊戲)
pagepath 否 所需跳轉到小程式的具體頁面路徑,支援帶引數,(示例index?foo=bar),暫不支援小遊戲
data 是 模板資料
color 否 模板內容字型顏色,不填預設為黑色
注:url和miniprogram都是非必填欄位,若都不傳則模板無跳轉;若都傳,會優先跳轉至小程式。開發者可根據實際需要選擇其中一種跳轉方式即可。當用戶的微信客戶端版本不支援跳小程式時,將會跳轉至url。

返回碼說明

在呼叫模板訊息介面後,會返回JSON資料包。正常時的返回JSON資料包示例:

{
"errcode":0,
"errmsg":"ok",
"msgid":200228332
}
相信看完以上文件,基本上沒有什麼問題了。

以下是我的部分程式碼:

// 獲取token
String token = saveAndFlushAccessTokenUtil.getToken();

String postUrl = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=" + token;

JSONObject jsonObject = new JSONObject();
jsonObject.put("touser", "傳送到使用者的openid"); // openid
jsonObject.put("template_id", "你的模板id");
jsonObject.put("url", "http://www.baidu.com");

JSONObject data = new JSONObject();
JSONObject first = new JSONObject();
first.put("value", "hello");
first.put("color", "#173177");
JSONObject keyword1 = new JSONObject();
keyword1.put("value", "hello");
keyword1.put("color", "#173177");
JSONObject keyword2 = new JSONObject();
keyword2.put("value", "hello");
keyword2.put("color", "#173177");
JSONObject keyword3 = new JSONObject();
keyword3.put("value", "hello");
keyword3.put("color", "#173177");
JSONObject remark = new JSONObject();
remark.put("value", "hello");
remark.put("color", "#173177");

data.put("first",first);
data.put("keyword1",keyword1);
data.put("keyword2",keyword2);
data.put("keyword3",keyword3);
data.put("remark",remark);

jsonObject.put("data", data);

String string = HttpClientUtils.sendPostJsonStr(postUrl, jsonObject.toJSONString());
JSONObject result = JSON.parseObject(string);
int errcode = result.getIntValue("errcode");
if(errcode == 0){
// 傳送成功
System.out.println("傳送成功");
} else {
// 傳送失敗
System.out.println("傳送失敗");
}
下面是http請求工具類:

package car.repair.common.util;

import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpEntity;
import org.apache.http.ParseException;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import java.io.IOException;

/**
* @author zhuzhe
* @date 2017/12/11
* HttpClient工具類
*/
@Slf4j
public class HttpClientUtils {

/**
* 以jsonString形式傳送HttpPost的Json請求,String形式返回響應結果
*
* @param url
* @param jsonString
* @return
*/
public static String sendPostJsonStr(String url, String jsonString) throws IOException {
if (jsonString == null || jsonString.isEmpty()) {
return sendPost(url);
}
String resp = "";
StringEntity entityStr = new StringEntity(jsonString,
ContentType.create("text/plain", "UTF-8"));
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(entityStr);
CloseableHttpResponse response = null;
try {
response = httpClient.execute(httpPost);
HttpEntity entity = response.getEntity();
resp = EntityUtils.toString(entity, "UTF-8");
EntityUtils.consume(entity);
} catch (ClientProtocolException e) {
log.error(e.getMessage());
} catch (IOException e) {
log.error(e.getMessage());
} finally {
if (response != null) {
try {
response.close();
} catch (IOException e) {
log.error(e.getMessage());
}
}
}
if (resp == null || resp.equals("")) {
return "";
}
return resp;
}

/**
* 傳送不帶引數的HttpPost請求
*
* @param url
* @return
*/
public static String sendPost(String url) throws IOException {
// 1.獲得一個httpclient物件
CloseableHttpClient httpclient = HttpClients.createDefault();
// 2.生成一個post請求
HttpPost httppost = new HttpPost(url);
CloseableHttpResponse response = null;
try {
// 3.執行get請求並返回結果
response = httpclient.execute(httppost);
} catch (IOException e) {
log.error(e.getMessage());
}
// 4.處理結果,這裡將結果返回為字串
HttpEntity entity = response.getEntity();
String result = null;
try {
result = EntityUtils.toString(entity);
} catch (ParseException | IOException e) {
log.error(e.getMessage());
}
return result;
}
}

收到訊息,我就不自己弄圖了。這裡附上官方圖片一張: