微信登录
开发前准备(必须)
小程序标识(appid):wx4d4838ebec29b8**
小程序秘钥(secret):4fd6ca38a1261f96cbc0314c5675b9**
登录微信官网 : https://developers.weixin.qq.com/miniprogram/dev/api-backend/open-api/login/auth.code2Session.html
根据官方文档
java 登录接口
//前端传给你的code
public void wxlogin(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 static JSONObject 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());
}
return jsonObject;
}
private static StringBuffer httpsRequest(String requestUrl, String requestMethod, String output)
throws NoSuchAlgorithmException, NoSuchProviderException, KeyManagementException, MalformedURLException,
IOException, ProtocolException, UnsupportedEncodingException {
URL url = new URL(null, requestUrl, new Handler());
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 = 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;
connection.disconnect();
return buffer;
}
如果 appid 和secret 没错的话 这样就百分百没问题了!
来源:oschina
链接:https://my.oschina.net/u/4408924/blog/3409217