一、微信公众号获取token
/*微信提供获取access_token接口地址*/
private static final String access_token_url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential";
/*第三方用户唯一凭证*/
private static final String APPID = "wx644f********";
/*第三方用户唯一凭证密钥,即appsecret*/
private static final String SECRET = "342f9a33a**********";
public String getToken() {
String tokenGetUrl = access_token_url;//微信提供获取access_token接口地址
String appid = APPID;
String secret = SECRET;
JSONObject tokenJson = new JSONObject();
if (StringUtils.isNotBlank(appid) && StringUtils.isNotBlank(secret)) {
tokenGetUrl += "&appid=" + appid + "&secret=" + secret;
tokenJson = new WeixinUtil().getUrlResponse(tokenGetUrl);
try {
return (String) tokenJson.get("access_token");
} catch (JSONException e) {
return null;
}
} else {
return null;
}
}
二、获取微信公众号关注用户
官方接口文档:https://developers.weixin.qq.com/doc/offiaccount/User_Management/Getting_a_User_List.html
/*获取微信公众号关注用户接口地址*/
private static final String get_userInfo_url = "https://api.weixin.qq.com/cgi-bin/user/get";
//传入获取的access_token获取微信关注用户列表
public Set<String> getUsers(String access_token) {
String usersGetUrl = get_userInfo_url;
usersGetUrl += "?access_token=" + access_token;
org.json.JSONObject data = new WeixinUtil().getUrlResponse(usersGetUrl);
System.out.println("~~~~~用户信息:" + data.toString());
Set<String> openIds = new HashSet<String>();
Integer total = 0, count = 0;
try {
total = (Integer) data.get("total");
count = (Integer) data.get("count");
//总关注用户数超过默认一万
if (count < total) {
openIds.addAll(getUsers(openIds, usersGetUrl, access_token, (String) data.get("next_openid")));
} else {
//有关注者 json才有data参数
if (count > 0) {
org.json.JSONObject openIdData = (org.json.JSONObject) data.get("data");
JSONArray openIdArray = (JSONArray) openIdData.get("openid");
for (int i = 0; i < openIdArray.length(); i++) {
openIds.add((String) openIdArray.get(i));
}
}
}
} catch (JSONException e) {
e.printStackTrace();
}
return openIds;
}
获取微信关注用户具体信息包括openid和unionid
/**
* 获取用户信息
* @param access_token 微信公众号token
* @param useropenid 用户openid
* @return
*/
public Record finduserInfo(String access_token, String useropenid) {
String usersfindUrl = find_userInfo_url;
usersfindUrl += "?access_token=" + access_token + "&openid=" + useropenid;
JSONObject data = new WeixinUtil().getUrlResponse(usersfindUrl);
System.out.println("用户信息====" + data);
return data;
}
WeixinUtil()类
package com.ddm.system.qywx;
import io.swagger.annotations.Api;
import org.apache.commons.lang.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.HttpResponseException;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.json.JSONObject;
import org.springframework.context.annotation.Scope;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import java.io.IOException;
import java.net.URI;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
@RestController
@RequestMapping(value = "/WeixinUtil")
@Api(value = "WeixinUtil.*")
@Scope("prototype")//多例模式
public class WeixinUtil {
public JSONObject getUrlResponse(String url) {
CharsetHandler handler = new CharsetHandler("UTF-8");
try {
HttpGet httpget = new HttpGet(new URI(url));
HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
//HttpClient
CloseableHttpClient client = httpClientBuilder.build();
client = (CloseableHttpClient) wrapClient(client);
return new JSONObject(client.execute(httpget, handler));
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
public static HttpClient wrapClient(HttpClient base) {
try {
SSLContext ctx = SSLContext.getInstance("TLSv1");
X509TrustManager tm = new X509TrustManager() {
public void checkClientTrusted(X509Certificate[] xcs,
String string) throws CertificateException {
}
public void checkServerTrusted(X509Certificate[] xcs,
String string) throws CertificateException {
}
public X509Certificate[] getAcceptedIssuers() {
return null;
}
};
ctx.init(null, new TrustManager[]{tm}, null);
SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(ctx, new String[]{"TLSv1"}, null,
SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);
CloseableHttpClient httpclient = HttpClients.custom().setSSLSocketFactory(sslsf).build();
return httpclient;
} catch (Exception ex) {
return null;
}
}
public class CharsetHandler implements ResponseHandler<String> {
private String charset;
public CharsetHandler(String charset) {
this.charset = charset;
}
public String handleResponse(HttpResponse response)
throws ClientProtocolException, IOException {
StatusLine statusLine = response.getStatusLine();
if (statusLine.getStatusCode() >= 300) {
throw new HttpResponseException(statusLine.getStatusCode(),
statusLine.getReasonPhrase());
}
HttpEntity entity = response.getEntity();
if (entity != null) {
if (!StringUtils.isBlank(charset)) {
return EntityUtils.toString(entity, charset);
} else {
return EntityUtils.toString(entity);
}
} else {
return null;
}
}
}
}
三、消息推送
/**
* 客户订单信息推送给用户
* @param unionid 用户unionid
* @return
*/
@PostMapping("/OrderTempMsg")
public boolean OrderTempMsg(Object unionid) {
String openId = "o1NS86Qshm94aftSCew******"; //用户openid
String templateId = "WCOPQyRW_9QolNU********";//消息模板id
Record json = new Record();
json.set("first", new Record().set("value","您已成功下达订单,商家将在5分钟内受理订单"));
json.set("keyword1", new Record().set("value","20160822161230")); //订单编号
json.set("keyword2", new Record().set("value","2023/04/04 15:30:25")); //下单时间
json.set("remark", new Record().set("value","如有疑问,请联系点送客服 5008654228......"));
return sendTempMsg(openId, templateId, json);
}
//针对用户openid发送消息推送
public boolean sendTempMsg(String openId, String template_id, Record data) {
Record json = new Record();
Record json1 = new Record();
json1.set("appid","123******");
json1.set("pagepath","pages/login/login");//消息模板跳转微信小程序(需要小程序与公众号进行关联)
json.set("touser", openId);
json.set("template_id", template_id);
json.set("url", "http://weixin.qq.com/download");
json.set("miniprogram", json1);
json.set("data", data);
String url = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=" + getAccessToken();
String jsonStr = HtmlTools.postJSON(url, json.toJson());
JSONObject jsonObject = JsonTools.strToJson(jsonStr);
if (jsonObject.get("errcode") != null && jsonObject.getInteger("errcode") == 0) {
return true;
} else {
logger.info("weixin sendTempMsg 错误:" + jsonObject);
return false;
}
}