JAvaは微信の許可を得てユーザー情報を取得する

9035 ワード

まず定数クラスを用意し、もちろんプロファイルにも書くことができます
/**
 * 
 *     :        
 * date: 2017-7-24 5:18:58
 * lk  */ public interface Constant { // (GET) public final static String TOKEN_URL = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=APPID&secret=SECRET&code=CODE&grant_type=authorization_code"; // , code public final static String WX_OAUTH_URL = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=APPID&redirect_uri=REDIRECT_URI&response_type=code&scope=SCOPE&state=STATE#wechat_redirect"; // , url public final static String WX_REDIRECT_URL = " url"; // url public final static String WX_SNSAPI_URL = "https://api.weixin.qq.com/sns/userinfo?access_token=ACCESS_TOKEN&openid=OPENID&lang=zh_CN"; // openId public final static String WX_OPEN_ID = " id"; // appSecret public final static String WX_APP_SECRET = "appSecret"; }
その後、いくつかのツールクラスが必要です.
/**
 * 
 *     :        
* date: 2017-7-24 5:18:58
* lk */ public class CommonMethod {     /**      *      *       * @param appid      * @param appsecret      * @return      */     public static Token getToken(String appid, String appsecret, String code) {         Token token = null;         String requestUrl = Constant.TOKEN_URL.replace("APPID", appid).replace("SECRET", appsecret).replace("CODE", code);         // GET         net.sf.json.JSONObject jsonObject = httpsRequest(requestUrl, "GET", null);         if (null != jsonObject) {             try {                 token = new Token();                 token.setAccessToken(jsonObject.getString("access_token"));                 token.setExpiresIn(jsonObject.getInt("expires_in"));                 token.setOpenId(jsonObject.getString("openid"));             } catch (JSONException e) {                 token = null;                 // token                 System.out.println(" token ");                 e.printStackTrace();                 //log.error(" token errcode:{} errmsg:{}", jsonObject.getInt("errcode"), jsonObject.getString("errmsg"));             }         }         return token;     }          /**      * URL (utf-8)      *       * @param source      * @return      */     public static String urlEncodeUTF8(String source) {         String result = source;         try {             result = java.net.URLEncoder.encode(source, "utf-8");         } catch (UnsupportedEncodingException e) {             e.printStackTrace();         }         return result;     } /**      * https      *       * @param requestUrl      * @param requestMethod (GET、POST)      * @param outputStr      * @return JSONObject( JSONObject.get(key) json )      */     public static net.sf.json.JSONObject httpsRequest(String requestUrl, String requestMethod, String outputStr) {     net.sf.json.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 = net.sf.json.JSONObject.fromObject(buffer.toString());         } catch (ConnectException ce) {         System.out.println(" :{}");         ce.printStackTrace();         } catch (Exception e) {         System.out.println("https :{}");         e.printStackTrace();         }         return jsonObject;     } }
Tokenクラス
public class Token {
	//       
    private String accessToken;
    //      ,  : 
    private int expiresIn;
    
    private String openId;

    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 getOpenId() {
		return openId;
	}

	public void setOpenId(String openId) {
		this.openId = openId;
	}
}
コールフローを以下に記す
最初のステップでcodeの取得を要求し、コード内で直接ジャンプしようとしたが成功せず、戻ったページを使用してページ内でジャンプすることにした.
	@RequestMapping("/index")
	public String home(HttpServletRequest request) {
		//         
		String requestUrl = Constant.WX_OAUTH_URL
				.replace("APPID", Constant.WX_OPEN_ID)
				.replace("REDIRECT_URI",
						CommonMethod.urlEncodeUTF8(Constant.WX_REDIRECT_URL))
				.replace("SCOPE", "snsapi_base").replace("STATE", "123");
		request.setAttribute("url", requestUrl);
		return "url";
	}
は現在、返されるjspコードです.
 
  
  
  	function redirectUrl(url){
  		window.location.href=url;
  	}
  
コールバックを受信するaction
	@RequestMapping("/showIndex")
	public String getIndex(HttpServletRequest request) {
		String code = request.getParameter("code");

		//   TOKEN
		Token accessToken = CommonMethod.getToken(Constant.WX_OPEN_ID,
				Constant.WX_APP_SECRET, code);
		if (!OAuth(request, accessToken.getAccessToken(),
				accessToken.getOpenId())) {
			//        			
			return "error";
		}		
		//        


}
public boolean OAuth(HttpServletRequest request, String accessToken,
String openId) {
TBaseMember member = null;
//接続要求先
String requestUrl = Constant.WX_SNSAPI_URL.replace("ACCESS_TOKEN",
accessToken).replace("OPENID", openId);
//ユーザー情報の取得
JSONObject jsonObject = CommonMethod.httpsRequest(requestUrl, "GET",
null);
if (null != jsonObject) {
try {
//Openidクエリによるユーザの有無の判断
TBaseMember tbm = memberService.selectMemberByOpenId(jsonObject
.getString("openid"));
if (null != tbm) {
request.getSession().setAttribute("member", tbm);
} else {
member = new TBaseMember();
member.setmId(AutoGenerationCode.getUUId());
member.setmState("01");
member.setIsValid("01");
member.setCreateDate(new Date());
member.setmOpenid(jsonObject.getString("openid"));
member.setExt2(jsonObject.getString("nickname"));
member.setmSex("0"+ jsonObject.getInt("sex"));
member.setExt1(jsonObject.getString("headimgurl"));
memberService.insertSelective(member);
request.getSession().setAttribute("member", member);
}
return true;
} catch (Exception e) {
e.printStackTrace();
/*
* if ("0".equals(member.getExt4())) {
*System.out.println(「ユーザー{}が注目されなくなった」);}else{int errorCode=
* jsonObject.getInt("errcode"); String errorMsg =
*jsonObject.getString(「errmsg」);System.out.println(「ユーザー情報の取得に失敗しました」
* + errorMsg); }
*/
return false;
}
}
return false;
}これでユーザー情報はデータベースとセッションに保存されます