微信测试号网页授权及获取用户信息

master
jyx 6 years ago
parent 5a0c9428e7
commit b3f3e0e374

@ -0,0 +1,18 @@
package com.example.demo.weixin.bean;
import lombok.Getter;
import lombok.Setter;
@Setter
@Getter
public class UserInfo {
private String openid; //用户的唯一标识
private String nickname; //用户昵称
private String sex; //用户的性别值为1时是男性值为2时是女性值为0时是未知
private String province; //用户个人资料填写的省份
private String city; //普通用户个人资料填写的城市
private String country; //国家如中国为CN
private String headimgurl; //用户头像最后一个数值代表正方形头像大小有0、46、64、96、132数值可选0代表640*640正方形头像用户没有头像时该项为空。若用户更换头像原有头像URL将失效。
private String privilege; //用户特权信息json 数组如微信沃卡用户为chinaunicom
private String unionid; //只有在用户将公众号绑定到微信开放平台帐号后,才会出现该字段。
}

@ -0,0 +1,14 @@
package com.example.demo.weixin.bean.authorize;
import lombok.Getter;
import lombok.Setter;
@Setter
@Getter
public class CodeToken {
private String openid;
private String Access_token;
private int Expires_in;
private String refresh_token;
private String scope;
}

@ -1,8 +1,11 @@
package com.example.demo.weixin.controller;
import com.example.demo.weixin.bean.UserInfo;
import com.example.demo.weixin.bean.authorize.CodeToken;
import com.example.demo.weixin.service.DataProcess;
import com.example.demo.weixin.service.WeixinCoreService;
import com.example.demo.weixin.util.WeixinSignUtil;
import com.example.demo.weixin.util.connection.WechatCommonUtil;
import com.example.demo.weixin.util.connection.WeixinSignUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
@ -13,6 +16,9 @@ import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import static com.example.demo.weixin.util.WechatConstants.appid;
import static com.example.demo.weixin.util.WechatConstants.appsecret;
@RestController
@RequestMapping(value = "/wechat")
public class WeixinCoreController {
@ -23,6 +29,8 @@ public class WeixinCoreController {
@Autowired
private WeixinSignUtil weixinSignUtil;
@Autowired
private WechatCommonUtil wechatCommonUtil;
@Autowired
private DataProcess dataProcess;
@Autowired
private WeixinCoreService weixinCoreService;
@ -69,4 +77,33 @@ public class WeixinCoreController {
}
}
@RequestMapping(value = "/auth",method = RequestMethod.GET)
public UserInfo auth(HttpServletRequest request,HttpServletResponse response)throws Exception{
logger.info("--------进入auth的方法--------");
String code = request.getParameter("code");
logger.info("code={}",code);
CodeToken codeToken = wechatCommonUtil.getCodeToken(appid,appsecret,code);
UserInfo userInfo = new UserInfo();
if(codeToken!=null){
try{
String openid = codeToken.getOpenid();
String refresh_token = codeToken.getRefresh_token();
String access_token = codeToken.getAccess_token();
//判断access_token是否过期
if(!wechatCommonUtil.isTokenValid(access_token,appid)){
wechatCommonUtil.refreshToken(appid,refresh_token);
}
logger.info("开始获取用户信息");
userInfo = wechatCommonUtil.getUserInfo(access_token,openid);
}catch (Exception e){
userInfo = null;
}
}else{
logger.info("用户授权失败");
}
return userInfo;
}
}

@ -144,6 +144,7 @@ public class WeixinCoreServiceImpl implements WeixinCoreService {
}
// 自定义菜单((自定义菜单URl视图)
else if (eventType.equals(weixinMessageUtil.EVENT_TYPE_VIEW)) {
respMessage = "自定义菜单uri视图";
System.out.println("处理自定义菜单URI视图");
}

@ -0,0 +1,17 @@
package com.example.demo.weixin.util;
public class WechatConstants {
public static String ACCESS_TOKEN_URL = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET";
public static String MENU_CREATE_URL = "https://api.weixin.qq.com/cgi-bin/menu/create?access_token=ACCESS_TOKEN";
public static String MENU_GET_URL = "https://api.weixin.qq.com/cgi-bin/menu/get?access_token=ACCESS_TOKEN";
public static String MENU_DELETE_URL = "https://api.weixin.qq.com/cgi-bin/menu/delete?access_token=ACCESS_TOKEN";
public static String appid = "wx473235c6be5c945a";
public static String appsecret = "69a0c7bcccf20833fd549ae9a530d299";
public static String redirect_url = "http://loan.ngrok.xiaomiqiu.cn/wechat/auth";
public static String ACCESS_TOKEN_URL_BY_CODE = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=APPID&secret=SECRET&code=CODE&grant_type=authorization_code";
public static String CODE_URL = "https://open.weixin.qq.com/connect/oauth2/authorize?appid="+appid
+"&redirect_uri="+redirect_url+"&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect"; //scope=snsapi_base获取用户openid
public static String REFRESH_TOKEN = "https://api.weixin.qq.com/sns/oauth2/refresh_token?appid=APPID&grant_type=refresh_token&refresh_token=REFRESH_TOKEN";
public static String SNSAPI_USERINFO_URL = "https://api.weixin.qq.com/sns/userinfo?access_token=ACCESS_TOKEN&openid=OPENID&lang=zh_CN";
public static String IS_TOKEN_VAILD = "https://api.weixin.qq.com/sns/auth?access_token=ACCESS_TOKEN&openid=OPENID";
}

