//前端传给你的code
public voidwxlogin(String code) {//填写你小程序的appid 和 secret , 还有前端传给你的code ,最后一个参数是固定的
String token_url= "https://api.weixin.qq.com/sns/jscode2session?appid=" +WxConfig.APP_ID + "&secret=" + WxConfig.SECRET + "&js_code=" + code + "&grant_type=authorization_code";
JSONObject access_token= httpsRequestToJsonObject(token_url, "GET", null);//openid string 用户唯一标识 这个就是你微信用户标识
String openid = access_token.getString("openid");//session_key string 会话密钥
String session_key = access_token.getString("session_key");//errcode number 错误码
String errcode = access_token.getString("errcode");//errmsg string 错误信息
String errmsg = access_token.getString("errmsg");if ("-1".equals(errcode)) {
System.err.println(errmsg);return;
}if ("4029".equals(errcode)) {
System.err.println(errmsg);return;
}if ("45011".equals(errcode)) {
System.err.println(errmsg);return;
}else{//证明没问题//保存openid 到你的数据库, 调用你的service 业务
}
}public staticJSONObject httpsRequestToJsonObject(String requestUrl, String requestMethod, String outputStr) {
JSONObject jsonObject= null;try{
StringBuffer buffer=httpsRequest(requestUrl, requestMethod, outputStr);
jsonObject=JSONObject.fromObject(buffer.toString());
}catch(ConnectException ce) {
System.err.println("请求连接超时"+ce);
}catch(Exception e) {
System.err.println("https请求异常:" +e.getMessage());
}returnjsonObject;
}private staticStringBuffer httpsRequest(String requestUrl, String requestMethod, String output)throwsNoSuchAlgorithmException, NoSuchProviderException, KeyManagementException, MalformedURLException,
IOException, ProtocolException, UnsupportedEncodingException {
URL url= new URL(null, requestUrl, newHandler());
HttpsURLConnection connection=(HttpsURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setUseCaches(false);
connection.setRequestMethod(requestMethod);if (null !=output) {
OutputStream outputStream=connection.getOutputStream();
outputStream.write(output.getBytes("UTF-8"));
outputStream.close();
}//从输入流读取返回内容
InputStream inputStream =connection.getInputStream();
InputStreamReader inputStreamReader= new InputStreamReader(inputStream, "utf-8");
BufferedReader bufferedReader= newBufferedReader(inputStreamReader);
String str= null;
StringBuffer buffer= newStringBuffer();while ((str = bufferedReader.readLine()) != null) {
buffer.append(str);
}
bufferedReader.close();
inputStreamReader.close();
inputStream.close();
inputStream= null;
connection.disconnect();returnbuffer;
}