我不写代码,我只是代码的搬运工。
导入pom文件
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.3</version><!--$NO-MVN-MAN-VER$ -->
</dependency>
<!-- 微信支付 -->
<dependency>
<groupId>com.github.wxpay</groupId>
<artifactId>wxpay-sdk</artifactId>
<version>0.0.3</version>
</dependency>
第一步获取微信openID
* 获取openID
*
* @param code
* @return
* @throws Exception
*/
@RequestMapping(value = "/getWxOpenid", method = RequestMethod.GET, produces = "application/json")
@ApiOperation("获取微信Openid")
public R getOpenidNews(String code) throws Exception {
/**
* 第一步 通过code获取openId
*/
LOGGER.info("微信code-->" + code);
// 页面获取openId接口
String getopenid_url = "https://api.weixin.qq.com/sns/oauth2/access_token";
String param = "appid=" + PrivateParam.APP_ID + "&secret=" + PrivateParam.APP_SECRET + "&code=" + code
+ "&grant_type=authorization_code";
String openIdStr = HttpRequestUtil.sendGet(getopenid_url, param);
// 转成Json格式
JSONObject json = JSONObject.parseObject(openIdStr);
LOGGER.info("json-->" + json);
if ("40029".equals(json.getString("errcode"))) {
return R.error().put("data", "Code无效错误!").put("json", json);
}
// 获取openId
String openId = json.getString("openid");
if (openId == null) {
return R.error().put("data", "openId为空值!");
}
WxOpenidEntity wx = new WxOpenidEntity();
// 网页授权接口的凭证
wx.setAccessToken(json.getString("access_token"));
// access_token接口调用凭证超时时间单位
wx.setExpiresIn(json.getString("expires_in"));
// 用户刷新access_token
wx.setRefreshToken(json.getString("refresh_token"));
// 用户的唯一标识
wx.setOpenid(json.getString("openid"));
// 用户授权的作用域
wx.setScope(json.getString("scope"));
return R.ok().put("data", wx);
}
HttpRequestUtil 工具类
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.URL;
import java.net.URLConnection;
import java.util.List;
import java.util.Map;
/**
*
* @author Mr.wang
* @version 2019年12月12日 下午4:09:30 微信支付类型
*/
public class HttpRequestUtil {
/**
* 向指定URL发送GET方法的请求
*
* @param url 发送请求的URL
* @param param 请求参数,请求参数应该是 name1=value1&name2=value2 的形式。
* @return URL 所代表远程资源的响应结果
*/
public static String sendGet(String url, String param) {
String result = "";
BufferedReader in = null;
try {
String urlNameString = url + "?" + param;
System.out.println(urlNameString);
URL realUrl = new URL(urlNameString);
// 打开和URL之间的连接
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();
// 获取所有响应头字段
Map<String, List<String>> map = connection.getHeaderFields();
// 遍历所有的响应头字段
for (String key : map.keySet()) {
System.out.println(key + "--->" + map.get(key));
}
// 定义 BufferedReader输入流来读取URL的响应
in = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));
String line;
while ((line = in.readLine()) != null) {
result += line;
}
} catch (Exception e) {
System.out.println("发送GET请求出现异常!" + e);
e.printStackTrace();
}
// 使用finally块来关闭输入流
finally {
try {
if (in != null) {
in.close();
}
} catch (Exception e2) {
e2.printStackTrace();
}
}
return result;
}
/**
* 向指定 URL 发送POST方法的请求
*
* @param url 发送请求的 URL
* @param param 请求参数,请求参数应该是 name1=value1&name2=value2 的形式。
* @return 所代表远程资源的响应结果
*/
public static String sendPost(String url, String param) {
PrintWriter out = null;
BufferedReader in = null;
String result = "";
try {
URL realUrl = new URL(url);
// 打开和URL之间的连接
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)");
// 发送POST请求必须设置如下两行
conn.setDoOutput(true);
conn.setDoInput(true);
// 获取URLConnection对象对应的输出流
out = new PrintWriter(conn.getOutputStream());
// 发送请求参数
out.print(param);
// flush输出流的缓冲
out.flush();
// 定义BufferedReader输入流来读取URL的响应
in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
String line;
while ((line = in.readLine()) != null) {
result += line;
}
} catch (Exception e) {
System.out.println("发送 POST 请求出现异常!" + e);
e.printStackTrace();
}
// 使用finally块来关闭输出流、输入流
finally {
try {
if (out != null) {
out.close();
}
if (in != null) {
in.close();
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
return result;
}
}
WxOpenidEntity 实体类
import lombok.Data;
@Data
public class WxOpenidEntity {
/**
* 网页授权接口调用凭证,注意:此access_token与基础支持的access_token不同
*/
private String accessToken;`在这里插入代码片`
/**
* access_token接口调用凭证超时时间,单位(秒)
*/
private String expiresIn;
/**
* 用户刷新access_token
*/
private String refreshToken;
/**
* 用户唯一标识
*/
private String openid;
/**
* 用户授权的作用域,使用逗号(,)分隔
*/
private String scope;
}
第二步-获取微信用户信息
/**
* 获取微信用户信息
*
* @param accessToken
* @param openid
* @return
* @throws Exception
*/
@RequestMapping(value = "/getWxUserMsg", method = RequestMethod.GET, produces = "application/json")
@ApiOperation("获取微信用户信息")
public R getWxUnionid(String accessToken, String openid) throws Exception {
/**
* 第一步 通过code获取openId
*/
System.out.println("accessToken-->" + accessToken);
System.out.println("openid-->" + openid);
// 页面获取openId接口
String getopenid_url = "https://api.weixin.qq.com/sns/userinfo";
String param = "access_token=" + accessToken + "&openid=" + openid + "&lang=zh_CN";
String openIdStr = HttpRequestUtil.sendGet(getopenid_url, param);
// 转成Json格式
JSONObject json = JSONObject.parseObject(openIdStr);
if ("40003".equals(json.getString("errcode"))) {
return R.error().put("msg", "openid无效!").put("json", json);
}
WxUnionidEntity unionid = new WxUnionidEntity();
// 用户微信openID
unionid.setOpenid(json.getString("openid"));
// 用户昵称
unionid.setNickname(json.getString("nickname"));
// 用户性别
unionid.setSex(json.getString("sex"));
// 用户个人资料填写的省份
unionid.setProvince(json.getString("province"));
// 用户个人资料填写的城市
unionid.setCity(json.getString("city"));
// 用户个人资料填写的国家
unionid.setCountry(json.getString("country"));
// 用户头像
unionid.setHeadimgurl(json.getString("headimgurl"));
// 用户特权信息
unionid.setPrivilege(json.getString("privilege"));
// 用户unionid
unionid.setUnionid(json.getString("unionid"));
return R.ok().put("data", unionid);
}
WxUnionidEntity 实体类
import lombok.Data;
@Data
public class WxUnionidEntity {
/**
* 用户的唯一标识
*/
private String openid;
/**
* 用户昵称
*/
private String nickname;
/**
* 用户的性别,值为1时是男性,值为2时是女性,值为0时是未知
*/
private String sex;
/**
* 用户个人资料填写的省份
*/
private String province;
/**
* 普通用户个人资料填写的城市
*/
private String city;
/**
* 国家,如中国为CN
*/
private String country;
/**
* 用户头像,最后一个数值代表正方形头像大小(有0、46、64、96、132数值可选,0代表640*640正方形头像),用户没有头像时该项为空。若用户更换头像,原有头像URL将失效。
*/
private String headimgurl;
/**
* 用户特权信息,json 数组,如微信沃卡用户为(chinaunicom)
*/
private String privilege;
/**
* 只有在用户将公众号绑定到微信开放平台帐号后,才会出现该字段。
*/
private String unionid;
}