1. WeChat 애플릿 <BR /> 1 단계 : WX.LOGIN에 전화하여 코드 문서 주소를 얻으려면 2 단계 : 사용자가 사용자 정보 문서 주소를 읽을 수있는 권한을 결정합니다. 3 단계 : 사용자 데이터 문서 주소를 읽으려면 WX.GETUSERINFO에 전화하십시오. 4 단계 : WECHAT 도메인 이름을 통해 WeChat 서버를 통해 WeChat 서버를 통화 할 수 없으므로 WeChat 서버 만 호출 할 수 있습니다. 따라서 WX.Login에서 얻은 암호화 된 데이터 및 IV를 전달하여 WX.Request 요청을 통해 코드와 wx.getuserinfo를 얻습니다.
서버에서 반환 한 데이터 :
미니 프로그램 코드 :
// 코드를 가져 오려면 로그인 인터페이스를 호출하여 wx.login ({success (res) {wx.getSetting ({setres)) {// 인증 된 if (! setres.authsetting [ 'scope.userinfo'])) {// wx.authorize ({scope.userin., ', get superation) wx.getuserinfo ({lang : "zh_cn", success : function (userres) {// 스택 네트워크 요청 wx.request ({url : config.loginwxurl, data : {code : res.code, acrypteddata : userres.encrypteddata, iv : userres.iv}, { "" "" ": "Application/x-form-urlencoded", 'post', // server-side 검색 성공 : var data = data.xpiretime; // 사용자 정보 가져 오기 wx.getUserInfo ({lang : "zh_cn", success : function (userres) {// 스택 네트워크 요청 wx.request ({url : config.loginwxurl, data : {Code : res.code, ancrypteddata : userres.encryptedData, IV : userres.iv} "Content-Type". }}})}}))) 2. Java 서버
Code에 따라 OpenID를 얻고 사용자 정보 코드를 디코딩합니다.
필요한 JAR 패키지
<pectionency> <groupid> org.codehaus.xfire </groupid> <artifactid> xfire-core </artifactid> <bersion> 1.2.6 </version> </depectency> <prectionency> <groupid> org.bouncycastle </groupid> <artifactid> bcprov-jdk16 </artifactid> <46 </버전> </6> 1.46
/ ** * wechat 애플릿 정보 받기 * @author zhy */ public class wxappletuserinfo {private static logger log = logger.getLogger (wxappletuserinfo.class); /** * wechat appret session_key 및 openID를 얻으십시오 * @Author Zhy * @param 코드 호출 wechat login * @return */public static jsonobject getsessionkeyOropenid (String Code) {// wechat 로그인 Code String wxcode = code; ResourceBundle Resource = ResourceBundle.getBundle ( "weixin"); // 속성 파일을 읽습니다. string requestUrl = resource.getString ( "url"); // 주소 요청 https://api.weixin.qq.com/sns/jscode2session map <string, String> requesturlparam = new Hashmap <String, String> (); requestUrlParam.put ( "appid", resource.getString ( "appid")); // 개발자 설정에서 Appid requestUrlParam.put ( "Secret", Resource.GetString ( "AppSecret")); // AppSecret requestUrlParam.put ( "js_code", wxcode); // 애플릿으로 반환 된 코드 wx.login requestUrlparam.put ( "grant_type", "userization_code"); // 기본 매개 변수 // WeChat https://api.weixin.qq.com/sns/jscode2session interface를 읽고 전화하려면 게시물 요청을 보내십시오. jsonobject를 반환합니다. } / *** 사용자 정보를 얻기위한 사용자 민감한 데이터를 해독 할 수 있습니다.* @author zhy* @param sessionkey 민감한 데이터를 포함하여 암호화 된 데이터의 암호화 된 서명에 대한 키* @param iv @param iv 암호화 알고리즘* / public jsonobject getusinfo의 초기 벡터 (string tata, etcryptedata, etcrypted getusinfo). iv) {// 암호화 된 데이터 바이트 [] databyte = base64.decode (encryptedData); // 암호화 된 키 바이트 [] keyByte = base64.decode (sessionKey); // 바이트 오프셋 [] ivbyte = base64.decode (iv); {// 키가 16 비트 미만인 경우 시도하십시오. 이것의 내용은 매우 중요한 int base = 16입니다. if (keybyte.length % base! = 0) {int groups = keybyte.length / base + (keybyte.length % base! = 0? 1 : 0); 바이트 [] temp = 새로운 바이트 [그룹 *베이스]; 배열 .fill (temp, (byte) 0); System.ArrayCopy (KeyByte, 0, Temp, 0, KeyByte.length); KeyByte = 임시; } // security를 초기화합니다. AddProvider (New BouncycastleProvider ()); Cipher Cipher = Cipher.getInstance ( "AES/CBC/PKCS7PADDING", "BC"); Secretkeyspec Spec = New SecretKeyspec (KeyByte, "AES"); AlgorithmParameters 매개 변수 = AlgorithMparameters.getInstance ( "AES"); PARAMETERS.INIT (New IVParameterspec (ivbyte)); cipher.init (cipher.decrypt_mode, spec, parameters); // byte 초기화 [] resultbyte = cipher.dofinal (databyte); if (null! = resultBeyte && resultByte.length> 0) {문자열 result = new String (resultByte, "utf-8"); json.parseobject (결과)를 반환합니다. }} catch (nosuchalgorithmexception e) {log.error (e.getMessage (), e); } catch (nosuchPaddingException e) {log.error (e.getMessage (), e); } catch (invalidParameterspecexception e) {log.error (e.getMessage (), e); } catch (delegalBlocksizeexception e) {log.error (e.getMessage (), e); } catch (badpaddingException e) {log.error (e.getMessage (), e); } catch (UnSupportedEncodingException e) {log.error (e.getMessage (), e); } catch (UnSupportedEncodingException e) {log.error (e.getMessage (), e); } catch (invalidkeyException e) {log.error (e.getMessage (), e); } catch (invalidalgorithmparameterexception e) {log.error (e.getMessage (), e); } catch (nosuchproviderexception e) {log.error (e.getMessage (), e); } return null; }} 요청을 보내려면 코드
/ *** 포스트 메소드에 대한 지정된 URL에 요청을 보내십시오* @param url 요청을 보내기위한 URL* @param param request 매개 변수* @return 이름*/ ublic static String sendPost (문자열 URL, map <String,?> Parammap) {printWriter out = null; 버퍼드 리더 in = null; 문자열 결과 = ""; 문자열 param = ""; iterator <string> it = parammap.keyset (). iterator (); while (it.hasnext ()) {String key = it.next (); param + = key + "=" + parammap.get (key) + "&"; } try {url realurl = new URL (url); // urlConnection 사이의 연결을 엽니 다. conn = realurl.openConnection (); // 일반 요청 속성을 설정하여 Conn.setRequestProperty ( "accept", "*/*"); Conn.setRequestProperty ( "Connection", "Keep-Alive"); Conn.setRequestProperty ( "허락-차 세트", "UTF-8"); Conn.setRequestProperty ( "사용자 에이전트", "Mozilla/4.0 (호환 가능; MSIE 6.0; Windows NT 5.1; Sv1)"); // 게시물 요청을 보내려면 다음 두 줄을 설정해야합니다. conn.setDoOutput (true); conn.setdoinput (true); // urlConnection 객체에 해당하는 출력 스트림을 가져옵니다. // 요청 매개 변수를 보내십시오 .print (param); // 플러시 출력 스트림의 Flush (); // bufferedReader Input Stream을 정의하여 = new bufferedReader에서 URL 응답을 읽습니다 (new inputStreamReader (conn.getInputStream (), "utf-8")); 문자열 라인; while ((line = in.readline ())! = null) {result += line; }} catch (예외 e) {log.error (e.getMessage (), e); } // 마침내 블록을 사용하여 출력 스트림과 입력 스트림을 닫습니다. 마지막으로 {try {if (out! = null) {out.close (); } if (in! = null) {in.close (); }} catch (ioexception ex) {ex.printstacktrace (); }} 반환 결과; }위는이 기사의 모든 내용입니다. 모든 사람의 학습에 도움이되기를 바랍니다. 모든 사람이 wulin.com을 더 지원하기를 바랍니다.