WeChatアプリケーションを呼び出し、WeChat登録を行い、オプンID及びjavaをサービス端末の例として取得する。


一、WeChatアプレット
第1ステップ:code 文書の住所を取得するためにwx.loginを呼び出します。
ステップ2:ユーザがユーザ情報の読み取りを許可しているかどうかを判断する文書の住所
第3ステップ:wx.getUserInfoを呼び出してユーザデータを読み出す文書の住所
第4ステップ:小さいプログラムのバックグランドがドメイン名を授権してWeChatのドメイン名を授権することができないため、私達は私達自身のサーバーを通じて(通って)WeChatサーバーを呼び出してユーザー情報を獲得することしかできなくて、だから私達はwx.loginをcodeとwx.getUserInfoの獲得したencryptとivをwx.requestを通じてバックグラウンドに入ることを要求します。

サーバから返されたデータ:

プログラムコード:

//      ,   code 
wx.login({ 
 success: function (res) { 
  wx.getSetting({ 
   success(setRes) { 
    //         
    if (!setRes.authSetting['scope.userInfo']) { 
     //      
     wx.authorize({ 
      scope: 'scope.userInfo', 
      success() { 
       //       
       wx.getUserInfo({ 
        lang: "zh_CN", 
        success: function (userRes) { 
         //       
         wx.request({ 
          url: config.loginWXUrl, 
          data: { 
           code: res.code, 
           encryptedData: userRes.encryptedData, 
           iv: userRes.iv 
          }, 
          header: { 
           "Content-Type": "application/x-www-form-urlencoded" 
          }, 
          method: 'POST', 
          //       
          success: function (result) { 
           var data = result.data.result; 
           data.expireTime = nowDate + EXPIRETIME; 
           wx.setStorageSync("userInfo", data); 
           userInfo = data; 
          } 
         }) 
        } 
       }) 
      } 
     }) 
    } else { 
     //       
     wx.getUserInfo({ 
      lang: "zh_CN", 
      success: function (userRes) { 
       //       
       wx.request({ 
        url: config.loginWXUrl, 
        data: { 
         code: res.code, 
         encryptedData: userRes.encryptedData, 
         iv: userRes.iv 
        }, 
        header: { 
         "Content-Type": "application/x-www-form-urlencoded" 
        }, 
        method: 'POST', 
        success: function (result) { 
         var data = result.data.result; 
         data.expireTime = nowDate + EXPIRETIME; 
         wx.setStorageSync("userInfo", data); 
         userInfo = data; 
        } 
       }) 
      } 
     }) 
    } 
   } 
  }) 
 } 
}) 

二、javaサーバー
codeからopenidを取得して、ユーザー情報コードを復号します。
必要なjarバッグ

<dependency> 
  <groupId>org.codehaus.xfire</groupId> 
  <artifactId>xfire-core</artifactId> 
  <version>1.2.6</version> 
</dependency> 
<dependency> 
  <groupId>org.bouncycastle</groupId> 
  <artifactId>bcprov-jdk16</artifactId> 
  <version>1.46</version> 
</dependency> 

/** 
 *           
 * 
 * @author zhy 
 */ 
public class WXAppletUserInfo { 
  private static Logger log = Logger.getLogger(WXAppletUserInfo.class); 
   
  /** 
   *         session_key   openid 
   * 
   * @author zhy 
   * @param code          Code 
   * @return 
   */ 
  public static JSONObject getSessionKeyOropenid(String code){ 
    //     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   code 
    requestUrlParam.put("grant_type", "authorization_code");  //     
     
    //  post         https://api.weixin.qq.com/sns/jscode2session     openid       
    JSONObject jsonObject = JSON.parseObject(UrlUtil.sendPost(requestUrl, requestUrlParam)); 
    return jsonObject; 
  } 
   
  /** 
   *                
   * 
   * @author zhy 
   * @param sessionKey             
   * @param encryptedData                      
   * @param iv           
   * @return 
   */ 
  public static JSONObject getUserInfo(String encryptedData,String sessionKey,String iv){ 
    //        
    byte[] dataByte = Base64.decode(encryptedData); 
    //      
    byte[] keyByte = Base64.decode(sessionKey); 
    //     
    byte[] ivByte = Base64.decode(iv); 
    try { 
        //       16 ,     .   if         
      int base = 16; 
      if (keyByte.length % base != 0) { 
        int groups = keyByte.length / base + (keyByte.length % base != 0 ? 1 : 0); 
        byte[] temp = new byte[groups * base]; 
        Arrays.fill(temp, (byte) 0); 
        System.arraycopy(keyByte, 0, temp, 0, keyByte.length); 
        keyByte = temp; 
      } 
      //     
      Security.addProvider(new BouncyCastleProvider()); 
      Cipher cipher = Cipher.getInstance("AES/CBC/PKCS7Padding","BC"); 
      SecretKeySpec spec = new SecretKeySpec(keyByte, "AES"); 
      AlgorithmParameters parameters = AlgorithmParameters.getInstance("AES"); 
      parameters.init(new IvParameterSpec(ivByte)); 
      cipher.init(Cipher.DECRYPT_MODE, spec, parameters);//     
      byte[] resultByte = cipher.doFinal(dataByte); 
      if (null != resultByte && resultByte.length > 0) { 
        String result = new String(resultByte, "UTF-8"); 
        return JSON.parseObject(result); 
      } 
    } 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 (IllegalBlockSizeException e) { 
      log.error(e.getMessage(), e); 
    } catch (BadPaddingException 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   POST      
* 
* @param url       URL 
* @param param      
* @return              
*/ 
ublic static String sendPost(String url, Map<String, ?> paramMap) { 
   PrintWriter out = null; 
   BufferedReader in = null; 
   String result = ""; 
    
   String 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); 
     //    URL      
     URLConnection conn = realUrl.openConnection(); 
     //           
     conn.setRequestProperty("accept", "*/*"); 
     conn.setRequestProperty("connection", "Keep-Alive"); 
     conn.setRequestProperty("Accept-Charset", "utf-8"); 
     conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)"); 
     //   POST           
     conn.setDoOutput(true); 
     conn.setDoInput(true); 
     //   URLConnection         
     out = new PrintWriter(conn.getOutputStream()); 
     //        
     out.print(param); 
     // flush       
     out.flush(); 
     //   BufferedReader      URL    
     in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8")); 
     String line; 
     while ((line = in.readLine()) != null) { 
       result += line; 
     } 
   } catch (Exception e) { 
    log.error(e.getMessage(), e); 
   } 
   //  finally       、    
   finally{ 
     try{ 
       if(out!=null){ 
         out.close(); 
       } 
       if(in!=null){ 
         in.close(); 
       } 
     } 
     catch(IOException ex){ 
       ex.printStackTrace(); 
     } 
   } 
   return result; 
 } 
以上が本文の全部です。皆さんの勉強に役に立つように、私たちを応援してください。