该经验适用于网页程序的开发,且针对企业号!
一、获取code
1、官方url:https://open.weixin.qq.com/connect/oauth2/authorize?appid={0}&redirect_uri={1}&response_type=code&scope=snsapi_base&state={2}#wechat_redirect
2、代码判断:
String code = request.getParameter("code");
if (StringUtils.isBlank(code)) {
String redirectUri = HttpRequest.getAuthorizeCode("appid", "http://***/***, "state");
response.sendRedirect(redirectUri);
} else if (StringUtils.isNotBlank(code) && "AUTHORITY".equals(code)) {
// 真正的业务处理
}
public String getAuthorizeCode(Object... arguments) {
return MessageFormat.format(redirectURL, arguments);
}
二、根据code获取用户的userid与deviceid
1、官方url:https://qyapi.weixin.qq.com/cgi-bin/user/getuserinfo?access_token={0}&code={1}&agentid={2},agentid=企业号中的应用id
三、GET请求的代码:
public static String httpsGet(String requestURL, String charset) {
HttpsURLConnection connection = null;
try {
TrustManager [] tms = { new MyTrustManager() };
SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");
sslContext.init(null, tms, new SecureRandom());
SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();
URL url = new URL(requestURL);
connection = (HttpsURLConnection) url.openConnection();
connection.setSSLSocketFactory(sslSocketFactory);
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setUseCaches(false);
connection.setRequestMethod("GET");
connection.connect();
String respStr = getResponseContent(connection.getInputStream(), charset);
return respStr;
} catch (Exception e) {
e.printStackTrace();
return null;
} finally {
if (connection != null) {
connection.disconnect();
}
}
}
private static class MyTrustManager implements X509TrustManager {
@Override
public void checkClientTrusted(X509Certificate[] xcs, String string) throws CertificateException {
}
@Override
public void checkServerTrusted(X509Certificate[] xcs, String string) throws CertificateException {
}
@Override
public X509Certificate[] getAcceptedIssuers() {
return null;
}
}