1 直接上代码
实体类
public class WxLoginModel {
@ApiModelProperty(value = "微信授权code码")
private String code;
@ApiModelProperty(value = "微信头像")
private String avatar;
@ApiModelProperty(value = "微信昵称")
private String nickname;
@ApiModelProperty(value = "推荐用户ID")
private String recommenderId;
@ApiModelProperty(value = "sex")
private Integer sex;
}
控制器
@PostMapping("/wxLogin")
public AjaxResult wxLogin(WxLoginModel loginModel) {
String s = getUserWXLoginInfo(loginModel.getCode());
logger.info("---------小程序授权返回结果:{}", s);
if (com.alibaba.druid.util.StringUtils.isEmpty(s)) {
return AjaxResult.error("请求微信授权失败");
}
JSONObject obj = JSONObject.parseObject(s);
String openid = obj.getString("openid");
String unionId = obj.getString("unionId");
if (com.alibaba.druid.util.StringUtils.isEmpty(openid)) {
return AjaxResult.error("请求微信授权失败,获取不到OPENID");
}
AppUserWx member = appUserWxService.getByOpenId(openid);
AppUser appUser = null;
if (ObjectUtils.isEmpty(member)) {
。。。。。。。。。。。。。。。。。。。。
}else {
。。。。。。。。。。。。。。。。。。。。
}
return AjaxResult.success();
}
private String getUserWXLoginInfo(String wxCode) {
String requestUrl = "https://api.weixin.qq.com/sns/jscode2session";
Map<String, String> requestUrlParam = new HashMap<String, String>();
requestUrlParam.put("appid", "1234456");
requestUrlParam.put("secret", "122435454");
requestUrlParam.put("js_code", wxCode);
requestUrlParam.put("grant_type", "authorization_code");
String s = HttpUtils.sendPost(requestUrl, JSONObject.toJSONString(requestUrlParam));
return s;
}
private String getUserWXLoginInfo(String wxCode) {
String requestUrl = "https://api.weixin.qq.com/sns/jscode2session?";
StringBuilder sb = new StringBuilder();
sb.append("appid=").append("1234456");
sb.append("&secret=").append("122435454");
sb.append("&js_code=").append(wxCode);
sb.append("&grant_type=").append("authorization_code");
String s = HttpUtils.sendPost(requestUrl+sb.toString, "");
return s;
}
@GetMapping("/getPhone")
public AjaxResult getWXPhone(String encryptedData, String iv, String openId) {
if (com.alibaba.druid.util.StringUtils.isEmpty(encryptedData) || com.alibaba.druid.util.StringUtils.isEmpty(iv) || com.alibaba.druid.util.StringUtils.isEmpty(openId)) {
return AjaxResult.error("参数不完整");
}
String session_key = (String) redisService.get(openId);
String decrypt = decrypt(encryptedData, session_key, iv);
logger.info("-----------手机号授权解析结果:{}", decrypt);
if (com.alibaba.druid.util.StringUtils.isEmpty(decrypt)) {
return AjaxResult.error("数据解析失败");
}
JSONObject jsonObject = JSONObject.parseObject(decrypt);
String phoneNumber = jsonObject.getString("phoneNumber");
AppUser appUser = appUserService.selectAppUserByPhonenumber(phoneNumber);
AppUserWx byOpenId = appUserWxService.getByOpenId(openId);
if (appUser == null) {
............................
}
return AjaxResult.success();
}
private static String decrypt(String encryptedData, String sessionKey, String iv) {
String result = "";
try {
byte[] resultByte = AESUtil.decrypt(java.util.Base64.getDecoder().decode(encryptedData),
java.util.Base64.getDecoder().decode(sessionKey),
java.util.Base64.getDecoder().decode(iv));
if (null != resultByte && resultByte.length > 0) {
result = new String(resultByte, "UTF-8");
}
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
工具类
public class HttpUtils {
private static final Logger log = LoggerFactory.getLogger(HttpUtils.class);
public static String sendGet(String url, String param) {
return sendGet(url, param, Constants.UTF8);
}
public static String sendGet(String url, String param, String contentType) {
StringBuilder result = new StringBuilder();
BufferedReader in = null;
try {
String urlNameString = url + "?" + param;
log.info("sendGet - {}", urlNameString);
URL realUrl = new URL(urlNameString);
URLConnection connection = realUrl.openConnection();
connection.setRequestProperty("accept", "*/*");
connection.setRequestProperty("connection", "Keep-Alive");
connection.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
connection.connect();
in = new BufferedReader(new InputStreamReader(connection.getInputStream(), contentType));
String line;
while ((line = in.readLine()) != null) {
result.append(line);
}
log.info("recv - {}", result);
} catch (ConnectException e) {
log.error("调用HttpUtils.sendGet ConnectException, url=" + url + ",param=" + param, e);
} catch (SocketTimeoutException e) {
log.error("调用HttpUtils.sendGet SocketTimeoutException, url=" + url + ",param=" + param, e);
} catch (IOException e) {
log.error("调用HttpUtils.sendGet IOException, url=" + url + ",param=" + param, e);
} catch (Exception e) {
log.error("调用HttpsUtil.sendGet Exception, url=" + url + ",param=" + param, e);
} finally {
try {
if (in != null) {
in.close();
}
} catch (Exception ex) {
log.error("调用in.close Exception, url=" + url + ",param=" + param, ex);
}
}
return result.toString();
}
public static String sendGet(String url) {
StringBuilder result = new StringBuilder();
BufferedReader in = null;
try {
String urlNameString = url;
log.info("sendGet - {}", urlNameString);
URL realUrl = new URL(urlNameString);
URLConnection connection = realUrl.openConnection();
connection.setRequestProperty("accept", "*/*");
connection.setRequestProperty("connection", "Keep-Alive");
connection.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
connection.connect();
in = new BufferedReader(new InputStreamReader(connection.getInputStream(), Constants.UTF8));
String line;
while ((line = in.readLine()) != null) {
result.append(line);
}
log.info("recv - {}", result);
} catch (ConnectException e) {
log.error("调用HttpUtils.sendGet ConnectException, url=" + url, e);
} catch (SocketTimeoutException e) {
log.error("调用HttpUtils.sendGet SocketTimeoutException, url=" + url, e);
} catch (IOException e) {
log.error("调用HttpUtils.sendGet IOException, url=" + url, e);
} catch (Exception e) {
log.error("调用HttpsUtil.sendGet Exception, url=" + url, e);
} finally {
try {
if (in != null) {
in.close();
}
} catch (Exception ex) {
log.error("调用in.close Exception, url=" + url, ex);
}
}
return result.toString();
}
public static String sendPost(String url, String param) {
PrintWriter out = null;
BufferedReader in = null;
StringBuilder result = new StringBuilder();
try {
String urlNameString = url;
log.info("sendPost - {}", urlNameString);
URL realUrl = new URL(urlNameString);
URLConnection conn = realUrl.openConnection();
conn.setRequestProperty("accept", "*/*");
conn.setRequestProperty("connection", "Keep-Alive");
conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
conn.setRequestProperty("Accept-Charset", "utf-8");
conn.setRequestProperty("contentType", "utf-8");
conn.setDoOutput(true);
conn.setDoInput(true);
out = new PrintWriter(conn.getOutputStream());
out.print(param);
out.flush();
in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "utf-8"));
String line;
while ((line = in.readLine()) != null) {
result.append(line);
}
log.info("recv - {}", result);
} catch (ConnectException e) {
log.error("调用HttpUtils.sendPost ConnectException, url=" + url + ",param=" + param, e);
} catch (SocketTimeoutException e) {
log.error("调用HttpUtils.sendPost SocketTimeoutException, url=" + url + ",param=" + param, e);
} catch (IOException e) {
log.error("调用HttpUtils.sendPost IOException, url=" + url + ",param=" + param, e);
} catch (Exception e) {
log.error("调用HttpsUtil.sendPost Exception, url=" + url + ",param=" + param, e);
} finally {
try {
if (out != null) {
out.close();
}
if (in != null) {
in.close();
}
} catch (IOException ex) {
log.error("调用in.close Exception, url=" + url + ",param=" + param, ex);
}
}
return result.toString();
}
public static String sendSSLPost(String url, String param, String token) {
StringBuilder result = new StringBuilder();
String urlNameString = url + "?" + param;
try {
log.info("sendSSLPost - {}", urlNameString);
SSLContext sc = SSLContext.getInstance("SSL");
sc.init(null, new TrustManager[]{
new TrustAnyTrustManager()}, new java.security.SecureRandom());
URL console = new URL(urlNameString);
HttpsURLConnection conn = (HttpsURLConnection) console.openConnection();
conn.setRequestProperty("accept", "*/*");
conn.setRequestProperty("connection", "Keep-Alive");
conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
conn.setRequestProperty("Accept-Charset", "utf-8");
conn.setRequestProperty("contentType", "utf-8");
if (!StringUtils.isEmpty(token)) {
conn.setRequestProperty("token", token);
}
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setSSLSocketFactory(sc.getSocketFactory());
conn.setHostnameVerifier(new TrustAnyHostnameVerifier());
conn.connect();
InputStream is = conn.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(is));
String ret = "";
while ((ret = br.readLine()) != null) {
if (ret != null && !ret.trim().equals("")) {
result.append(new String(ret.getBytes("ISO-8859-1"), "utf-8"));
}
}
log.info("recv - {}", result);
conn.disconnect();
br.close();
} catch (ConnectException e) {
log.error("调用HttpUtils.sendSSLPost ConnectException, url=" + url + ",param=" + param, e);
} catch (SocketTimeoutException e) {
log.error("调用HttpUtils.sendSSLPost SocketTimeoutException, url=" + url + ",param=" + param, e);
} catch (IOException e) {
log.error("调用HttpUtils.sendSSLPost IOException, url=" + url + ",param=" + param, e);
} catch (Exception e) {
log.error("调用HttpsUtil.sendSSLPost Exception, url=" + url + ",param=" + param, e);
}
return result.toString();
}
public static String sendTwoPost(String url, String param, String token) {
PrintWriter out = null;
BufferedReader in = null;
StringBuilder result = new StringBuilder();
try {
String urlNameString = url;
log.info("sendPost - {}", urlNameString);
URL realUrl = new URL(urlNameString);
URLConnection conn = realUrl.openConnection();
conn.setRequestProperty("accept", "*/*");
conn.setRequestProperty("connection", "Keep-Alive");
conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
conn.setRequestProperty("Accept-Charset", "utf-8");
conn.setRequestProperty("contentType", "utf-8");
if (!StringUtils.isEmpty(token)) {
conn.setRequestProperty("token", token);
}
conn.setDoOutput(true);
conn.setDoInput(true);
out = new PrintWriter(conn.getOutputStream());
out.print(param);
out.flush();
in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "utf-8"));
String line;
while ((line = in.readLine()) != null) {
result.append(line);
}
log.info("recv - {}", result);
} catch (ConnectException e) {
log.error("调用HttpUtils.sendPost ConnectException, url=" + url + ",param=" + param, e);
} catch (SocketTimeoutException e) {
log.error("调用HttpUtils.sendPost SocketTimeoutException, url=" + url + ",param=" + param, e);
} catch (IOException e) {
log.error("调用HttpUtils.sendPost IOException, url=" + url + ",param=" + param, e);
} catch (Exception e) {
log.error("调用HttpsUtil.sendPost Exception, url=" + url + ",param=" + param, e);
} finally {
try {
if (out != null) {
out.close();
}
if (in != null) {
in.close();
}
} catch (IOException ex) {
log.error("调用in.close Exception, url=" + url + ",param=" + param, ex);
}
}
return result.toString();
}
public static JSONObject volunteer(String url,String token) {
BufferedReader in = null;
StringBuilder result = new StringBuilder();
try {
String urlNameString = url;
log.info("sendPost - {}", urlNameString);
URL realUrl = new URL(urlNameString);
URLConnection conn = realUrl.openConnection();
conn.setRequestProperty("accept", "*/*");
conn.setRequestProperty("connection", "Keep-Alive");
conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
conn.setRequestProperty("Accept-Charset", "utf-8");
conn.setRequestProperty("contentType", "utf-8");
if (!StringUtils.isEmpty(token)) {
conn.setRequestProperty("token", token);
}
conn.setDoOutput(true);
conn.setDoInput(true);
in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "utf-8"));
String line;
while ((line = in.readLine()) != null) {
result.append(line);
}
log.info("recv - {}", result);
} catch (Exception e) {
log.error("调用HttpsUtil.sendPost Exception, url={},ERR_MSG={}" , url , e);
} finally {
try {
if (in != null) {
in.close();
}
} catch (IOException ex) {
log.error("调用in.close Exception, url=" + url , ex);
}
}
return JSONObject.parseObject(result.toString());
}
private static class TrustAnyTrustManager implements X509TrustManager {
@Override
public void checkClientTrusted(X509Certificate[] chain, String authType) {
}
@Override
public void checkServerTrusted(X509Certificate[] chain, String authType) {
}
@Override
public X509Certificate[] getAcceptedIssuers() {
return new X509Certificate[]{
};
}
}
private static class TrustAnyHostnameVerifier implements HostnameVerifier {
@Override
public boolean verify(String hostname, SSLSession session) {
return true;
}
}
public static String get(String urlStr, Map<String, String> parameters) throws IOException {
URL url = new URL(urlStr);
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setDoInput(true);
httpURLConnection.setDoOutput(true);
httpURLConnection.setRequestMethod("GET");
httpURLConnection.setRequestProperty("charset", "utf-8");
PrintWriter pw = new PrintWriter(new BufferedOutputStream(httpURLConnection.getOutputStream()));
StringBuffer parameter = new StringBuffer();
parameter.append("1=1");
for (Map.Entry<String, String> entry : parameters.entrySet()) {
parameter.append("&" + entry.getKey() + "=" + entry.getValue());
}
pw.write(parameter.toString());
pw.flush();
pw.close();
BufferedReader br = new BufferedReader(new InputStreamReader(httpURLConnection.getInputStream(), "utf-8"));
String line = null;
StringBuilder sb = new StringBuilder();
while ((line = br.readLine()) != null) {
sb.append(line + "\n");
}
br.close();
return sb.toString();
}
获取小程序二维码
二维码
@GetMapping("qrcode")
public Result qrcode(HttpServletRequest req, String content) {
Member member = getMember(req);
if (member == null) {
return Result.error(201, WEB_TOKEN_INVALID);
}
BitMatrix encode = QrCodeUtil.encode(content, 260, 260);
BufferedImage bufferedImage = QrCodeUtil.toImage(encode, 0xFF000000, null);
try {
String bufferedImageToBase64 = getBufferedImageToBase64(bufferedImage, null);
String url = getUrl(bufferedImageToBase64, member.getId());
return Result.ok(url);
} catch (IOException e) {
e.printStackTrace();
}
return Result.error("二维码生成失败");
}
小程序二维码
@GetMapping("qrcode")
public Result qrcode(HttpServletRequest req, String path) {
Member member = getMember(req);
if (member == null) {
return Result.error(201, WEB_TOKEN_INVALID);
}
String accessToken = (String) redisUtil.get(PlatformConstant.WX_ACCESS_TOKEN_KEY);
if (StringUtils.isEmpty(accessToken)){
accessToken = WeChatUtil.getWxAccessToken();
redisUtil.set(PlatformConstant.WX_ACCESS_TOKEN_KEY,accessToken);
}
String fileName = "qr"+member.getId()+".png";
String filePath = "/root/"+fileName;
WeChatUtil.getWxQRCode(path,accessToken,filePath);
return Result.ok("https://wap.tayunxinxi.com/img/"+fileName);
}
工具类
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-all</artifactId>
<version>${
hutool-all.version}</version>
</dependency>
可直接在前端展示的和保存服务器返回路径,两种方式
public static String getBufferedImageToBase64(BufferedImage bufferedImage, String imageFormatName) throws IOException {
if (StringUtils.isEmpty(imageFormatName)) {
imageFormatName = "png";
}
ByteArrayOutputStream stream = new ByteArrayOutputStream();
ImageIO.write(bufferedImage, imageFormatName, stream);
String s = Base64.getEncoder().encodeToString(stream.toByteArray());
return "data:image/jpg;base64," + s;
}
private String getUrl(String base64string, String account) {
int index = base64string.indexOf("base64,") + 7;
String newImage = base64string.substring(index, base64string.length());
BASE64Decoder decoder = new BASE64Decoder();
try {
byte[] b = decoder.decodeBuffer(newImage);
for (int i = 0; i < b.length; ++i) {
if (b[i] < 0) {
b[i] += 256;
}
}
String fileName = "qr" + account + ".png";
String pathString = "/root/" + fileName;
File file = new File(pathString);
if (file.exists()) {
file.createNewFile();
}
FileOutputStream out = new FileOutputStream(pathString);
out.write(b);
out.flush();
out.close();
System.out.println("生成图片结束");
return prefix + fileName;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
微信工具类
@Slf4j
public class WeChatUtil {
public static String getWxAccessToken() {
String accessTokenUrl="https://api.weixin.qq.com/cgi-bin/token";
Map<String,Object> params = new HashMap<String,Object>();
params.put("appid", PlatformConstant.WX_APPID);
params.put("secret",PlatformConstant.WX_SECRET);
params.put("grant_type","client_credential");
try {
String accessTokenResult = HttpClientUtil.getInstance().doGet(accessTokenUrl,params,null);
log.info("---------微信access_token刷新返回信息:{}",accessTokenResult);
JSONObject accessTokenJson = JSONObject.parseObject(accessTokenResult);
if(accessTokenJson.get("errcode")!=null&&!"0".equals(accessTokenJson.get("errcode"))){
return null;
}
String accessToken = accessTokenJson.getString("access_token");
return accessToken;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
public static Map<String,String> authCode2Session(String code) {
String authCode2SessionUrl="https://api.weixin.qq.com/sns/jscode2session";
Map<String,Object> params = new HashMap<String,Object>();
params.put("appid", PlatformConstant.WX_APPID);
params.put("secret",PlatformConstant.WX_SECRET);
params.put("js_code",code);
params.put("grant_type","authorization_code");
try {
String authResult = HttpClientUtil.getInstance().doGet(authCode2SessionUrl,params,null);
log.info("---------微信授权登录返回信息:{}",authResult);
JSONObject accessTokenJson = JSONObject.parseObject(authResult);
if(accessTokenJson.get("errcode")!=null&&!"0".equals(accessTokenJson.get("errcode"))){
return null;
}
String openId = accessTokenJson.getString("openid");
String unionId = accessTokenJson.getString("unionid");
String sessionKey = accessTokenJson.getString("session_key");
Map<String,String> resultMap = new HashMap<String,String>();
resultMap.put("openId",openId);
resultMap.put("unionId",unionId);
resultMap.put("sessionKey",sessionKey);
return resultMap;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
public static void getWxQRCode(String path, String accessToken,String filePath) {
String wxQRCodeUrl = "https://api.weixin.qq.com/wxa/getwxacode?access_token="+accessToken;
JSONObject params = new JSONObject();
params.put("path",path);
InputStream inputStream = HttpClientUtil.getInstance().doPostBackStream(wxQRCodeUrl, params.toString());
BufferedInputStream bis = new BufferedInputStream(inputStream);
try {
OutputStream os = new FileOutputStream(new File(filePath));
int len;
byte[] arr = new byte[1024];
while ((len = bis.read(arr)) != -1) {
os.write(arr, 0, len);
os.flush();
}
os.close();
} catch (IOException e) {
e.printStackTrace();
}
}
微信登录(app)
@PostMapping("/wechat")
public AjaxResult wechat(String openId) {
if (StringUtils.isEmpty(openId)) {
return AjaxResult.error("参数不能为空");
}
AppUserWx userWx = appUserWxService.getByOpenId(openId);
if (userWx == null) {
return AjaxResult.error("账号不存在,请先注册");
}
Long userId = userWx.getUserId();
AppUser user = appUserService.selectAppUserById(userId);
return AjaxResult.success(map);
}