微信小程序(获取open_id工具类)

最近公司要开发小程序,由于业务需要,需要在用户注册时获取用户的openId作为userId进行注册

一、获取code

将code作为参数传递过来

//如果有code,说明是微信小程序,根据code获取openId
//classify用于标识是哪个小程序
            if (!CheckUtil.checkNulls( keUser.getCode(),keUser.getClassify())){
                //
                String openid = OpenIdUtil.oauth2GetOpenid(keUser.getCode(),keUser.getClassify());
                printParamsLog(openid, logger);
                keUser.setUserId(openid);
            }
   
   
  • 二、工具类

    package com.util;
    
    import net.sf.json.JSONObject;
    import org.apache.http.client.HttpClient;
    import org.apache.http.client.ResponseHandler;
    import org.apache.http.client.methods.HttpGet;
    import org.apache.http.impl.client.BasicResponseHandler;
    import org.apache.http.impl.client.DefaultHttpClient;
    
    import java.util.HashMap;
    import java.util.Map;
    
    /**
     * @author xsx
     */
    public class OpenIdUtil {
        public static String oauth2GetOpenid(String code,String classify) {
            String appid="";
            String appsecret="";
            switch (classify){
                case "1":
                    //自己的配置appid
                    appid = "**********";
                    //自己的配置APPSECRET;
                    appsecret = "**********";
                    break;
                case "2":
                    appid = "**********";
                    appsecret = "************";
                    break;
                case "3":
                    appid = "**********";
                    appsecret = "************";
                    break;
                case "4":
                    appid = "**********";
                    appsecret = "************";
                    break;
                case "5":
                    appid = "**********";
                    appsecret = "************";
            }
    
            //授权(必填)
            String grant_type = "authorization_code";
            //URL
            String requestUrl = "https://api.weixin.qq.com/sns/jscode2session";
            //请求参数
            String params = "appid=" + appid + "&secret=" + appsecret + "&js_code=" + code + "&grant_type=" + grant_type;
            //发送请求
            String data = HttpUtil.get(requestUrl, params);
            //解析相应内容(转换成json对象)
            JSONObject  json = JSONObject.fromObject(data);
            //用户的唯一标识(openid)
            String Openid =String.valueOf(json.get("openid"));
            //System.out.println(Openid);
            return Openid;
        }
    }
    
         
         
    • 三、发送请求的工具类

      package com.util;
      
      
      import java.io.BufferedReader;
      import java.io.InputStreamReader;
      import java.net.URL;
      import java.net.URLConnection;
      import java.util.List;
      import java.util.Map;
      
      /**
       * @author xsx
       */
      public class HttpUtil {
          /**
           * 向指定URL发送GET方法的请求
           *
           * @param url
           *            发送请求的URL
           * @param param
           *            请求参数,请求参数应该是 name1=value1&name2=value2 的形式。
           * @return String 所代表远程资源的响应结果
           */
          public static String get(String url,String param){
              String result = "";
              BufferedReader in = null;
              try {
                  String urlNameString = url + "?" + param;
                  //System.out.println(urlNameString);
                  URL realUrl = new URL(urlNameString);
                  // 打开和URL之间的连接
                  URLConnection connection = realUrl.openConnection();
                  // 设置通用的请求属性
                  connection.setRequestProperty("accept", "*/*");
                  connection.setRequestProperty("connection", "Keep-Alive");
                  connection.setRequestProperty("user-agent",
                          "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
                  // 建立实际的连接
                  connection.connect();
                  // 获取所有响应头字段
                  Map<String, List<String>> map = connection.getHeaderFields();
                  // 遍历所有的响应头字段
                  /*for (String key : map.keySet()) {
                      System.out.println(key + "--->" + map.get(key));
                  }*/
                  // 定义 BufferedReader输入流来读取URL的响应
                  in = new BufferedReader(new InputStreamReader(
                          connection.getInputStream()));
                  String line;
                  while ((line = in.readLine()) != null) {
                      result += line;
                  }
              } catch (Exception e) {
                  System.out.println("发送GET请求出现异常!" + e);
                  e.printStackTrace();
              }
              // 使用finally块来关闭输入流
              finally {
                  try {
                      if (in != null) {
                          in.close();
                      }
                  } catch (Exception e2) {
                      e2.printStackTrace();
                  }
              }
              return result;
          }
      }
      
             
             
      • 四、检查参数是否为空的工具类

        public class CheckUtil {
        
            /**
             * 验证是否有空值的参数,只要有一个,就返回true
             *
             * @param args
             * @return true
             */
            public static boolean checkNulls(String... args) {
        
                if (args.length == 0) {
                    return true;
                }
                //
                for (String str : args) {
                    if (isNullOrEmpty(str)) {
                        return true;
                    }
                }
                return false;
            }
        }
                 
                 
    ### 回答1: 在微信小程序中用 Java 写授权登录的代码可以这样写: 1. 先调用 wx.login() 方法,获取到小程序的 code(一个临时登录凭证)。 2. 然后把 code 发送给你的服务器,你的服务器再通过 code 去获取用户信息。具体来说,服务器需要调用微信提供的接口,使用 code 换取用户信息(包括用户的唯一标识 openid 和 会话密钥 session_key)。 3. 在服务器端获取到用户信息之后,把用户信息存储在服务器端的数据库中。 4. 最后调用 wx.setStorageSync() 方法,把用户信息存储在小程序端。 下面是一段代码示例,它展示了如何调用 wx.login() 方法: ``` wx.login({ success: function(res) { if (res.code) { // 发送 res.code 到后台换取 openId, sessionKey, unionId console.log(res.code) } else { console.log('登录失败!' + res.errMsg) } } }); ``` 需要注意的是,上面的代码中的 success 回调函数是在小程序端执行的,因此你需要在服务器端提供一个接口,供小程序端调用,使用 code 换取用户信息。 如果你想了解更多关于微信小程序授权登 ### 回答2: 在微信开发者工具中使用Java编写微信小程序授权登录的代码,可以使用微信开放平台的API实现。以下是一个简单的示例代码: ```java import java.io.BufferedReader; import java.io.InputStream; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; public class WeChatMiniProgramAuth { // 小程序 AppID 和 AppSecret private static final String APPID = "YOUR_APPID"; private static final String APPSECRET = "YOUR_APPSECRET"; public static void main(String[] args) { // 获取登录凭证code String code = "YOUR_CODE"; // 构造获取access_token的URL String url = "https://api.weixin.qq.com/sns/jscode2session?appid=" + APPID + "&secret=" + APPSECRET + "&js_code=" + code + "&grant_type=authorization_code"; try { // 发起HTTP请求 HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection(); connection.setRequestMethod("GET"); connection.connect(); // 读取API返回的JSON数据 InputStream inputStream = connection.getInputStream(); BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream)); StringBuilder response = new StringBuilder(); String line; while ((line = bufferedReader.readLine()) != null) { response.append(line); } bufferedReader.close(); // 解析JSON数据 String accessToken = response.toString(); // 处理access_token等信息 // 对用户数据进行处理 // ... } catch (Exception e) { e.printStackTrace(); } } } ``` 上述代码中,需要将YOUR_APPID和YOUR_APPSECRET替换为在微信开放平台上注册的小程序的实际AppID和AppSecret。另外,需要将YOUR_CODE替换为实际的登录凭证code。 代码中使用了java.net包下的HttpURLConnection类进行HTTP请求。在实际开发中,可以使用更为方便的第三方类库(如Apache HttpClient)来发送HTTP请求并处理返回的JSON数据。 该示例代码中只演示了如何获取access_token以及如何处理用户数据,实际开发中还需要根据业务需求进行其他相关操作。 ### 回答3: 在微信开发者工具中用Java写一段微信小程序授权登录的代码如下: ```java import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; public class WeChatMiniProgramAuth { // 定义小程序AppId和AppSecret private static final String APP_ID = "YourMiniProgramAppId"; private static final String APP_SECRET = "YourMiniProgramAppSecret"; // 定义获取access_token的URL private static final String ACCESS_TOKEN_URL = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + APP_ID + "&secret=" + APP_SECRET; // 定义获取session_key和openid的URL private static final String SESSION_KEY_URL = "https://api.weixin.qq.com/sns/jscode2session?appid=" + APP_ID + "&secret=" + APP_SECRET + "&js_code=%s&grant_type=authorization_code"; // 定义登录凭证校验的URL private static final String LOGIN_URL = "https://api.weixin.qq.com/wxa/msg_sec_check?access_token=%s"; public static void main(String[] args) throws IOException { // 获取access_token String accessToken = getAccessToken(); System.out.println("Access Token: " + accessToken); // 使用登录凭证校验 String code = "YourLoginCode"; loginWithCode(code, accessToken); } // 获取access_token private static String getAccessToken() throws IOException { URL url = new URL(ACCESS_TOKEN_URL); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.connect(); StringBuilder stringBuilder = new StringBuilder(); try (BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(connection.getInputStream()))) { String line; while ((line = bufferedReader.readLine()) != null) { stringBuilder.append(line); } } // 解析获取的JSON数据,获取access_token // 这里需要使用JSON解析库进行解析,这里假设已经获得了access_token return "your_access_token"; } // 使用登录凭证校验 private static void loginWithCode(String code, String accessToken) throws IOException { URL url = new URL(String.format(SESSION_KEY_URL, code)); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.connect(); StringBuilder stringBuilder = new StringBuilder(); try (BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(connection.getInputStream()))) { String line; while ((line = bufferedReader.readLine()) != null) { stringBuilder.append(line); } } // 解析获取的JSON数据,获取session_key和openid // 这里需要使用JSON解析库进行解析,这里假设已经获得了session_key和openid String sessionKey = "your_session_key"; String openid = "your_openid"; // 进行后续的授权登录逻辑处理 // ..... } } ``` 请注意,这段代码中的相关URL地址需要替换为真实的微信小程序开发者服务器地址。同时,还需要使用JSON解析库来解析获取到的JSON数据,实际开发中可以使用各种Java的JSON解析库,如Gson、Jackson等。另外,该代码只实现了获取access_token和使用登录凭证校验的功能,具体的授权登录逻辑需要根据实际需求进行进一步编写。
    评论
    添加红包

    请填写红包祝福语或标题

    红包个数最小为10个

    红包金额最低5元

    当前余额3.43前往充值 >
    需支付:10.00
    成就一亿技术人!
    领取后你会自动成为博主和红包主的粉丝 规则
    hope_wisdom
    发出的红包
    实付
    使用余额支付
    点击重新获取
    扫码支付
    钱包余额 0

    抵扣说明:

    1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
    2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

    余额充值