java 实现微信公众号扫码授权注册登录
第一次实现这个功能,查了资料API还有很多资料才实现的。真是痛苦呀!
希望可以帮到需要的得到帮助的小伙伴!!!
现在正是开始。
第一步:在pom.xml 文件中引jar包
<dependency>
<groupId>commons-httpclient</groupId>
<artifactId>commons-httpclient</artifactId>
<version>3.1</version>
</dependency>
第二步:jar包依赖添加完后,我们直接上代码:
第一个类是工具类
package com.ytrj.utils;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.util.StringUtil;
import com.ytrj.config.db.RedisUtil;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import java.net.URLEncoder;
import java.security.MessageDigest;
import java.util.Formatter;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
/**
* User: Administrator
* Date: 14-8-31
* Time: 下午2:16
*/
public class WxHelper {
private Log logger = LogFactory.getLog(WxHelper.class);
private ExecutorService executor = Executors.newFixedThreadPool(10);
private final char[] HEX_DIGITS = {'0', '1', '2', '3', '4', '5',
'6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
private String wxAppId;
private String wxAppSecret;
private static Map<String, WxHelper> map = new HashMap<String, WxHelper>();
private static WxHelper instance;
private RedisUtil redisUtil;
private WxHelper(String wxAppId, String wxAppSecret, RedisUtil redisUtil) {
this.wxAppId = wxAppId;
this.wxAppSecret = wxAppSecret;
this.redisUtil = redisUtil;
}
public static WxHelper getInstance(String wxAppId, String wxAppSecret,RedisUtil redisUtil) {
if (instance == null) {
instance = new WxHelper(wxAppId,wxAppSecret,redisUtil);
}
return instance;
}
/**
* 网页授权后拉取用户信息,使用授权后给与的Access_Token
*
* @param openid
* @return
*/
public JSONObject getWxUserInfoByOauth(String openid, String oauth2_access_token) {
try {
if (oauth2_access_token != null) {
String url = "https://api.weixin.qq.com/sns/userinfo?" +
"access_token=" + oauth2_access_token + "&openid=" + openid + "&lang=zh_CN";
logger.info(url);
JSONObject jsonObject = new JSONObject(HttpClientUtils.httpGet(url));
logger.info(jsonObject);
return jsonObject;
}
return null;
} catch (Exception e) {
logger.error("", e);
}
return null;
}
public JSONObject getWxUserInfoByOpenId(String openid,String accessToken) {
try {
if (getToken() != null) {
String url = "https://api.weixin.qq.com/sns/userinfo?" +
"access_token=" + accessToken + "&openid=" + openid + "&lang=zh_CN";
logger.info(url);
JSONObject jsonObject = new JSONObject(HttpClientUtils.httpGet(url));
logger.info(jsonObject);
if (StringUtil.isNotEmpty(jsonObject.getString("errcode"))
&&
("40001".equals(jsonObject.getString("errcode"))
||
"40014".equals(jsonObject.getString("errcode"))
||
"42001".equals(jsonObject.getString("errcode")))
) {
resetToken();
}
return jsonObject;
}
} catch (Exception e) {
logger.error("", e);
}
return null;
}
public String[] getOpenIdByCode(String code) {
try {
String url = "https://api.weixin.qq.com/sns/oauth2/access_token?" +
"appid=" + wxAppId +