微信小程式-登入流程
流程圖:
1、首先,客戶端呼叫wx.login,回撥資料了包含jscode,用於獲取openid(使用者唯一標識)和sessionkey(會話金鑰)。
2、拿到jscode後,將其傳送給服務端,服務端拿它與微信服務端做互動獲取openid和sessionkey。具體獲取方法如下:
(1)需要寫一個HttpUrlConnection工具類:
?1234567891011121314151617181920212223242526272829303132333435363738394041424344 | public class MyHttpUrlConnection { private final int mTimeout = 10000 ; // 超時時間 /** * get訪問 */ public String[] requestJson(String url) { return request(url); } private String[] request(String connurl) { String[] resultStr = new String[]{ "" , "" }; StringBuilder resultData = new StringBuilder( "" ); HttpURLConnection conn = null ; try { URL url = new URL(connurl); conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod( "GET" ); conn.setUseCaches( false ); conn.setConnectTimeout(mTimeout); conn.connect(); int resultCode = conn.getResponseCode(); InputStreamReader in; if (resultCode == 200 ) { in = new InputStreamReader(conn.getInputStream()); BufferedReader buffer = new BufferedReader(in); String inputLine; while ((inputLine = buffer.readLine()) != null ) { resultData.append(inputLine); resultData.append( "\n" ); } buffer.close(); in.close(); } resultStr[ 0 ] = resultData.toString(); resultStr[ 1 ] = resultCode + "" ; } catch (Exception e) { e.printStackTrace(); } finally { if (conn != null ) { conn.disconnect(); } } return resultStr; } } |
(2)然後通過這個工具類與微信伺服器建立連線,獲取想要的資料:
?1234567 | + jsCode + "&grant_type=authorization_code" ; String res[] = connection.requestJson(url); System.out.println(res[ 0 ]); JSONObject object = JSON.parseObject(res[ 0 ]); String openId = object.getString( "openid"
|