首先,獲取微信公衆號配置
1. 登錄微信公衆平臺,查看APPID,appsecret
2. 獲取到這倆關鍵值後,還是平臺頁面,往下滑找到開發配置 -》基本配置 -》IP白名單,點擊查看,添加上你服務器的IP地址,可以通過換行來添加多個,確定修改,需要管理員掃碼確認,OK,配置完成。
開始開發:
客服消息—發消息 點擊查看微信官方文檔
微信公衆平臺在線調試 點擊前往
1. 獲取微信的access_token,傳入APPID,appsecret(注意:請求ip必須在APPID對應的公衆號的ip白名單)
/**
* @Description: 獲取access_token
* @author: Hanweihu
* @date: 2019/7/12 11:14
* @param: [appid, appsecret]
* @return: java.lang.String
*/
public String getAccess_token(String appid, String appsecret) {
// 先判斷redis中是否存在
String token = redisTemplate.opsForValue().get(自定義key);
if (StringUtils.isBlank(token) == false) {
// token還未過期,獲取後直接返回,無需重新獲取
return token;
}
// token已過期或不存在,需重新獲取
redisTemplate.delete(自定義key);
String access_url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential" + "&appid=" + appid + "&secret=" + appsecret;
String message = "";
try {
URL url = new URL(access_url);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setDoOutput(true);
connection.setDoInput(true);
connection.connect();
//獲取返回的字符
InputStream inputStream = connection.getInputStream();
int size = inputStream.available();
byte[] bs = new byte[size];
inputStream.read(bs);
message = new String(bs, "UTF-8");
} catch (Exception e) {
e.printStackTrace();
}
//獲取access_token
JSONObject jsonObject = JSONObject.fromObject(message);
log.info("======獲取公衆號平臺的access_token:" + jsonObject.toString());
String accessToken = jsonObject.getString("access_token");
String expires_in = jsonObject.getString("expires_in");
// 防止代碼運行超時,提前1分鐘讓微信token失效
redisTemplate.opsForValue().set(自定義key, accessToken, Integer.valueOf(expires_in) - 60, TimeUnit.SECONDS);
return accessToken;
}
2. 成功獲取到access_token後,就可以根據文檔來發客服消息了
/**
* @Description: 微信--推送客服消息
* @author: Hanweihu
* @date: 2019/7/15 14:28
* @param: [unionid]
* @return: void
*/
@RequestMapping(value = "/pushWxAdmin", method = RequestMethod.POST)
@ApiOperation("微信--推送客服消息")
public void pushWxAdmin(String unionid) {
// unionid是用來查詢用戶下單信息的,查到信息後推送給管理員。
if (StringUtils.isBlank(unionid)) {
return;
}
// 調用上面的方法,獲取AccessToken,傳入APPID,appsecret
String wxAccessToken = getAccess_token(APPID, appsecret);
if (StringUtils.isBlank(wxAccessToken)) {
return;
}
// 查詢用戶下單信息
// ==省略查數據庫代碼,CustomerSignUp爲數據實體類,你們自定義
CustomerSignUp customerSignUp = customerSignUpList.get(0);
StringBuffer stringBuffer = new StringBuffer("");
stringBuffer.append("姓名:" + customerSignUp.getCustomerName() + "\n");
stringBuffer.append("電話:" + customerSignUp.getCustomerPhone() + "\n");
stringBuffer.append("身份證號:" + customerSignUp.getCustomerIdCard() + "\n");
stringBuffer.append("公司名稱:" + customerSignUp.getCustomerCompanyName() + "\n");
stringBuffer.append("助教姓名:" + customerSignUp.getHelpTeachName() + "\n");
stringBuffer.append("助教公司:" + customerSignUp.getHelpTeachCompanyName() + "\n");
stringBuffer.append("支付時間:" + sdf.format(customerSignUp.getCreateDate()) + "\n");
stringBuffer.append("支付狀態:" + (customerSignUp.getPayStatus() == 2 ? "已支付" : "未支付"));
// 獲取admin的openID
String admin_openid = "";
if (StringUtils.isBlank(admin_openid) == false) {
JSONObject jsonObject = new JSONObject();
jsonObject.put("content", stringBuffer.toString());
wxProPushMessage(admin_openid, wxAccessToken, jsonObject);
}
}
/**
* @Description: 只給管理員發送客戶報名成功消息
* @author: Hanweihu
* @date: 2019/7/12 11:25
* @param:
* @return: void
*/
public void wxProPushMessage(String touser, String accesstoken, String data) {
StringBuilder requestUrl = new StringBuilder("https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=");
requestUrl.append(accesstoken);
JSONObject json = new JSONObject();
json.put("touser", touser);// 設置openid
json.put("msgtype", "text");// 設置消息類型
json.put("text", data);// 設置模板消息內容
log.info("推送消息:" + json.toString());
Map<String, Object> map = null;
try {
HttpClient client = HttpClientBuilder.create().build();//構建一個Client
HttpPost post = new HttpPost(requestUrl.toString());//構建一個POST請求
StringEntity s = new StringEntity(json.toString(), "UTF-8");
s.setContentEncoding("UTF-8");
s.setContentType("application/json; charset=UTF-8");
post.setEntity(s);//設置編碼,不然模板內容會亂碼
HttpResponse response = client.execute(post);//提交POST請求
HttpEntity result = response.getEntity();//拿到返回的HttpResponse的"實體"
String content = EntityUtils.toString(result);
System.out.println(content);//打印返回的消息
JSONObject res = JSONObject.fromObject(content);//轉爲json格式
//把信息封裝到map
if (res != null && "ok".equals(res.get("errmsg"))) {
System.out.println("模版消息發送成功");
} else {
//封裝一個異常
StringBuilder sb = new StringBuilder("模版消息發送失敗\n");
sb.append(map.toString());
throw new Exception(sb.toString());
}
} catch (Exception e) {
e.printStackTrace();
}
}
關鍵地方提醒一下:
1. 請求ip必須在APPID對應的公衆號的ip白名單,不然導致獲取不到access_token
2. IP白名單可以通過換行來添加多個
3. 拼接內容時,換行用 “\n”
4. 最終發送的json串必須與文檔的key保持一致
{
"touser":"OPENID",
"msgtype":"text",
"text":
{
"content":"Hello World"
}
}