首先,页面内容
参数官方API说的很清楚了,我就不重复阐述。
参数填正确后打开这个页面会显示一个二维码
接下来用微信扫码,确定授权后这个页面会自动跳转到redirect_uri?code=xxx&state=xxxx
然后你就获得了关键的东西之一code!
接下来需要你用appId(开放平台申请的网站应用id)、appSecret(密匙)、code这三个参数去获取AccessToken
我的代码贴上
/**
* 获取授权凭证
*
* @param appId 公众账号的唯一标识
* @param appSecret 公众账号的密钥
* @param code
* @return Token
*/
public static getAccessToken(String appId, String appSecret, String code) {
WeixinOauth2Token wat = null;
// 拼接请求地址
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 = HttpLink.httpsRequest(requestUrl, "GET", null,"https");
if (null != jsonObject) {
try {
wat = new WeixinOauth2Token();
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;
int errorCode = jsonObject.getInt("errcode");
String errorMsg = jsonObject.getString("errmsg");
log.error("获取凭证失败 errcode:{} errmsg:{}", errorCode, errorMsg);
}
}
return wat;
}
贴上工具类httplink
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.ConnectException;
import java.net.HttpURLConnection;
import java.net.URL;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import net.sf.json.JSONException;
import net.sf.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* 通用工具类
*/
public class HttpLink {
private static Logger log = LoggerFactory.getLogger(HttpLink.class);
// 凭证获取(GET)
public final static String token_url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET";
/**
* 发送http、https请求
*
* @param requestUrl 请求地址
* @param requestMethod 请求方式(GET、POST)
* @param outputStr 提交的数据
* @param linkType http、https
* @return JSONObject(通过JSONObject.get(key)的方式获取json对象的属性值
*/
public static JSONObject httpsRequest(String requestUrl, String requestMethod, String outputStr,String linkType) {
JSONObject jsonObject = null;
try {
if("https".equals(linkType)){
// 创建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);
jsonObject = closeLink(null,conn,outputStr);
}
else{
URL url = new URL(requestUrl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
if(requestMethod.endsWith("GET")){
conn.setDoInput(true);
}
else{
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setUseCaches(false);
}
conn.setRequestMethod(requestMethod);
jsonObject = closeLink(conn,null,outputStr);
}
} catch (ConnectException ce) {
log.error("连接超时:{}", ce);
} catch (Exception e) {
log.error("https请求异常:{}", e);
}
return jsonObject;
}
/**
* 返回结果 释放资源
* @param conn
* @param conns
* @return
*/
public static JSONObject closeLink(HttpURLConnection conn,HttpsURLConnection conns,String ots){
try {
// 当ots不为null时向输出流写数据
if (null != ots) {
OutputStream outputStream=null;
if(conn!=null){
outputStream=conn.getOutputStream();
}
else{
outputStream=conns.getOutputStream();
}
// 设置编码格式
outputStream.write(ots.getBytes("UTF-8"));
outputStream.close();
}
JSONObject jsonObject = null;
// 从输入流读取返回内容
InputStream inputStream = conn==null?conns.getInputStream():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;
if(conn!=null){
conn.disconnect();
}
else{
conns.disconnect();
}
jsonObject = JSONObject.fromObject(buffer.toString());
return jsonObject;
} catch (Exception e) {
return null;
}
}
}
还需要一个信任管理器,这里置为空就好,jre目录\lib\security里面自带信任好了的ssl证书不用管。
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import javax.net.ssl.X509TrustManager;
/**
* 信任管理器
*/
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;
}
}
WeixinAgentToken实体
/**
* accessToken实体
*/
public class WeixinAgentToken {
// 网页授权接口调用凭证
private String accessToken;
// 凭证有效时长
private int expiresIn;
// 用于刷新凭证
private String refreshToken;
// 用户标识
private String openId;
// 用户授权作用域
private String scope;
public String getAccessToken() {
return accessToken;
}
public void setAccessToken(String accessToken) {
this.accessToken = accessToken;
}
public int getExpiresIn() {
return expiresIn;
}
public void setExpiresIn(int expiresIn) {
this.expiresIn = expiresIn;
}
public String getRefreshToken() {
return refreshToken;
}
public void setRefreshToken(String refreshToken) {
this.refreshToken = refreshToken;
}
public String getOpenId() {
return openId;
}
public void setOpenId(String openId) {
this.openId = openId;
}
public String getScope() {
return scope;
}
public void setScope(String scope) {
this.scope = scope;
}
}
接下来调用getAccessToken这个方法就可以了,这时候你可以从返回的实体拿到AccessToken以及openid,下一步开始。
调用下面这个方法
/**
* 开发平台获取用户信息
*
* @param accessToken 接口访问凭证
* @param openId 用户标识
* @return WeixinUserInfo
*/
public static WeixinUserInfo getAgentWxUserInfo(String accessToken, String openId) {
WeixinUserInfo weixinUserInfo = null;
// 拼接请求地址
String requestUrl = "https://api.weixin.qq.com/sns/userinfo?access_token=ACCESS_TOKEN&openid=OPENID";
requestUrl = requestUrl.replace("ACCESS_TOKEN", accessToken).replace("OPENID", openId);
// 获取用户信息
JSONObject jsonObject = HttpLink.httpsRequest(requestUrl, "GET", null,"https");
if (null != jsonObject) {
try {
weixinUserInfo = new WeixinUserInfo();
// 用户的标识
weixinUserInfo.setOpenId(jsonObject.getString("openid"));
// 昵称
weixinUserInfo.setNickname(jsonObject.getString("nickname"));
// 用户的性别(1是男性,2是女性,0是未知)
weixinUserInfo.setSex(jsonObject.getInt("sex"));
// 用户所在国家
weixinUserInfo.setCountry(jsonObject.getString("country"));
// 用户所在省份
weixinUserInfo.setProvince(jsonObject.getString("province"));
// 用户所在城市
weixinUserInfo.setCity(jsonObject.getString("city"));
// 用户的语言,简体中文为zh_CN
weixinUserInfo.setLanguage(jsonObject.getString("language"));
// 用户头像
weixinUserInfo.setHeadImgUrl(jsonObject.getString("headimgurl"));
//开发平台统一unionid
weixinUserInfo.setUnionid(jsonObject.getString("unionid"));
} catch (Exception e) {
log.error("开放平台获取用户信息失败errmsg:{}", e.getMessage());
}
}
return weixinUserInfo;
}
贴上实体
/**
* 微信用户的基本信息
*/
public class WeixinUserInfo {
// 用户的标识
private String openId;
// 关注状态(1是关注,0是未关注),未关注时获取不到其余信息
private int subscribe;
// 用户关注时间,为时间戳。如果用户曾多次关注,则取最后关注时间
private String subscribeTime;
// 昵称
private String nickname;
// 用户的性别(1是男性,2是女性,0是未知)
private int sex;
// 用户所在国家
private String country;
// 用户所在省份
private String province;
// 用户所在城市
private String city;
// 用户的语言,简体中文为zh_CN
private String language;
// 用户头像
private String headImgUrl;
//unionid
private String unionid;
public String getOpenId() {
return openId;
}
public void setOpenId(String openId) {
this.openId = openId;
}
public int getSubscribe() {
return subscribe;
}
public void setSubscribe(int subscribe) {
this.subscribe = subscribe;
}
public String getSubscribeTime() {
return subscribeTime;
}
public void setSubscribeTime(String subscribeTime) {
this.subscribeTime = subscribeTime;
}
public String getNickname() {
return nickname;
}
public void setNickname(String nickname) {
this.nickname = nickname;
}
public int getSex() {
return sex;
}
public void setSex(int sex) {
this.sex = sex;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
public String getProvince() {
return province;
}
public void setProvince(String province) {
this.province = province;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getLanguage() {
return language;
}
public void setLanguage(String language) {
this.language = language;
}
public String getHeadImgUrl() {
return headImgUrl;
}
public void setHeadImgUrl(String headImgUrl) {
this.headImgUrl = headImgUrl;
}
public String getUnionid() {
return unionid;
}
public void setUnionid(String unionid) {
this.unionid = unionid;
}
}
好了,用户信息获取完毕。接下来该做啥做啥。