最近忙着做一个登录公众号获取用户信息及用户分享后可以得到积分。
首先用户点击一个链接
window.location.href="https://open.weixin.qq.com/connect/oauth2/authorize?appid=#&redirect_uri=#&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect"
appid是你公众号里的
redirect_ur是调用微信返回数据,咱们系统接收code的方法,这个必须要是外网可以访问的 http://www.....com/OhdWeixin/UserAction!getPersonal.action
response_type=code
cope=snsapi_userinfo
state=STATE#wechat_redirect"
1.获取用户信息de action;可以在这一步就获取用户的信息 放在自己的库里 ,我们需求是要在登录的时候把登录信息一起放在一个库里,
public String getPersonal() throws Exception {
String result="login";
BindUserFace bindUserFace = this.getBeanByBeanClass(BindUserFace.class);
String code = request.getParameter("code"); //用户同意授权后,能获取到code
if(!"authdeny".equals(code) && code!=null){
//获取网页授权accexx_token
WeixinOauth2TokenView weixinOauth2TokenView = AdvancedUtil.getOauth2AccessToken(CommonUtil.appId, CommonUtil.appSecret, code);
if(weixinOauth2TokenView!=null) {
//用户标识
String openId = weixinOauth2TokenView.getOpenId();
//网页授权接口访问凭证
String accessToken = weixinOauth2TokenView.getAccessToken();
session.put("openid",openId);
session.put("accessToken",accessToken);
BindWxUser bindWxUser=bindUserFace.findBindWxUser(openId);//openId
if(bindWxUser!=null){
session.put("bindWxUser",bindWxUser);
getMallURL();
result="personal";//这是跳到个人中心页面
}else{
result="login";//如果没有
}
}
}
return result;
}
2.要获取用户的openid 来获取用户的头像:
/**
* 登录(注册)
*/
public String login() throws Exception {
BindUserFace bindUserFace = this.getBeanByBeanClass(BindUserFace.class);
if(session.get("openid")==null && session.get("accessToken")==null) {
String code = request.getParameter("code");
//用户同意授权
if(!"authdeny".equals(code) && code!=null){
String accessToken= (String) session.get("accessToken");
String openid= (String) session.get("openid");
BindWxUser binUs=bindUserFace.findBindWxUser(openid);//openId
if(binUs==null){
//获取用户信息
String tel=bindWxUser.getMobile();
bindWxUser=AdvancedUtil.getSNSUserInfo(accessToken,openid);
bindWxUser.setMobile(tel);
bindWxUser.setRecommender(recommender);
bindUserFace.addBindWxUser(bindWxUser);//保存用户信息
session.put("bindWxUser",bindWxUser);
getMallURL();
}
}
}
return "personal";
}
下面是调用微信接口的util
public class AdvancedUtil {
private static Map<String,WeixinOauth2TokenView> map=new HashMap<String,WeixinOauth2TokenView>();
private static String date=DateTool.dateToString(new Date());
/**
* 获取网页授权凭证
* @param appId 公众号的唯一标识
* @param appSecret 公众号的密钥
* @param code
* @return
*/
public static WeixinOauth2TokenView getOauth2AccessToken(String appId,String appSecret,String code) throws Exception {
WeixinOauth2TokenView wat = null;
if(!date.equals(DateTool.dateToString(new Date()))) {
map.clear();
date=DateTool.dateToString(new Date());
}
if(map.get(code)==null || DateTool.getDistanceMinute(map.get(code).getDate(), new Date())>=(map.get(code).getExpiresIn()/60)) {
// 拼接请求地址
String requestUrl = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=APPID&secret=SECRET&code=CODE&grant_type=authorization_code";
requestUrl = requestUrl.replace("APPID", appId);
requestUrl = requestUrl.replace("SECRET", appSecret);
requestUrl = requestUrl.replace("CODE", code);
// 获取网页授权凭证
JSONObject jsonObject = CommonUtil.httpsRequest(requestUrl,"GET",null);
if (null != jsonObject) {
try {
wat = new WeixinOauth2TokenView();
wat.setAccessToken(jsonObject.getString("access_token"));
wat.setExpiresIn(jsonObject.getInt("expires_in"));
wat.setRefreshToken(jsonObject.getString("refresh_token"));
wat.setOpenId(jsonObject.getString("openid"));
wat.setScope(jsonObject.getString("scope"));
wat.setDate(new Date());
map.put(code, wat);
}
catch (Exception e) {
wat = null;
}
}
}
else {
wat=map.get(code);
}
return wat;
}
/**
* 刷新网页授权凭证
* @param appId
* @param refreshToken
* @return
*/
public static WeixinOauth2TokenView refreshOauth2AccessToken(String appId,String refreshToken) throws Exception {
WeixinOauth2TokenView wat = null;
//拼接请求地址
String requestUrl="https://api.weixin.qq.com/sns/oauth2/refresh_token?appid=APPID&grant_type=refresh_token&refresh_token=REFRESH_TOKEN";
requestUrl = requestUrl.replace("APPID", appId);
requestUrl = requestUrl.replace("REFRESH_TOKEN", refreshToken);
//刷新网页授权凭证
JSONObject jsonObject = CommonUtil.httpsRequest(requestUrl, "GET", null);
if(null != jsonObject){
try {
wat = new WeixinOauth2TokenView();
wat.setAccessToken(jsonObject.getString("access_token"));
wat.setExpiresIn(jsonObject.getInt("expires_in"));
wat.setRefreshToken(jsonObject.getString("refresh_token"));
wat.setOpenId(jsonObject.getString("openid"));
wat.setScope(jsonObject.getString("scope"));
} catch (Exception e) {
wat = null;
}
}
return wat;
}
/**
* 通过网页授权获取用户信息
* @param accessToken 网页授权接口调用凭证
* @param openId 用户标识
* @return
* @throws Exception
*/
public static BindWxUser getSNSUserInfo(String accessToken,String openId) throws Exception{
BindWxUser bindWxUser = null;
//拼接请求地址
String requestUrl="https://api.weixin.qq.com/sns/userinfo?access_token=ACCESS_TOKEN&openid=OPENID&lang=zh_CN";
requestUrl = requestUrl.replace("ACCESS_TOKEN", accessToken);
requestUrl = requestUrl.replace("OPENID", openId);
//通过网页授权获取用户信息
JSONObject jsonObject = CommonUtil.httpsRequest(requestUrl, "GET", null);
if(null != jsonObject){
try {
bindWxUser = new BindWxUser();
//用户标识
bindWxUser.setOpenid(jsonObject.getString("openid"));
//用户昵称
bindWxUser.setNickname(jsonObject.getString("nickname"));
//用户头像
bindWxUser.setHeadimgurl(jsonObject.getString("headimgurl"));
} catch (Exception e) {
bindWxUser=null;
}
}
return bindWxUser;
}
public static String urlEncodeUTF8(String source){
String result = source;
try {
result=java.net.URLEncoder.encode(source,"UTF-8");
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
public static void main(String args[]) throws Exception{
//String url = "http://1.text123456.sinaapp.com/oauthServlet";
//String url = "http://www.oohdear.com/m/m/AppraiseCommodityMobAction!getSNSUserInfo.action";
String url = "http://www.oohdear.com/m/m/AppraiseCommodityMobAction!weixinPay.action";
System.out.println(urlEncodeUTF8(url));
}
}
还有CommonUtil类
public class CommonUtil {
public static final String appId="";
public static final String appSecret="";
/**
* 发送https请求
*
* @param requestUrl 请求地址
* @param requestMethod 请求方式(get,post)
* @param outputStr 提交的数据
* @return
*/
public static JSONObject httpsRequest(String requestUrl,String requestMethod,String outputStr) throws Exception{
JSONObject jsonObject = null;
try {
//创建SSLContext 对象,并使用我们指定的信任管理器初始化
TrustManager[] tm = { new MyX509TrustManager()};
SSLContext sslContext = SSLContext.getInstance("SSL","SunJSSE");
sslContext.init(null, tm, new java.security.SecureRandom());
//从上述SSLContext对象中得到 SSLSocketFactory对象
SSLSocketFactory ssf = sslContext.getSocketFactory();
URL url = new URL(requestUrl);
HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
conn.setSSLSocketFactory(ssf);
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setUseCaches(false);
//设置请求方式(get/post)
conn.setRequestMethod(requestMethod);
//当outputStr 不为null时,向输出流写数据
if(null != outputStr){
OutputStream outputStream = conn.getOutputStream();
//注意编码格式
outputStream.write(outputStr.getBytes("UTF-8"));
outputStream.close();
}
//从输出流读取返回内容
InputStream inputStream = conn.getInputStream();
InputStreamReader inputStreamReader = new InputStreamReader(inputStream,"UTF-8");
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
String str = null;
StringBuffer buffer = new StringBuffer();
while((str = bufferedReader.readLine()) != null){
buffer.append(str);
}
//释放资源
bufferedReader.close();
inputStreamReader.close();
inputStream.close();
inputStream=null;
conn.disconnect();
jsonObject = JSONObject.fromObject(buffer.toString());
} catch (ConnectException ce) {
ce.printStackTrace();
}
return jsonObject;
}
}
还有 MyX509TrustManager
public class MyX509TrustManager implements X509TrustManager {
//检查客户端证书
public void checkClientTrusted(X509Certificate[] chain,String authType) throws CertificateException{
}
//检查服务器端证书
public void checkServerTrusted(X509Certificate[] chain,String authType) throws CertificateException{
}
//返回受信任的X509证书数组
public X509Certificate[] getAcceptedIssuers(){
return null;
}
}
还有一个时间类 这四个工具类
public class DateTool {
public DateTool() {
}
public static Date stringToDate(String date) {
try {
SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
return sdf.parse(date);
}
catch(Exception err) {
return null;
}
}
public static Date dateToDate(Date date) {
try {
SimpleDateFormat simpledate = new SimpleDateFormat("yyyy-MM-dd");
return simpledate.parse(simpledate.format(date));
}
catch(Exception err) {
return null;
}
}
public static Date stringToDateTime(String date) {
try {
SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm");
return sdf.parse(date);
}
catch(Exception err) {
return null;
}
}
public static String dateToString(Date date) {
SimpleDateFormat simpledate = new SimpleDateFormat("yyyy-MM-dd");
return simpledate.format(date);
}
public static String dateToStringTime(Date date) {
SimpleDateFormat simpledate = new SimpleDateFormat("yyyy-MM-dd HH:mm");
return simpledate.format(date);
}
public static int getYear() {
Calendar ca = Calendar.getInstance();
ca.setTime(new java.util.Date());
int year = ca.get(Calendar.YEAR);
return year;
}
public static int getYear(Date date) {
Calendar ca = Calendar.getInstance();
ca.setTime(date);
int year = ca.get(Calendar.YEAR);
return year;
}
public static int getMonth(Date date) {
Calendar ca = Calendar.getInstance();
ca.setTime(date);
int month = ca.get(Calendar.MONTH);
return month;
}
public static int getMonth() {
Calendar ca = Calendar.getInstance();
ca.setTime(new java.util.Date());
int month = ca.get(Calendar.MONTH);
return month;
}
public static int getDay() {
Calendar ca = Calendar.getInstance();
ca.setTime(new java.util.Date());
int day = ca.get(Calendar.DAY_OF_MONTH);
return day;
}
public static String dateToTimeString() {
SimpleDateFormat simpledate = new SimpleDateFormat("yyyyMMddHHmmss");
return simpledate.format(new java.util.Date());
}
public static String dateToTimeString(Date date) {
SimpleDateFormat simpledate = new SimpleDateFormat("yyyyMMddHHmmss");
return simpledate.format(date);
}
public static Date timeStringToDate(String dateTime) {
try {
SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
return sdf.parse(dateTime);
}
catch(Exception err) {
return null;
}
}
public static String getYearMonthDay(String dateFormateArg) {
String dateFormate=null;
Calendar ca = Calendar.getInstance();
if(dateFormateArg!=null && !"".equals(dateFormateArg)) {
dateFormate=dateFormateArg;
}
else {
dateFormate="yyyyMMdd";
}
ca.setTime(new java.util.Date());
SimpleDateFormat simpledate = new SimpleDateFormat(dateFormate);
String date = simpledate.format(ca.getTime());
return date;
}
/**
* 计算当前期加n年后的日期
*/
public static Date changeDate(Date date,int years) throws Exception {
Calendar c = Calendar.getInstance();
c.setTime(date);
c.add(Calendar.YEAR, years);
return c.getTime();
}
/**
* 计算两个时间间隔多少个月,date1为先前时间,date2为现在时间
*/
public static int getDistanceMonth(Date date1, Date date2) {
Calendar c1 = Calendar.getInstance();
Calendar c2 = Calendar.getInstance();
c1.setTime(date1);
c2.setTime(date2);
int year =c2.get(Calendar.YEAR)-c1.get(Calendar.YEAR);
return year*12+c2.get(Calendar.MONTH)-c1.get(Calendar.MONTH);
}
/**
* 计算两个时间间隔多少天,date1为先前时间,date2为现在时间。
*/
public static int getDistanceDay(Date date1,Date date2) {
int distanceDay=0;
if(date1!=null && date2!=null) {
Calendar ca1 = Calendar.getInstance();
Calendar ca2 = Calendar.getInstance();
ca1.setTime(date1);
ca2.setTime(date2);
int year1=ca1.get(Calendar.YEAR);
int year2=ca2.get(Calendar.YEAR);
if(year1!=year2) {
if((year2-year1)>=2) {
for(int i=year1+1;i<year2;i++) {
if(isLeapYear(i)) {
distanceDay=distanceDay+366;
}
else {
distanceDay=distanceDay+365;
}
}
}
if(isLeapYear(year1)) {
distanceDay=distanceDay+366-ca1.get(Calendar.DAY_OF_YEAR)+ca2.get(Calendar.DAY_OF_YEAR);
}
else {
distanceDay=distanceDay+365-ca1.get(Calendar.DAY_OF_YEAR)+ca2.get(Calendar.DAY_OF_YEAR);
}
}
else {
distanceDay = ca2.get(Calendar.DAY_OF_YEAR) - ca1.get(Calendar.DAY_OF_YEAR);
}
}
return distanceDay;
}
/**
* 计算两个时间间隔多少小时,date1为先前时间,date2为现在时间。
*/
public static int getDistanceHour(Date date1,Date date2) {
int distanceHour=0;
if(date1!=null && date2!=null) {
Calendar ca1 = Calendar.getInstance();
Calendar ca2 = Calendar.getInstance();
ca1.setTime(date1);
ca2.setTime(date2);
distanceHour = ca2.get(Calendar.HOUR_OF_DAY) - ca1.get(Calendar.HOUR_OF_DAY);
int year1=ca1.get(Calendar.YEAR);
int year2=ca2.get(Calendar.YEAR);
int distanceDay=0;
if(year1!=year2) {
if((year2-year1)>=2) {
for(int i=year1+1;i<year2;i++) {
if(isLeapYear(i)) {
distanceDay=distanceDay+366;
}
else {
distanceDay=distanceDay+365;
}
}
}
if(isLeapYear(year1)) {
distanceDay=distanceDay+366-ca1.get(Calendar.DAY_OF_YEAR)+ca2.get(Calendar.DAY_OF_YEAR);
}
else {
distanceDay=distanceDay+365-ca1.get(Calendar.DAY_OF_YEAR)+ca2.get(Calendar.DAY_OF_YEAR);
}
}
else {
distanceDay = ca2.get(Calendar.DAY_OF_YEAR) - ca1.get(Calendar.DAY_OF_YEAR);
}
distanceHour=distanceHour+distanceDay*24;
}
return distanceHour;
}
/**
* 计算两个时间间隔多少分钟,date1为先前时间,date2为现在时间。
*/
public static long getDistanceMinute(Date date1,Date date2) throws Exception {
SimpleDateFormat dfs = new SimpleDateFormat("yyyy-MM-dd HH:mm");
Date begin = dfs.parse(dateToStringTime(date1));
Date end = dfs.parse(dateToStringTime(date2));
long between = end.getTime() - begin.getTime(); /* 得到两者的毫秒数 */
between=(between/1000)/60;
return between;
}
/**
* 判断是否是闰年,闰年366天,非闰年365天
*/
public static boolean isLeapYear(int year) {
boolean isLeapYear = true;
if ((year % 4 == 0 && year % 100 != 0) || year % 400 == 0) {
isLeapYear = true;
}
else {
isLeapYear = false;
}
return isLeapYear;
}
/**
* 得到指定月的天数
*/
public static int getMonthLastDay(int year,int month) {
Calendar a = Calendar.getInstance();
a.set(Calendar.YEAR, year);
a.set(Calendar.MONTH, month - 1);
a.set(Calendar.DATE, 1);//把日期设置为当月第一天
a.roll(Calendar.DATE, -1);//日期回滚一天,也就是最后一天
int maxDate = a.get(Calendar.DATE);
return maxDate;
}
/**
* 计算几天后的日期
*/
public static Date getComputeDate(int days) {
Calendar ca = Calendar.getInstance();
ca.add(Calendar.DAY_OF_YEAR, days);
return ca.getTime();
}
/**
* 计算当天是星期几
*/
public static int getDayOfWeek(Date date) {
Calendar ca = Calendar.getInstance();
ca.setTime(date);
return ca.get(Calendar.DAY_OF_WEEK);
}
/**
* 比较两个日期的大小,date1大于date2返回true,date1小于date2返回false。
*/
public static boolean compareDate(Date date1,Date date2) {
if(date1.getTime()>=date2.getTime()) {
return true;
}
else {
return false;
}
}
方法直接可以调用 换上自己的公众号id就ok