小程序后端获取一些用户信息

先写一个get请求公用方法,后面很多接口都要用到

//根据url获取openId和sessionkey
 private 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);
 int mTimeout = 10000;
 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;
 }各种请求url
 // 定义微信解密获取手机号码的接口地址,固定的
 private final String wxAppHost = “https://api.weixin.qq.com”;
 private final String wxAppPath = “/sns/jscode2session”;
 /**
 * 获取access_token的url
 *
 *appid=APPID(公众号唯一标识)
 * secret=SECRET(公众号的appsecret)
 * code=CODE(第一步获取的code参数)
 * grant_type=authorization_code(无需更改)
 *
 * 返回结果(json格式数据)
 * {
 * “access_token”: “e1nYJFpZuehfQH1buzHFZLb7onqs_wT1cudSdy9HRlnaMXFtFpRMNFOA0euK6UxPcItrSNbAQVcXDdthbLJYX0MdH1p7-tkZSKuGqBCxVc0”,
 * “expires_in”: 7200,
 * “refresh_token”: “0iVsXn4O1rBCASbO7hx8VNVUVFM1RP2Q4xS0giegd4jlIsJYOjTJNZ0b4Dsh_xcoB02ZZ3bt0WH0a47LvjIEPjWUnESJCZyl6EtY_xYZdVs”,
 * “openid”: “o47Fa0mp9SRTf3eiKmqWm69BjG_8”,
 * “scope”: “snsapi_userinfo”
 * }
 *
 * 结果解释
 * access_token 网页授权接口调用凭证,注意:此access_token与基础支持的access_token不同
 * expires_in access_token接口调用凭证超时时间,单位(秒)
 * refresh_token 用户刷新access_token
 * openid 用户唯一标识,请注意,在未关注公众号时,用户访问公众号的网页,也会产生一个用户和公众号唯一的OpenID
 * scope 用户授权的作用域,使用逗号(,)分隔
 * */
 private final String getTokenUrl = “https://api.weixin.qq.com/sns/oauth2/”;
/**
 * 使用access_token获取用户信息的url
 *参数说明
 * access_token=ACCESS_TOKEN(第2步获取的access_token参数,此access_token与基础支持的access_token不同)
 * openid=OPENID(第2步获取的openid参数)
 * langlang=zh_CN	返回国家地区语言版本,zh_CN 简体,zh_TW 繁体,en 英语
 *
 *返回结果(json格式数据)
 * {
 * "openid": "o47Fa0mp9SRTf3eiKmqWm69BjG_8",
 * "nickname": "齐齐",
 * "sex": 0,
 * "language": "zh_CN",
 * "city": "Shaoxing",
 * "province": "Zhejiang",
 * "country": "CN",
 * "headimgurl": "http://wx.qlogo.cn/mmhead/Q3auHgzwzM6kqfcibzzVc8MDGBch53mIgJjWrbKSwkBnzcsWBOMOGlg/0",
 * "privilege": []
 * }
 *
 * 结果解释
 * openid	用户的唯一标识
 * nickname	用户昵称
 * sex	用户的性别,值为1时是男性,值为2时是女性,值为0时是未知
 * province	用户个人资料填写的省份
 * city	普通用户个人资料填写的城市
 * country	国家,如中国为CN
 * headimgurl	用户头像,最后一个数值代表正方形头像大小(有0、46、64、96、132数值可选,0代表640*640正方形头像),用户没有头像时该项为空
 * privilege	用户特权信息,json 数组,如微信沃卡用户为(chinaunicom)
 *
 */
private final String getUserInfoUrl = "https://api.weixin.qq.com/sns/userinfo?";

1、获取用户信息