@ -0,0 +1,167 @@
package com.example.demo.weixin.util.connection;
import com.example.demo.weixin.bean.UserInfo;
import com.example.demo.weixin.bean.authorize.CodeToken;
import com.example.demo.weixin.bean.menu.AccessToken;
import com.example.demo.weixin.util.WechatConstants;
import com.example.demo.weixin.util.https.HttpRequestUtil;
import net.sf.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
/**
* access_token
*/
@Component
public class WechatCommonUtil {
Logger logger = LoggerFactory.getLogger(WechatCommonUtil.class);
//获取access_token接口
private static String token_url = WechatConstants.ACCESS_TOKEN_URL;
//@Autowired
HttpRequestUtil httpRequestUtil = new HttpRequestUtil();
/**
* @Description: access_token
* @Parameters:
* @Return:
*/
public AccessToken getAccessToken(String appid,String appsecret){
//将公众号的appid和appsecret替换进url
//String.replace()替换原字符串中的子串
String url = token_url.replace("APPID", appid).replace("APPSECRET", appsecret);
AccessToken accessToken = new AccessToken();
//发起get请求获取凭证
JSONObject jsonObject = httpRequestUtil.httpsRequest(url,"GET",null);
logger.info("获取到的json格式的Token为:"+jsonObject);
if (jsonObject!=null) {
try {
accessToken.setAccess_token(jsonObject.getString("access_token"));
accessToken.setExpires_in(jsonObject.getInt("expires_in"));
} catch (Exception e) {
accessToken = null;
//获取token失败
logger.error("获取token失败 errcode:{} errmsg:{}",
jsonObject.getInt("errcode"),
jsonObject.getString("errmsg"));
}
}
return accessToken;
}
/**
* @Description: codeaccess_token
* @Parameters:
* @Return:
*/
public CodeToken getCodeToken(String appid,String secret,String code){
token_url = WechatConstants.ACCESS_TOKEN_URL_BY_CODE;
//将appidsecret,code替换进url
String url = token_url.replace("APPID",appid).replace("SECRET",secret).replace("CODE",code);
CodeToken codeToken = new CodeToken();
//发起get请求获取凭证
JSONObject jsonObject = httpRequestUtil.httpsRequest(url,"GET",null);
logger.info("获取到的json格式的Token为:"+jsonObject);
if(jsonObject!=null){
try{
codeToken.setAccess_token(jsonObject.getString("access_token"));
codeToken.setExpires_in(jsonObject.getInt("expires_in"));
codeToken.setOpenid(jsonObject.getString("openid"));
codeToken.setRefresh_token(jsonObject.getString("refresh_token"));
codeToken.setScope(jsonObject.getString("scope"));
}catch(Exception e){
codeToken = null;
//获取token失败
logger.error("获取token失败 errcode:{} errmsg:{}",
jsonObject.getInt("errcode"),
jsonObject.getString("errmsg"));
}
}
return codeToken;
}
/**
* access_token
*/
public CodeToken refreshToken(String appid,String refresh_token){
token_url = WechatConstants.REFRESH_TOKEN;
String url = token_url.replace("APPID",appid).replace("refresh_token",refresh_token);
CodeToken codeToken = new CodeToken();
JSONObject jsonObject = httpRequestUtil.httpsRequest(url,"GET",null);
if(jsonObject!=null){
try{
codeToken.setScope(jsonObject.getString("scope"));
codeToken.setRefresh_token(jsonObject.getString("refresh_token"));
codeToken.setAccess_token(jsonObject.getString("access_token"));
codeToken.setExpires_in(jsonObject.getInt("expires_in"));
codeToken.setOpenid(jsonObject.getString("openid"));
}catch (Exception e){
codeToken = null;
//获取token失败
logger.error("获取token失败 errcode:{} errmsg:{}",
jsonObject.getInt("errcode"),
jsonObject.getString("errmsg"));
}
}
return codeToken;
}
/**
*
*/
public UserInfo getUserInfo(String access_token,String openid){
token_url = WechatConstants.SNSAPI_USERINFO_URL;
String url = token_url.replace("ACCESS_TOKEN",access_token).replace("OPENID",openid);
UserInfo userInfo = new UserInfo();
JSONObject jsonObject = httpRequestUtil.httpsRequest(url,"GET",null);
if(jsonObject!=null){
try{
userInfo.setCity(jsonObject.getString("city"));
userInfo.setCountry(jsonObject.getString("country"));
userInfo.setHeadimgurl(jsonObject.getString("headimgurl"));
userInfo.setNickname(jsonObject.getString("nickname"));
userInfo.setOpenid(jsonObject.getString("openid"));
userInfo.setPrivilege(jsonObject.getString("privilege"));
userInfo.setProvince(jsonObject.getString("province"));
userInfo.setSex(jsonObject.getString("sex"));
userInfo.setUnionid(jsonObject.getString("unionid"));
}catch (Exception e){
userInfo = null;
//获取信息失败
logger.info("获取信息失败errcode{} errmsg:{}",
jsonObject.getInt("errcode"),
jsonObject.getString("errmsg"));
}
}
return userInfo;
}
/**
* access_token
*/
public boolean isTokenValid(String access_token,String openid)throws Exception{
token_url = WechatConstants.IS_TOKEN_VAILD;
String url = token_url.replace("ACCESS_TOKEN",access_token).replace("OPENID",openid);
JSONObject jsonObject = httpRequestUtil.httpsRequest(url,"GET",null);
boolean flag = false;
if(jsonObject!=null){
if(jsonObject.getInt("errcode")==0)flag=true;
}
logger.info("errcode:{} errmsg:{}",
jsonObject.getInt("errcode"),
jsonObject.getString("errmsg"));
return flag;
}
}

