springboot 解析微信小程序获取手机号

引用依赖包

 <dependency><groupId>bouncycastle</groupId><artifactId>bcprov-jdk14</artifactId><version>138</version></dependency><dependency><groupId>com.alibaba</groupId><artifactId>fastjson</artifactId><version>1.2.80</version></dependency><dependency><groupId>io.github.admin4j</groupId><artifactId>http</artifactId><version>0.4.6</version></dependency><!-- https://mvnrepository.com/artifact/org.bouncycastle/bcprov-jdk15on --><!--解密依赖包--><dependency><groupId>cn.hutool</groupId><artifactId>hutool-all</artifactId><version>5.4.0</version></dependency><dependency><groupId>org.bouncycastle</groupId><artifactId>bcprov-jdk15on</artifactId><version>1.70</version></dependency><dependency><groupId>com.alibaba</groupId><artifactId>fastjson</artifactId><version>1.2.80</version><scope>compile</scope></dependency>

AccountInfo


public class AccountInfo {public static  String grantType="client_credential";public static String appId="";  //public static String appSecret="";  //public static String accessTokenUrl="https://api.weixin.qq.com/cgi-bin/token" ;public static  String getPhoneNumberUrl="https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=";}

接口

  if (code == null || code.length() == 0) {return  null;}String wxAppid = AccountInfo.appId;// 小程序的 app secret (在微信小程序管理后台获取)String wxSecret = AccountInfo.appSecret;// 授权(必填)String grant_type = AccountInfo.grantType;// 请求参数String params = "appid=" + wxAppid + "&secret=" + wxSecret + "&grant_type="+ grant_type;try {String sr = HttpRequest.sendGetSSL(AccountInfo.accessTokenUrl, params);JSONObject json = null;System.out.println("sr");System.out.println(sr);json = JSON.parseObject(sr);String access_token = (String) json.get("access_token");String jsonData = "{\"code\":\"" + telCode + "\"}";Object data = JSON.parse(jsonData);String sr1 = HttpRequest.sendPostSSl(AccountInfo.getPhoneNumberUrl + access_token, data);System.out.println("sr1");System.out.println(sr1);json = JSON.parseObject(sr1);Integer errcode = (Integer) json.get("errcode");if (errcode== 0) {String tel = (String) JSON.parseObject(json.get("phone_info").toString()).get("phoneNumber");//去数据库里面查询if (tel == null || tel.equals("")) {return null;}} else {}} catch (Exception e) {return  null;}

HttpRequest

public class HttpRequest {public static void main(String[] args) {//发送 GET 请求String s=HttpRequest.sendGet("http://v.qq.com/x/cover/kvehb7okfxqstmc.html?vid=e01957zem6o", "");System.out.println(s);//        //发送 POST 请求
//        String sr=HttpRequest.sendPost("http://www.toutiao.com/stream/widget/local_weather/data/?city=%E4%B8%8A%E6%B5%B7", "");
//        JSONObject json = JSONObject.fromObject(sr);
//        System.out.println(json.get("data"));}/*** 向指定URL发送GET方法的请求** @param url*            发送请求的URL* @param param*            请求参数,请求参数应该是 name1=value1&name2=value2 的形式。* @return URL 所代表远程资源的响应结果*/public static String sendGet(String url, String param) {String result = "";BufferedReader in = null;try {String urlNameString = url + "?" + param;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();}}System.out.println("result");System.out.println(result);return result;}/***  http get请求 请求参数在url后面拼接*  @throws Exception*/public static String sendGetSSl(String requestUrl, String param,Map<String,String> header) throws Exception{HttpsURLConnection conn = null;InputStream input = null;BufferedReader br = null;StringBuffer buffer = null;try {SSLContext sc = SSLContext.getInstance("SSL");sc.init(null, new TrustManager[] { new TrustAnyTrustManager() },new java.security.SecureRandom());HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());String urlNameString = requestUrl + "?" + param;URL url = new URL(urlNameString);conn = (HttpsURLConnection) url.openConnection();conn.setSSLSocketFactory(sc.getSocketFactory());conn.setHostnameVerifier(new TrustAnyHostnameVerifier());conn.setDoOutput(false);conn.setDoInput(true);conn.setUseCaches(false);conn.setConnectTimeout(1000 * 100);conn.setReadTimeout(1000 * 100);conn.setRequestMethod("GET");conn.setRequestProperty("Accept", "*/*");conn.setRequestProperty("Connection", "keep-alive");conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");conn.setRequestProperty("Charset", "UTF-8");conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");//添加headerif(header != null){for(Map.Entry<String, String> entry : header.entrySet()){String mapKey = entry.getKey();String mapValue = entry.getValue();conn.setRequestProperty(mapKey, mapValue);}}conn.connect();// 读取服务器端返回的内容System.out.println("======================响应体=========================");System.out.println("ResponseCode:" + conn.getResponseCode() + ",ResponseMessage:" + conn.getResponseMessage());if(conn.getResponseCode()==200){input = conn.getInputStream();}else{input = conn.getErrorStream();}br = new BufferedReader(new InputStreamReader(input, "UTF-8"));buffer = new StringBuffer();String line = null;while ((line = br.readLine()) != null) {buffer.append(line);}System.out.println("返回报文:" + buffer.toString());} catch (Exception e) {System.out.println("发送GET请求出现异常!" + e);e.printStackTrace();} finally {try {if (conn != null) {conn.disconnect();conn = null;}if (br != null) {br.close();br = null;}} catch (IOException ex) {throw new Exception(ex);}}return buffer.toString();}public static String sendGetSSL(String requestUrl,String param){String urlNameString = requestUrl + "?" + param;Response response = HttpUtil.get(urlNameString);ResponseBody responseBody = response.body();okio.BufferedSource source = responseBody.source();try {source.request(Long.MAX_VALUE); // Buffer the entire body.okio.Buffer buffer = source.buffer();Charset charset = StandardCharsets.UTF_8;MediaType contentType = responseBody.contentType();if (contentType != null) {charset = contentType.charset(StandardCharsets.UTF_8);}return buffer.clone().readString(charset);} catch (IOException e) {throw new RuntimeException(e);}}public static String sendPostSSl(String requestUrl,Object body){Response response= HttpUtil.post(requestUrl, body);ResponseBody responseBody = response.body();okio.BufferedSource source = responseBody.source();try {source.request(Long.MAX_VALUE); // Buffer the entire body.okio.Buffer buffer = source.buffer();Charset charset = StandardCharsets.UTF_8;MediaType contentType = responseBody.contentType();if (contentType != null) {charset = contentType.charset(StandardCharsets.UTF_8);}return buffer.clone().readString(charset);} catch (IOException e) {throw new RuntimeException(e);}}/*** 向指定 URL 发送POST方法的请求** @param url*            发送请求的 URL* @param param*            请求参数,请求参数应该是 name1=value1&name2=value2 的形式。* @return 所代表远程资源的响应结果*/public static String sendPost(String url, String param) {PrintWriter out = null;BufferedReader in = null;String result = "";try {URL realUrl = new URL(url);// 打开和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)");// 发送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()));String line;while ((line = in.readLine()) != null) {result += line;}} catch (Exception e) {System.out.println("发送 POST 请求出现异常!"+e);e.printStackTrace();}//使用finally块来关闭输出流、输入流finally{try{if(out!=null){out.close();}if(in!=null){in.close();}}catch(IOException ex){ex.printStackTrace();}}return result;}
}

TrustAnyHostnameVerifier

public class TrustAnyHostnameVerifier implements HostnameVerifier {public boolean verify(String hname, SSLSession session) {return true;}
}

TrustAnyTrustManager

public class TrustAnyTrustManager implements X509TrustManager {public  void checkClientTrusted(java.security.cert.X509Certificate[] var1, String var2) throws java.security.cert.CertificateException{}public void checkServerTrusted(java.security.cert.X509Certificate[] var1, String var2) throws java.security.cert.CertificateException{}public java.security.cert.X509Certificate[] getAcceptedIssuers(){return null;}
}

WeChatUtil

public class WeChatUtil {/*** 请求微信接口服务,获取 openid,session_key,unionid,errcode,errmsg* https://developers.weixin.qq.com/miniprogram/dev/api-backend/open-api/login/auth.code2Session.html** @param jscode* @return*/public static JSONObject getSessionByCode(String jscode) {// jscode是前端请求wx.login()方法获取的code;不是getPhoneNumber接口获取的code// wx.login()方法,需要最先调用,否则可能会报错:pad block corrupted,获取不到解密的信息String baseUrl = "https://api.weixin.qq.com/sns/jscode2session";HashMap<String, Object> requestParam = new HashMap<>();// 小程序 appIdrequestParam.put("appid",  AccountInfo.appId);// 小程序 appSecretrequestParam.put("secret",  AccountInfo.appSecret);// 登录时获取的 code(小程序端返回的code)requestParam.put("js_code", jscode);// 默认参数,填“authorization_code”requestParam.put("grant_type", "authorization_code");// 发送post请求读取调用微信接口获取openid用户唯一标识String result = HttpUtil.get(baseUrl, requestParam);return JSONUtil.parseObj(result);}/*** 解密:通过加密密钥,iv偏移量来解密 encryptedData* 根据encryptedData的不同,解密出来的json数据结构不同(数据结构的详情需要看前端调用的是哪个微信的接口,获取用户哪些信息)** @param encryptData* @param sessionKey* @param iv* @return*/public static JSONObject getUserInfo(String encryptData, String sessionKey, String iv) {// 解密:被加密的数据byte[] dataByte = Base64.decode(encryptData);// 解密:加密密钥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());KeyGenerator.getInstance("AES").init(128);// 生成ivAlgorithmParameters iv1 = AlgorithmParameters.getInstance("AES");iv1.init(new IvParameterSpec(ivByte));// 生成解密SecretKeySpec secretKeySpec = new SecretKeySpec(keyByte, "AES");Cipher cipher = Cipher.getInstance("AES/CBC/PKCS7Padding");cipher.init(Cipher.DECRYPT_MODE, secretKeySpec, iv1);// 设置为解密模式byte[] decryptByte = cipher.doFinal(dataByte);if (null != decryptByte && decryptByte.length > 0) {String result = new String(decryptByte, "UTF-8");return JSONUtil.parseObj(result);}} catch (Exception e) {e.printStackTrace();}return null;}
}

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/226959.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

I2C 从设备

驱动文件 \drivers\i2c\busses\i2c-designware-slave.c I2C控制器 \drivers\i2c\i2c-slave-eeprom.c I2C设备示例 由于作为从&#xff0c;接收主写过来的数据时总是少一个&#xff0c;因为分析相关。 控制器驱动中断 加打印&#xff0c;很多时候不能打印出来。如下中断中…

为什么选择国产WordPress:HelpLook的优势解析

如今网站建设可以说已经是企业必备。而在众多的网站建设工具中&#xff0c;WordPress无疑是其中的佼佼者。作为一款开源的CMS&#xff08;内容管理系统&#xff09;&#xff0c;WordPress拥有丰富的插件和主题&#xff0c;以及强大的功能&#xff0c;使得用户可以轻松地构建出符…

vivado约束方法8

无交互的逻辑互斥时钟组 逻辑排他性时钟是指在不同源点上定义但共享部分的时钟由于多路复用器或其他组合逻辑&#xff0c;它们的时钟树。时间限制向导识别此类时钟&#xff0c;并建议在它们这样做时直接对其进行时钟组约束除了连接到其共享时钟的逻辑之外&#xff0c;彼此之间…

半导体:Gem/Secs基本协议库的开发(5)

此篇是1-4 《半导体》的会和处啦&#xff0c;我们有了协议库&#xff0c;也有了通讯库&#xff0c;这不得快乐的玩一把~ 一、先创建一个从站&#xff0c;也就是我们的Equipment端 QT - guiCONFIG c11 console CONFIG - app_bundle CONFIG no_debug_release # 不会生…

Python 直观理解基尼系数

基尼系数最开始就是衡量人群财富收入是否均衡&#xff0c;大家收入平平&#xff0c;那就是很平均&#xff0c;如果大家收入不平等&#xff0c;那基尼系数就很高。 还是给老干部们讲的言简意赅。 什么是基尼系数 我们接下来直接直观地看吧&#xff0c;程序说话 # -*- coding:…

Chart.js 实现实时动态折线图 并限制最大长度

<!DOCTYPE html> <html><head><title>模拟</title><script src"https://lib.sinaapp.com/js/jquery/3.1.0/jquery-3.1.0.min.js"></script><script src"https://cdn.staticfile.org/Chart.js/3.9.1/chart.js"…

小程序图片显示不出来 怎么解决?

一、如果不是本地路径的图片 可以改成本地路径 二、使用图床 使用图床的基本步骤如下&#xff1a; 选择图床服务&#xff1a;根据自己的需求选择一家可靠的图床服务提供商&#xff0c;例如七牛云、腾讯云COS、阿里云OSS等。 注册账号&#xff1a;前往选定的图床服务提供商的…

12345、ABCDE项目符号列表文字视频怎么制作?重点内容介绍PR标题模板项目工程文件

Premiere模板&#xff0c;包含10个要点标题12345、ABCDE项目符号列表文字模板PR项目工程文件。可以根据自己的需要定制颜色。在视频的开头、中间和结尾使用。包括视频教程。 适用软件&#xff1a;Premiere Pro 2019 | 分辨率&#xff1a;19201080 (HD) | 文件大小&#xff1a;9…

基于Java SSM框架实现疫情居家办公OA系统项目【项目源码+论文说明】

基于java的SSM框架实现疫情居家办公OA系统演示 摘要 21世纪的今天&#xff0c;随着社会的不断发展与进步&#xff0c;人们对于信息科学化的认识&#xff0c;已由低层次向高层次发展&#xff0c;由原来的感性认识向理性认识提高&#xff0c;管理工作的重要性已逐渐被人们所认识…

Python基础03-循环结构

零、文章目录 Python基础03-循环结构 1、循环简介 &#xff08;1&#xff09;循环是什么 程序是为了解决实际问题的&#xff0c;实际问题中存在着重复动作&#xff0c;那么程序中也应该有相应的描述&#xff0c;这就是循环。 &#xff08;2&#xff09;循环的作用 让代码…

加油站“变身”快充站,探讨充电新模式——安科瑞 顾烊宇

摘要&#xff1a;新能源汽车规模化发展的同时&#xff0c;充电不便利的痛点愈发明显。在未来的新能源汽车行业发展当中&#xff0c;充电的矛盾要远远大于造车的矛盾&#xff0c;解决好充电的问题成为电动汽车行业发展的一个突出问题。解决充电补能问题&#xff0c;重要的方式之…

LangChain(0.0.340)官方文档十:Retrieval——Retrievers(检索器)

LangChain官网、LangChain官方文档 、langchain Github、langchain API文档、llm-universe 文章目录 一、Vector store-backed retriever1.1 基础示例1.1.1 从文本创建Vector store1.1.2 从documents创建Vector store1.1.3 MMR搜索1.1.4 设置相似性分数阈值1.1.5 指定 top k 1.…

分库分表以后,如何实现扩容?

在实际开发中&#xff0c;数据库的扩容和不同的分库分表规则直接相关&#xff0c;今天我们从系统设计的角度&#xff0c;抽象了一个项目开发中出现的业务场景&#xff0c;从数据库设计、路由规则&#xff0c;以及数据迁移方案的角度进行讨论。 从业务场景出发进行讨论 假设这…

msvcrtd.dll下载安装方法,解决msvcrtd.dll找不到的问题

在这篇文章中&#xff0c;我们将详细讨论msvcrtd.dll文件的下载安装方法&#xff0c;并分析出现找不到msvcrtd.dll的情况及解决方法。如果你遇到了与msvcrtd.dll相关的问题&#xff0c;本文将为你提供全面且详细的解决方案。 一.什么是msvcrtd.dll文件 首先&#xff0c;让我们…

透明PP专用UV胶水粘接PP材料高效率的提升生产效率

使用透明PP专用UV胶水粘接PP材料是提高生产效率的方法。以下方法&#xff0c;可以助您在生产中实现高效的PP材料粘接&#xff1a; ​1.选用合适的透明PP专用UV胶水 选择经过专门设计用于透明PP的UV胶水。这种胶水具有透明性&#xff0c;能保证粘接后的清晰度和外观。 2.自动…

vue中预览pdf的方法

使用vue-pdf 备注&#xff1a;这里只介绍了一页的pdf <div class"animation-box-pdf"><pdf :src"http://xxxx" /> </div>import Pdf from vue-pdf // src可以是文件地址url&#xff0c;也可以是文件流blob&#xff08;将blob转成url&a…

W25N01GV 芯片应用

项目中处于成本考虑&#xff0c;要把Nor Flash换成低成本的Nand Flash。 这里总结下芯片应用。 总体概述&#xff1a; 1&#xff09;W25N01&#xff08;NandFlash&#xff09;和W25Q&#xff08;Nor Flash&#xff09;的操作大不一样。 NandFlash擦除以块&#xff08;128KB&…

Java系列-ConcurrentHashMap构造方法

1.无参 什么都没做 public class ConcurrentHashMap<K,V> extends AbstractMap<K,V>implements ConcurrentMap<K,V>, Serializable {private static final float LOAD_FACTOR 0.75f;public ConcurrentHashMap() {} } 2.带初始容量 tableSizeFor方法的实…

外包干了3年,技术退步明显。。。

前言 简单说下我的情况吧&#xff01;普通本科的科班生&#xff0c;19年的时候通过校招进了一家小自研&#xff0c;工资还凑合&#xff0c;在里面带了一年多&#xff0c;公司没了&#xff0c;疫情期间找工作很麻烦&#xff0c;后面就开始自己近3年的外包生涯&#xff0c;这三年…

如果你找不到东西,请先确保你在正确的地方寻找

之前我们在几篇文章中描述了如何进行”思想”调试&#xff0c;今天的文章我将不会这样做。 因为下面的编程错误大部分人都会遇到&#xff0c;如果你看一眼下面的代码&#xff0c;你不会发现有什么问题&#xff0c;这仅仅是因为你的的大脑只给你希望看到的&#xff0c;而不是那…