微信企业号java,主页型应用的oauth2验证

来源:互联网 发布:淘宝仓库管理员累吗 编辑:程序博客网 时间:2024/05/21 10:16


一、在主页URL填写回调处理过的URL

/**
* 1、以snsapi_base为scope发起的网页授权,是用来获取进入页面的用户的openid的,并且是静默授权并自动跳转到回调页的。用户感知的就是直接进入了回调页(往往是业务页面)
* 2、以snsapi_userinfo为scope发起的网页授权,是用来获取用户的基本信息的。但这种授权需要用户手动同意,并且由于用户同意过,所以无须关注,就可在授权后获取该用户的基本信息。
*/
public static String GET_CODE = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=CORPID&redirect_uri=REDIRECT_URI&response_type=code&scope=snsapi_base&state=a123#wechat_redirect";
/**
* 企业获取code地址处理
* @param appid 企业的CorpID
* @param redirect_uri 授权后重定向的回调链接地址,请使用urlencode对链接进行处理
* @param response_type 返回类型,此时固定为:code
* @param scope 应用授权作用域,此时固定为:snsapi_base
* @param state 重定向后会带上state参数,企业可以填写a-zA-Z0-9的参数值
* @param #wechat_redirect 微信终端使用此参数判断是否需要带上身份信息
* 员工点击后,页面将跳转至 redirect_uri/?code=CODE&state=STATE,企业可根据code参数获得员工的userid
* */
public static String GetCode(){
String get_code_url = "";
get_code_url = GET_CODE.replace("CORPID", ParamesAPI.corpId).replace("REDIRECT_URI", WeixinUtil.URLEncoder(ParamesAPI.REDIRECT_URI));
return get_code_url;
}



       如图:              

        提示:    可以把回调的的state换成企业应用ID

二、得到access_token


/** 
     * 发起https请求并获取结果 
     *  
     * @param requestUrl 请求地址 
     * @param requestMethod 请求方式(GET、POST) 
     * @param outputStr 提交的数据 
     * @return JSONObject(通过JSONObject.get(key)的方式获取json对象的属性值) 
     */  
public static JSONObject HttpRequest(String request , String requestMethod , String output ){
JSONObject jsonObject = null;
StringBuffer buffer = new StringBuffer();
try {
//建立连接
URL url = new URL(request);
HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
TrustManager[] tm={new MyX509TrustManager()};
// 设置SSL客户端使用的协议
SSLContext sslContext=SSLContext.getInstance("SSL","SunJSSE");
sslContext.init(null, tm, new java.security.SecureRandom());
SSLSocketFactory sff = sslContext.getSocketFactory();
conn.setSSLSocketFactory(sff);
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setUseCaches(false);
conn.setRequestMethod(requestMethod);

if ("GET".equalsIgnoreCase(requestMethod)) { 
conn.connect();
}


if(output!=null){
OutputStream out = conn.getOutputStream();
out.write(output.getBytes("UTF-8"));
out.close();
}
//流处理
InputStream input = conn.getInputStream();
InputStreamReader inputReader = new InputStreamReader(input,"UTF-8");
BufferedReader reader = new BufferedReader(inputReader);
String line;
while((line=reader.readLine())!=null){
buffer.append(line);
}
//关闭连接、释放资源
reader.close();
inputReader.close();
input.close();
input = null;
conn.disconnect();
jsonObject = JSONObject.fromObject(buffer.toString());
} catch (Exception e) {
}
return jsonObject;

/**
*  获取access_token的接口地址(GET)   
*/
public final static String access_token_url = "https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=CorpID&corpsecret=SECRET";  
 
/** 
* 获取access_token 
*  
* @param CorpID 企业Id 
* @param SECRET 管理组的凭证密钥,每个secret代表了对应用、通讯录、接口的不同权限;不同的管理组拥有不同的secret 
* @return 
*/  
public static AccessToken getAccessToken(String corpID, String secret) {  
   AccessToken accessToken = null;  
 
   String requestUrl = access_token_url.replace("CorpID", corpID).replace("SECRET", secret);  
   JSONObject jsonObject = HttpRequest(requestUrl, "GET", null);  
   // 如果请求成功  
   if (null != jsonObject) {  
       try {  
           accessToken = new AccessToken();  
           accessToken.setToken(jsonObject.getString("access_token"));  
           accessToken.setExpiresIn(jsonObject.getInt("expires_in"));
           System.out.println("获取token成功:"+jsonObject.getString("access_token")+"————"+jsonObject.getInt("expires_in"));
       } catch (Exception e) {  
           accessToken = null;  
           // 获取token失败  
           String error = String.format("获取token失败 errcode:{} errmsg:{}", jsonObject.getInt("errcode"), jsonObject.getString("errmsg"));  
           System.out.println(error);
       }  
   }  
   return accessToken;  
}


三、根据get请求传过来的code获取user信息


public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
request.setCharacterEncoding("UTF-8");
response.setCharacterEncoding("UTF-8");
PrintWriter out = response.getWriter();
String code = request.getParameter("code");

               String agentid = request.getParameter("state");// Oauth2Manager.GET_CODE的state换成企业应用ID

             String userID =GetUserID (access_token,code ,agentid)


}



public static String CODE_TO_USERINFO = "https://qyapi.weixin.qq.com/cgi-bin/user/getuserinfo?access_token=ACCESS_TOKEN&code=CODE&agentid=AGENTID";

/**
* 根据code获取成员信息
* @param access_token 调用接口凭证
* @param code 通过员工授权获取到的code,每次员工授权带上的code将不一样,code只能使用一次,5分钟未被使用自动过期
* @param agentid 跳转链接时所在的企业应用ID
* 管理员须拥有agent的使用权限;agentid必须和跳转链接时所在的企业应用ID相同
* */
public static String GetUserID (String access_token,String code ,String agentid){
String UserId = "";
String requestUrl = "";
requestUrl = CODE_TO_USERINFO.replace("ACCESS_TOKEN", access_token).replace("CODE", code).replace("AGENTID", agentid);
JSONObject jsonobject = HttpRequest(requestUrl, "GET", null);

if(null!=jsonobject){
if(!jsonobject.containsKey("errcode")){
    UserId = jsonobject.getString("UserId");
}
if(!"".equals(UserId)){
System.out.println("获取信息成功,o(∩_∩)o ————UserID:"+UserId);
}else{
int errorrcode = jsonobject.getInt("errcode");  
           String errmsg = jsonobject.getString("errmsg");
           System.out.println("错误码:"+errorrcode+"————"+"错误信息:"+errmsg);
}
}else{
System.out.println("获取授权失败了,●﹏●,自己找原因。。。");
}
return UserId;
}

1 0
原创粉丝点击