@ -2,7 +2,7 @@
* signature
*/
package com.example.demo.weixin.util;
package com.example.demo.weixin.util.connection;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

@ -1,4 +1,4 @@
package com.example.demo.weixin.service.https;
package com.example.demo.weixin.util.https;
import net.sf.json.JSONObject;
import org.slf4j.Logger;
@ -43,7 +43,14 @@ public class HttpRequestUtil {
HttpsURLConnection httpsURLConnection = (HttpsURLConnection)url.openConnection();
httpsURLConnection.setSSLSocketFactory(sslSocket);
httpsURLConnection.setDoOutput(true); /*httpUrlConnection.setDoOutput(true);以后就可以使用conn.getOutputStream().write() httpUrlConnection.setDoInput(true);以后就可以使用conn.getInputStream().read(); get请求用不到conn.getOutputStream()因为参数直接追加在地址后面因此默认是false。 post请求比如文件上传需要往服务区传输大量的数据这些数据是放在http的body里面的因此需要在建立连接以后往服务端写数据。 因为总是使用conn.getInputStream()获取服务端的响应因此默认值是true。 */
httpsURLConnection.setDoOutput(true);
/**
*httpUrlConnection.setDoOutput(true);使conn.getOutputStream().write()
*httpUrlConnection.setDoInput(true);使conn.getInputStream().read();
*getconn.getOutputStream()false
*posthttpbody
*使conn.getInputStream()true
*/
httpsURLConnection.setDoInput(true);
httpsURLConnection.setUseCaches(false);
//设置请求方式 GET/POST

@ -2,7 +2,7 @@
* https X509TrustManager
*/
package com.example.demo.weixin.service.https;
package com.example.demo.weixin.util.https;
import javax.net.ssl.X509TrustManager;
import java.security.cert.CertificateEncodingException;

@ -1,52 +0,0 @@
package com.example.demo.weixin.util.menu;
import com.example.demo.weixin.bean.menu.AccessToken;
import com.example.demo.weixin.service.https.HttpRequestUtil;
import net.sf.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
/**
* access_token
*/
@Component
public class WechatCommonUtil {
Logger logger = LoggerFactory.getLogger(WechatCommonUtil.class);
//获取access_token接口
private static String token_url = WechatConstants.ACCESS_TOKEN_URL;
//@Autowired
HttpRequestUtil httpRequestUtil = new HttpRequestUtil();
/**
* @Description: access_token
* @Parameters:
* @Return:
*/
public AccessToken getAccessToken(String appid,String appsecret){
//将公众号的appid和appsecret替换进url
//String.replace()替换原字符串中的子串
String url = token_url.replace("APPID", appid).replace("APPSECRET", appsecret);
AccessToken accessToken = new AccessToken();
//发起get请求获取凭证
JSONObject jsonObject = httpRequestUtil.httpsRequest(url,"GET",null);
logger.info("获取到的json格式的Token为:"+jsonObject);
if (jsonObject!=null) {
try {
accessToken.setAccess_token(jsonObject.getString("access_token"));
accessToken.setExpires_in(jsonObject.getInt("expires_in"));
} catch (Exception e) {
accessToken = null;
//获取token失败
logger.error("获取token失败 errcode:{} errmsg:{}",
jsonObject.getInt("errcode"),
jsonObject.getString("errmsg"));
}
}
return accessToken;
}
}

@ -1,8 +0,0 @@
package com.example.demo.weixin.util.menu;
public class WechatConstants {
public static String ACCESS_TOKEN_URL = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET";
public static String MENU_CREATE_URL = "https://api.weixin.qq.com/cgi-bin/menu/create?access_token=ACCESS_TOKEN";
public static String MENU_GET_URL = "https://api.weixin.qq.com/cgi-bin/menu/get?access_token=ACCESS_TOKEN";
public static String MENU_DELETE_URL = "https://api.weixin.qq.com/cgi-bin/menu/delete?access_token=ACCESS_TOKEN";
}

@ -2,6 +2,10 @@ package com.example.demo.weixin.util.menu;
import com.example.demo.weixin.bean.menu.Menu;
import com.example.demo.weixin.util.connection.WechatCommonUtil;
import static com.example.demo.weixin.util.WechatConstants.appid;
import static com.example.demo.weixin.util.WechatConstants.appsecret;
/**
* @Description:
@ -13,8 +17,7 @@ public class WechatCreatDefaultMenu {
WechatCommonUtil wechatCommonUtil = new WechatCommonUtil();
WechatMenuUtil wechatMenuUtil = new WechatMenuUtil();
WechatMenuManagerUtil wechatMenuManagerUtil = new WechatMenuManagerUtil();
String appid = "wx473235c6be5c945a";
String appsecret = "69a0c7bcccf20833fd549ae9a530d299";
//获取access_token
String accessToken = wechatCommonUtil.getAccessToken(appid, appsecret).getAccess_token();

@ -2,6 +2,8 @@ package com.example.demo.weixin.util.menu;
import com.example.demo.weixin.bean.menu.*;
import static com.example.demo.weixin.util.WechatConstants.CODE_URL;
/**
* @Description:
@ -23,7 +25,7 @@ public class WechatMenuManagerUtil {
ViewButton firstViewButton = new ViewButton();
firstViewButton.setName("业务介绍");
firstViewButton.setType("view");
firstViewButton.setUrl("http://loan.ngrok.xiaomiqiu.cn/personalCenter.html");
firstViewButton.setUrl(CODE_URL);
ViewButton secondViewButton = new ViewButton();
secondViewButton.setName("我要贷款");
@ -34,7 +36,7 @@ public class WechatMenuManagerUtil {
ViewButton viewButton1 = new ViewButton();
viewButton1.setType("view");
viewButton1.setName("个人中心");
viewButton1.setName("中心");
viewButton1.setUrl("http://loan.ngrok.xiaomiqiu.cn/personalCenter.html");
ViewButton viewButton2 = new ViewButton();

@ -1,7 +1,8 @@
package com.example.demo.weixin.util.menu;
import com.example.demo.weixin.bean.menu.Menu;
import com.example.demo.weixin.service.https.HttpRequestUtil;
import com.example.demo.weixin.util.WechatConstants;
import com.example.demo.weixin.util.https.HttpRequestUtil;
import net.sf.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

@ -1,9 +1,9 @@
spring.datasource.url=jdbc:mysql://127.0.0.1:3306/soft?serverTimezone=GMT%2B8
spring.datasource.username=root
spring.datasource.password=123456789
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
#spring.datasource.max-idle=10
#spring.datasource.max-wait=10000
#spring.datasource.min-idle=5
#spring.datasource.initial-size=5
#spring.datasource.url=jdbc:mysql://127.0.0.1:3306/soft?serverTimezone=GMT%2B8
#spring.datasource.username=root
#spring.datasource.password=123456789
#spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
##spring.datasource.max-idle=10
##spring.datasource.max-wait=10000
##spring.datasource.min-idle=5
##spring.datasource.initial-size=5
#

@ -1,14 +1,14 @@
#spring:
# mvc:
# view:
# prefix:
# suffix: .html
# datasource:
# url: jdbc:mysql://127.0.0.1:3306/soft?useUnicode=true&characterEncoding=utf8&serverTimezone=GMT%2B8
# username: root
# password:
# driver-class-name: com.mysql.cj.jdbc.Driver
#mybatis:
# type-aliases-package: com.example.demo.Dao
##server:
## path: 80
spring:
mvc:
view:
prefix:
suffix: .html
datasource:
url: jdbc:mysql://127.0.0.1:3306/loan?useUnicode=true&characterEncoding=utf8&serverTimezone=GMT%2B8
username: root
password: 12345678
driver-class-name: com.mysql.cj.jdbc.Driver
mybatis:
type-aliases-package: com.example.demo.Dao
server:
port: 80

Loading…
Cancel
Save