@RequestMapping("/getUserinfo")
 public Result getUserinfo(@RequestBody Map json){
 String code = json.get(“code”).toString();
 //获取access_token
 String path = getTokenUrl+“appid=”+weixinConfig.getAppid()+"&secret="+weixinConfig.getSecret()+
 “&code=”+code+"&grant_type=authorization_code";
 try{
 String res[] = requestJson(path);
 JSONObject jsonObject = JSON.parseObject(res[0]);
 String accessToken = jsonObject.getString(“access_token”);
 if(ToolUtil.isEmpty(accessToken)){
 log.error(“获取access_token异常”);
 return Result.failure(“获取access_token失败”);
 }
 String openId = jsonObject.getString(“openid”);
 //获取用户信息
 String path2 = getUserInfoUrl+accessToken+"&openid="+openId+"&lang=zh_CN";
 String res2[] = requestJson(path2);
 JSONObject jsonObject2 = JSON.parseObject(res2[0]);
 return Result.success(jsonObject2);
 }catch (Exception e){
 log.error(“获取用户信息异常,信息如下:”, e);
 return Result.failure(“获取用户信息失败”);
 }
 }/**
 *
 * 小程序
 * 获取openId 和 sessionkey
 * @param
 * @param
 * @param
 * @return
 * @RequestParam(value = “encrypted”) String encrypted,
 * @RequestParam(value = “iv”) String iv,
 * @RequestParam(value = “code”) String code
 */
 @RequestMapping(value = “/decodePhone”, method = RequestMethod.POST)
 public Result getAppPhone(@RequestBody Map json) {
 String encrypted = json.get(“encrypted”).toString();
 String iv = json.get(“iv”).toString();
 String code = json.get(“code”).toString();
 JSONObject returnObject = new JSONObject();
 try {
 returnObject = decodeWxAppPhone(encrypted, iv, code);
 if(ToolUtil.isEmpty(returnObject)){
 return Result.failure(“无法获取sessionkey”);
 }
 return Result.success(returnObject);
 } catch (Exception e) {
 // TODO Auto-generated catch block
 e.printStackTrace();
 }
 return Result.failure(“无法获取sessionkey”);
 }获取手机号方法
 private JSONObject decodeWxAppPhone(String encrypted, String iv, String code){
String path =wxAppHost+
            wxAppPath
            + "?appid="
            + weixinConfig.getAppid()
            + "&secret="
            + weixinConfig.getSecret()
            + "&js_code="
            + code
            + "&grant_type=authorization_code&connect_redirect=1#wechat_redirect";
    try {
        // 向微信服务器发送get请求获取加密了的内容
// HttpResponse response = HttpUtils.doGet(wxAppHost, path, “GET”, null, null);
 // String jsonStr = response.getEntity();
 String res[] = requestJson(path);
 JSONObject jsonObject = JSON.parseObject(res[0]);
 String sessionkey = jsonObject.getString(“session_key”); // 解密
 String openId = jsonObject.getString(“openid”);
 byte[] encrypData = Base64Utils.decodeFromString(encrypted);
 byte[] ivData = Base64Utils.decodeFromString(iv);
 byte[] sessionKey = Base64Utils.decodeFromString(sessionkey);
 AlgorithmParameterSpec ivSpec = new IvParameterSpec(ivData);
 Cipher cipher = Cipher.getInstance(“AES/CBC/PKCS5Padding”);
 SecretKeySpec keySpec = new SecretKeySpec(sessionKey, “AES”);
 cipher.init(Cipher.DECRYPT_MODE, keySpec, ivSpec);
 String resultString = new String(cipher.doFinal(encrypData), “UTF-8”);
 JSONObject object = JSONObject.parseObject(resultString); // 拿到手机号码
 String phone = object.getString(“phoneNumber”); // 返回手机号码
 JSONObject returnObject = new JSONObject();
 returnObject.put(“phone”, phone);
returnObject.put("openid",openId);
        return returnObject;
    } catch (Exception e) {
        log.error("微信小程序手机号码解密异常,信息如下:", e);
        return null;
    }


/**
 * 小程序获取 unionid
 * @param json
 * @return
 */
@RequestMapping("/getUnionid")
public Result getUnionid(@RequestBody Map json){
    String encrypted = json.get("encrypted").toString();
    String iv = json.get("iv").toString();
    String code = json.get("code").toString();
    JSONObject returnObject = new JSONObject();
    try {
        returnObject = getWeChatUserinfo(encrypted, iv, code);
        if(ToolUtil.isEmpty(returnObject)){
            return Result.failure("获取失败");
        }
        String unionId = returnObject.getString("unionId");          // 返回手机号码
        JSONObject object = new JSONObject();
        object.put("unionId", unionId);

        return Result.success(object);
    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    return Result.failure("获取失败");
}