小程序授权获取微信用户手机号码

后台代码:

获取手机号码:

	@RequestMapping(value = "decode/wxapp/phone", method = RequestMethod.POST,produces="application/json;charset=UTF-8")
	  @ResponseBody
		public ResultOutDto decodeWxAppPhone(
	         String encrypted,
	         String iv,
	         String code) {
	      return ResultOutDto.ok(decodeWxAppPhoneService(encrypted, iv, code));
	  }


	 
	  
	  public JSONObject decodeWxAppPhoneService(String encrypted, String iv, String code) {

	  		try{
//	  		JSONObject json = JSONObject.fromObject(new UserInfoController().sendPost(WX_APPID, WX_SECRET, code, "authorization_code"));
//	          String jsonStr = EntityUtils.toString(response.getEntity());     
//	          JSONObject jsonObject = JSON.parseObject(jsonStr);
	  			JSONObject json = JSONObject.fromObject(code);
	          String sessionkey = json.getString("session_key");

	          // 解密
	          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.fromObject(resultString);
	         // 拿到手机号码
	          String phone = object.getString("phoneNumber");
	          // 返回手机号码
	          JSONObject returnObject = new JSONObject();
	          returnObject.put("phone", phone);
	          return returnObject;
	      } catch (Exception e) {
	          System.out.println("微信小程序手机号码解密异常,信息如下:");
	          e.printStackTrace();
	      }
		return null;
	  }

第二: 

/**
	 * 获取微信openid
	 * 获取 session_key 和 openid 等。
	 * code 调用微信登陆返回的Code 
	 */
	 @IgnoreAuth
	@ResponseBody
	@RequestMapping(value="/getOpenId",produces="application/json;charset=UTF-8")
	public static JSONObject sendPost(String appid, String secret, String js_code, String grant_type) {
		PrintWriter out = null;
		BufferedReader in = null;
		String result = "";
		try {
			URL realUrl = new URL("https://api.weixin.qq.com/sns/jscode2session");
			// 打开和URL之间的连接
			URLConnection conn = realUrl.openConnection();
			// 设置通用的请求属性
			conn.setRequestProperty("accept", "*/*");
			conn.setRequestProperty("connection", "Keep-Alive");
			conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
			// conn.setRequestProperty("Charset", "UTF-8");
			// 发送POST请求必须设置如下两行
			conn.setDoOutput(true);
			conn.setDoInput(true);
			// 获取URLConnection对象对应的输出流
			out = new PrintWriter(conn.getOutputStream());
			// 设置请求属性
			String param = "appid=" + appid + "&secret=" + secret + "&js_code=" + js_code + "&grant_type=" + grant_type;
			// 发送请求参数
			out.print(param);
			// flush输出流的缓冲
			out.flush();
			// 定义BufferedReader输入流来读取URL的响应
			in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
			String line;
			while ((line = in.readLine()) != null) {
				result += line;
			}

		} catch (Exception e) {
			System.err.println("发送 POST 请求出现异常!" + e);
			e.printStackTrace();
		}
		// 使用finally块来关闭输出流、输入流
		finally {
			if (out != null) {
				out.close();
			}
		}
		
		JSONObject json = JSONObject.fromObject(result);
		System.out.println(json);

		return json;
	}

猜你喜欢

转载自blog.csdn.net/linhaibing009/article/details/89354857