1--依赖
org.apache.httpcomponents httpclient4.5 com.github.binarywang weixin-java-mp4.1.0 com.github.binarywang weixin-java-common4.1.0
2--使用方法
//获取二维码图片(微信二维码似乎只能携带一个参数)
private ResultJson getQrCode() {
// 获取token开发者
String getQrCodeUrl = "https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token=" + WeChatUtils.getAccessToken();
// 生成前端唯一标识UUID
String UUID = ResultUtil.getUUID();
String json = "{"expire_seconds": 604800, "action_name": "QR_STR_SCENE"" + ", "action_info": {"scene": {"scene_str": "" + UUID + ""}}}";
String result = WeChatUtils.doPostJson(getQrCodeUrl, json);
//返回给前端
try {
JSonObject jsonObject = JSONObject.parseObject(result);
jsonObject.put("UUID", UUID);
return ResultJson.ok(jsonObject);
} catch (Exception e) {
e.printStackTrace();
return ResultJson.error(e.getMessage());
}
}
@RequestMapping("/checkSign")
public String checkSign(HttpServletRequest request) throws Exception {
//获取微信请求参数
String signature = request.getParameter("signature");
String timestamp = request.getParameter("timestamp");
String nonce = request.getParameter("nonce");
String echostr = request.getParameter("echostr");
//参数排序。 token 就要换成自己实际写的 token
String[] params = new String[]{timestamp, nonce, "123456"};
Arrays.sort(params);
//拼接
String paramstr = params[0] + params[1] + params[2];
//加密
//获取 shal 算法封装类
MessageDigest Sha1Dtgest = MessageDigest.getInstance("SHA-1");
//进行加密
byte[] digestResult = Sha1Dtgest.digest(paramstr.getBytes("UTF-8"));
//拿到加密结果
String mysignature = StringUtil.bytes2HexString(digestResult);
mysignature = mysignature.toLowerCase(Locale.ROOT);
//是否正确
boolean signsuccess = mysignature.equals(signature);
//逻辑处理
if (signsuccess && echostr != null) {
//peizhi token
return echostr;//不正确就直接返回失败提示.
} else {
//重点
JSonObject jsonObject = loginService.callback(request);
return jsonObject.toJSonString();
}
}
//上面的方法调用这个方法
public JSonObject callback(HttpServletRequest request) throws IOException {
//request中有相应的信息,进行解析
WxMpXmlMessage message = WxMpXmlMessage.fromXml(request.getInputStream());//获取消息流,并解析xml
//消息类型
String messageType = message.getMsgType();
//消息事件
String messageEvent = message.getEvent();
//openid
String openId = message.getFromUser();
//UUID
String UUID = message.getEventKey();
JSonObject jsonObject = new JSonObject();
jsonObject.put("code", "200");
//if判断,判断查询
if (messageType.equals("event")) {
jsonObject = null;
//扫描二维码
if (messageEvent.equals("SCAN")) {
}
//关注
if (messageEvent.equals("subscribe")) {
}
//没有该用户
if (jsonObject == null) {
//从微信上中拉取用户信息
String url = "https://api.weixin.qq.com/cgi-bin/user/info?access_token=" + getAccessToken() +
"&openid=" + fromUser +
"&lang=zh_CN";
String result = doGet(url);
jsonObject = JSONObject.parseObject(result);
}
return jsonObject;
}
3--工具类
public class WeChatUtils {
private static final String APP_ID = "";
private static final String APP_SECRET = "";
public static String getAccessToken() {
String accessToken;
String getTokenUrl = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + APP_ID + "&secret=" + APP_SECRET;
String result = doGet(getTokenUrl);
JSonObject jsonObject = JSONObject.parseObject(result);
accessToken = jsonObject.getString("access_token");
return accessToken;
}
public static String doGet(String url, Map param) {
// 创建Httpclient对象
CloseableHttpClient httpclient = HttpClients.createDefault();
String resultString = "";
CloseableHttpResponse response = null;
try {
// 创建uri
URIBuilder builder = new URIBuilder(url);
if (param != null) {
for (String key : param.keySet()) {
builder.addParameter(key, param.get(key));
}
}
URI uri = builder.build();
// 创建http GET请求
HttpGet httpGet = new HttpGet(uri);
// 执行请求
response = httpclient.execute(httpGet);
// 判断返回状态是否为200
if (response.getStatusLine().getStatusCode() == 200) {
resultString = EntityUtils.toString(response.getEntity(), "UTF-8");
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (response != null) {
response.close();
}
httpclient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return resultString;
}
public static String doGet(String url) {
return doGet(url, null);
}
public static String doPost(String url, Map param) {
// 创建Httpclient对象
CloseableHttpClient httpClient = HttpClients.createDefault();
CloseableHttpResponse response = null;
String resultString = "";
try {
// 创建Http Post请求
HttpPost httpPost = new HttpPost(url);
// 创建参数列表
if (param != null) {
List paramList = new ArrayList<>();
for (String key : param.keySet()) {
paramList.add(new BasicNamevaluePair(key, param.get(key)));
}
// 模拟表单
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(paramList, "utf-8");
httpPost.setEntity(entity);
}
// 执行http请求
response = httpClient.execute(httpPost);
resultString = EntityUtils.toString(response.getEntity(), "utf-8");
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
response.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return resultString;
}
public static String doPost(String url) {
return doPost(url, null);
}
public static String doPostJson(String url, String json) {
// 创建Httpclient对象
CloseableHttpClient httpClient = HttpClients.createDefault();
CloseableHttpResponse response = null;
String resultString = "";
try {
// 创建Http Post请求
HttpPost httpPost = new HttpPost(url);
// 创建请求内容
StringEntity entity = new StringEntity(json, ContentType.APPLICATION_JSON);
httpPost.setEntity(entity);
// 执行http请求
response = httpClient.execute(httpPost);
resultString = EntityUtils.toString(response.getEntity(), "utf-8");
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
response.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return resultString;
}
}



