在微信開發中遇到要向用戶主動發送微信消息的需求,查閱開發文檔並未提供相關接口。搜索也並未發現相關解決辦法,靈感突發使用消息預覽接口實現了該需求!上圖:
// 消息預覽URL
private static String message_preview_url = "https://api.weixin.qq.com/cgi-bin/message/mass/preview?access_token=ACCESS_TOKEN";
/**
* 圖文消息預覽
*
* @param touser
* 接收人openid
* @param wxArticles
* 圖文集合
* @throws WexinReqException
*/
public static void messagePrivate(String accesstoken, String touser, List<WxArticle> wxArticles) throws WexinReqException {
if (accesstoken != null) {
String requestUrl = message_preview_url.replace("ACCESS_TOKEN", accesstoken);
try {
String mediaId = getMediaId(accesstoken, wxArticles);
JSONObject obj = new JSONObject();
JSONObject mpnews = new JSONObject();
obj.put("touser", touser);
obj.put("msgtype", "mpnews");
mpnews.put("media_id", mediaId);
obj.put("mpnews", mpnews);
JSONObject result = WxstoreUtils.httpRequest(requestUrl, "POST", obj.toString());
//System.out.println("微信返回的結果:" + result.toString());
} catch (Exception e) {
throw new WexinReqException(e);
}
} else {
throw new WexinReqException("accesstoken 為空,請檢查!");
}
}