(感謝好多老哥提供的文檔,哈哈,這裏我就只是代碼貼出來,方便以後copy)
1獲取token
String token = Wechat.getAccess_token(appId, appSecret).getString("access_token");
public static JSONObject getAccess_token(String appId, String appSecret) {
String url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + appId + "&secret=" + appSecret;
String accessToken = null;
JSONObject jsonObj = null;
try {
URL urlGet = new URL(url);
HttpURLConnection http = (HttpURLConnection) urlGet.openConnection();
http.setRequestMethod("GET"); // 必須是get方式請求
http.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
http.setDoOutput(true);
http.setDoInput(true);
http.connect();
InputStream is = http.getInputStream();
int size = is.available();
byte[] jsonBytes = new byte[size];
is.read(jsonBytes);
accessToken = new String(jsonBytes, "UTF-8");
System.err.println(accessToken);
jsonObj = JSONObject.parseObject(accessToken);
is.close();
} catch (Exception e) {
e.printStackTrace();
}
return jsonObj;
}
2調用service層發消息模板
TemplateMessageService.sendTemp(appId, token, appSecret, entity.realAmount, tenantEntity.name, memberEntity.wechatOpenId);
3進入該模板後會調用httputil類,發送消息
package com.mall.common.services;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.mall.common.utils.HttpSend;
import com.mall.common.utils.HttpUtil;
import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
public class TemplateMessageService {
public static void sendTemp(String appid, String accessToken, String appSecret, Double realAmount, String shopName, String openId) {
String url = "https://api.weixin.qq.com/cgi-bin/token";
String param = "grant_type=client_credential" + "&appid=" + appid + "&secret=" + appSecret;
String accTemp = HttpSend.sendGet(url, param);
JSONObject jsonObject = JSONObject.parseObject(accTemp);
System.out.println("1--->" + jsonObject);
accessToken = jsonObject.getString("access_token"); // 獲取到了access_token,調用接口都要用到的,有時效
// 封裝要發送的json
Map<String, Object> map = new HashMap();
map.put("touser", openId);//你要發送給某個用戶的openid 前提是已關注該公衆號,該openid是對應該公衆號的,不是普通的openid
map.put("template_id", "VkxwzizOa2YS_M2RQbVQHPHzHTbabAqLvqU5FNFqQVs");//模板消息id
//map.put("url","https://www.vipkes.cn");//用戶點擊模板消息,要跳轉的地址
// 封裝miniprogram 跳轉小程序用,不跳不要填
Map<String, String> mapA = new HashMap<>();
mapA.put("appid", ""); //小程序appid
mapA.put("pagepath", ""); //小程序頁面pagepath
map.put("miniprogram", mapA);
// 以下就是根據模板消息的格式封裝好,我模板的是:問題反饋結果通知 可以和我一樣試試
// 封裝first
Map firstMap = new HashMap();
firstMap.put("value", "新的消費通知!"); //內容
firstMap.put("color", "#173177"); //字體顏色
// 封裝keyword1 提交的問題
Map keyword1Map = new HashMap();
keyword1Map.put("value", shopName);
keyword1Map.put("color", "#fff");
// 封裝keyword2此處也可以是商品名
Map keyword2Map = new HashMap();
keyword2Map.put("value", "-");
keyword2Map.put("color", "#fff");
// 封裝keyword2此處可以是商品價格
Map keyword3Map = new HashMap();
keyword3Map.put("value", realAmount + "元");
keyword3Map.put("color", "#fff");
// 封裝keyword4
// 封裝remark
Date date = new Date();
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Map keyword4Map = new HashMap();
keyword4Map.put("value", simpleDateFormat.format(date));
keyword4Map.put("color", "#fff");
Map remarkMap = new HashMap();
remarkMap.put("value", "尊敬的用戶,您於" + simpleDateFormat.format(date) + "在" + shopName + "消費了" + realAmount + "元");
remarkMap.put("color", "#fff");
// 封裝data
Map dataMap = new HashMap();
dataMap.put("first", firstMap);
dataMap.put("keyword1", keyword1Map);
dataMap.put("keyword2", keyword2Map);
dataMap.put("keyword3", keyword3Map);
dataMap.put("keyword4", keyword4Map);
dataMap.put("remark", remarkMap);
map.put("data", dataMap);
String r = HttpUtil.getJsonData(JSONObject.parseObject(JSON.toJSONString(map)), "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=" + accessToken); //發送模板消息,這裏有個工具類,我給你喲
System.out.println("-->" + r);
}
public static void sendTempPoint(String appid, String accessToken, String appSecret, Integer Id, String name, String mobile, Double amount, String wechatOpenId) {
String url = "https://api.weixin.qq.com/cgi-bin/token";
String param = "grant_type=client_credential" + "&appid=" + appid + "&secret=" + appSecret;
String accTemp = HttpSend.sendGet(url, param);
JSONObject jsonObject = JSONObject.parseObject(accTemp);
System.out.println("1--->" + jsonObject);
accessToken = jsonObject.getString("access_token"); // 獲取到了access_token,調用接口都要用到的,有時效
// 封裝要發送的json
Map<String, Object> map = new HashMap();
map.put("touser", wechatOpenId);//你要發送給某個用戶的openid 前提是已關注該公衆號,該openid是對應該公衆號的,不是普通的openid
map.put("template_id", "672dPs0Jwl9zLvhVrncI0nyEHxX3Mx-fPNLBcIEb05A");//模板消息id
//map.put("url","https://www.vipkes.cn");//用戶點擊模板消息,要跳轉的地址
// 封裝miniprogram 跳轉小程序用,不跳不要填
Map<String, String> mapA = new HashMap<>();
mapA.put("appid", ""); //小程序appid
mapA.put("pagepath", ""); //小程序頁面pagepath
map.put("miniprogram", mapA);
// 以下就是根據模板消息的格式封裝好,我模板的是:問題反饋結果通知 可以和我一樣試試
// 封裝first
Map firstMap = new HashMap();
firstMap.put("value", "會員積分消費提醒!"); //內容
firstMap.put("color", "#173177"); //字體顏色
String newname;
try {
newname = (java.net.URLDecoder.decode(name, "UTF-8"));
} catch (UnsupportedEncodingException e) {
newname = name;
}
// 封裝keyword1 提交的問題
Map XM = new HashMap();
XM.put("value", newname);
XM.put("color", "#fff");
// 封裝keyword2此處也可以是商品名
Map KH = new HashMap();
KH.put("value", Id);
KH.put("color", "#fff");
Date date = new Date();
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
// 封裝keyword3此處可以是商品價格
Map CONTENTS = new HashMap();
CONTENTS.put("value", "尊敬的用戶,您的賬戶於" + simpleDateFormat.format(date) + "增加了" + amount + "積分");
CONTENTS.put("color", "#fff");
Map remarkMap = new HashMap();
remarkMap.put("value", "消息惠顧");
remarkMap.put("color", "#fff");
// 封裝data
Map dataMap = new HashMap();
dataMap.put("first", firstMap);
dataMap.put("XM", XM);
dataMap.put("KH", KH);
dataMap.put("CONTENTS", CONTENTS);
dataMap.put("remark", remarkMap);
map.put("data", dataMap);
String r = HttpUtil.getJsonData(JSONObject.parseObject(JSON.toJSONString(map)), "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=" + accessToken); //發送模板消息,這裏有個工具類,我給你喲
System.out.println("-->" + r);
}
}
4發送消息
package com.mall.common.utils;
import com.alibaba.fastjson.JSONObject;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
public class HttpUtil {
public static String getJsonData(JSONObject jsonParam, String urls) {
StringBuffer sb = new StringBuffer();
try {
// 創建url資源
URL url = new URL(urls);
// 建立http連接
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
// 設置允許輸出
conn.setDoOutput(true);
// 設置允許輸入
conn.setDoInput(true);
// 設置不用緩存
conn.setUseCaches(false);
// 設置傳遞方式
conn.setRequestMethod("POST");
// 設置維持長連接
conn.setRequestProperty("Connection", "Keep-Alive");
// 設置文件字符集:
conn.setRequestProperty("Charset", "UTF-8");
// 轉換爲字節數組
byte[] data = (jsonParam.toString()).getBytes();
// 設置文件長度
conn.setRequestProperty("Content-Length", String.valueOf(data.length));
// 設置文件類型:
conn.setRequestProperty("contentType", "application/json");
// 開始連接請求
conn.connect();
//OutputStream out = new DataOutputStream(conn.getOutputStream()) ;
//防止消息亂碼
OutputStreamWriter out = new OutputStreamWriter(conn.getOutputStream(), "utf-8");
// 寫入請求的字符串
out.write(jsonParam.toString());
out.flush();
out.close();
System.out.println(conn.getResponseCode());
// 請求返回的狀態
if (HttpURLConnection.HTTP_OK == conn.getResponseCode()) {
System.out.println("連接成功");
// 請求返回的數據
InputStream in1 = conn.getInputStream();
try {
String readLine = new String();
BufferedReader responseReader = new BufferedReader(new InputStreamReader(in1, "UTF-8"));
while ((readLine = responseReader.readLine()) != null) {
sb.append(readLine).append("\n");
}
responseReader.close();
System.out.println(sb.toString());
} catch (Exception e1) {
e1.printStackTrace();
}
} else {
System.out.println("error++");
}
} catch (Exception e) {
}
return sb.toString();
}
/**
* @auther: cxl
* @Description 發送post請求 參數String
* @date: 2019/4/28 19:38
*/
public static String post(String jsonParam, String urls) {
StringBuffer sb = new StringBuffer();
try {
// 創建url資源
URL url = new URL(urls);
// 建立http連接
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
// 設置允許輸出
conn.setDoOutput(true);
// 設置允許輸入
conn.setDoInput(true);
// 設置不用緩存
conn.setUseCaches(false);
// 設置傳遞方式
conn.setRequestMethod("POST");
// 設置維持長連接
conn.setRequestProperty("Connection", "Keep-Alive");
// 設置文件字符集:
conn.setRequestProperty("Charset", "UTF-8");
// 轉換爲字節數組
//byte[] data = (jsonParam.toString()).getBytes();
// 設置文件長度
// conn.setRequestProperty("Content-Length", String.valueOf(data.length));
// 設置文件類型:
conn.setRequestProperty("contentType", "application/text");
// 開始連接請求
conn.connect();
//防止消息亂碼
OutputStreamWriter out = new OutputStreamWriter(conn.getOutputStream(), "utf-8");
// 寫入請求的字符串
out.write(jsonParam.toString());
out.flush();
out.close();
System.out.println(conn.getResponseCode());
// 請求返回的狀態
if (HttpURLConnection.HTTP_OK == conn.getResponseCode()) {
System.out.println("連接成功");
// 請求返回的數據
InputStream in1 = conn.getInputStream();
try {
String readLine = new String();
BufferedReader responseReader = new BufferedReader(new InputStreamReader(in1, "UTF-8"));
while ((readLine = responseReader.readLine()) != null) {
sb.append(readLine).append("\n");
}
responseReader.close();
System.out.println(sb.toString());
} catch (Exception e1) {
e1.printStackTrace();
}
} else {
System.out.println("error++");
}
} catch (Exception e) {
e.printStackTrace();
}
return sb.toString();
}
}
5以下問題是之後出的問題
此處如果不寫utf-8本地postman測試不一定會亂碼 ,上傳線上有機率亂碼,我遇到了,被罵死,哈哈,其他的真沒什麼問題,openid是他們提供的,我不太清楚,然後千萬別亂給微信公衆號,他們給錯公衆號害得我一直顯示未關注公衆號,擦,說了他們不信