java 微信小程序登錄


 微信登錄

 

開發前准備(必須)

  小程序標識(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 沒錯的話 這樣就百分百沒問題了!


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM