当前位置:网站首页>微信小程序获取手机号
微信小程序获取手机号
2022-07-06 09:38:00 【飞飞翼】
1、主要接口
//小程序 AppID
private static final String appid = "wxa******e0b3";
//小程序 AppSecret
private static final String secret = "8ffc**************bc0896e937d";
@PostMapping("/wxphone")
public Map<String,Object> wxphone(@RequestBody Image image)
{
Map<String,Object> map=new HashMap<>();
String encryptedData=image.getParams().get("encryptedData").toString();
String session_key="";
String iv=image.getParams().get("iv").toString();
String code=image.getParams().get("code").toString();
// 获取session_key,完善一下 存到数据库
HttpUtil httpUtil=new HttpUtil();
String params = "appid=" + appid + "&secret=" + secret + "&js_code=" + code + "&grant_type=authorization_code";
String session_keyData=HttpUtil.sendGet("https://api.weixin.qq.com/sns/jscode2session", params);
JSONObject json_session=JSONObject.parseObject(session_keyData);
session_key=json_session.get("session_key").toString();
// 获取手机号
String result= WXBizDataCrypt.decrypt1(encryptedData,session_key,iv);
JSONObject json=JSONObject.parseObject(result);
if (!StringUtils.isEmpty(result)&&result.length()>0) {
map.put("purePhoneNumber", json.getString("purePhoneNumber"));
map.put("phoneNumber", json.getString("phoneNumber"));
map.put("countryCode", json.getString("countryCode"));
map.put("msg","success");
}
map.put("msg","按操作成功");
map.put("code",200);
return map;
}
2.工具类 请求接口
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.util.List;
import java.util.Map;
public class HttpUtil {
/**
* 向指定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();
}
}
return result;
}
}
3.解密用的
import org.apache.commons.codec.binary.Base64;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.io.UnsupportedEncodingException;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.spec.AlgorithmParameterSpec;
public class WXBizDataCrypt {
/**
* AES解密
*
* @param data //密文,被加密的数据
* @param key //秘钥
* @param iv //偏移量
* @return
* @throws Exception
*/
public static String decrypt1(String data, String key,String iv){
//被加密的数据
byte[] dataByte = Base64.decodeBase64(data);
//加密秘钥
byte[] keyByte = Base64.decodeBase64(key);
//偏移量
byte[] ivByte = Base64.decodeBase64(iv);
try {
AlgorithmParameterSpec ivSpec = new IvParameterSpec(ivByte);
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
SecretKeySpec keySpec = new SecretKeySpec(keyByte, "AES");
cipher.init(Cipher.DECRYPT_MODE, keySpec, ivSpec);
return new String(cipher.doFinal(dataByte),"UTF-8");
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (NoSuchPaddingException e) {
e.printStackTrace();
} catch (InvalidKeyException e) {
e.printStackTrace();
} catch (InvalidAlgorithmParameterException e) {
e.printStackTrace();
} catch (IllegalBlockSizeException e) {
e.printStackTrace();
} catch (BadPaddingException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return null;
}
}
边栏推荐
- 华为认证云计算HICA
- Wordcloud colormap color set and custom colors
- Remote code execution penetration test - B module test
- Single responsibility principle
- Summary of study notes for 2022 soft exam information security engineer preparation
- CTF reverse entry question - dice
- [VNCTF 2022]ezmath wp
- Solrcloud related commands
- Serial serialold parnew of JVM garbage collector
- [reverse intermediate] eager to try
猜你喜欢
Huawei certified cloud computing hica
学 SQL 必须了解的 10 个高级概念
Final review of information and network security (based on the key points given by the teacher)
CTF reverse entry question - dice
Models used in data warehouse modeling and layered introduction
04 products and promotion developed by individuals - data push tool
虚拟机启动提示Probing EDD (edd=off to disable)错误
C WinForm series button easy to use
How does wechat prevent withdrawal come true?
Connect to LAN MySQL
随机推荐
Xin'an Second Edition: Chapter 23 cloud computing security requirements analysis and security protection engineering learning notes
轻量级计划服务工具研发与实践
集成开发管理平台
[reverse primary] Unique
PyTorch 提取中间层特征?
信息与网络安全期末复习(基于老师给的重点)
The art of Engineering (3): do not rely on each other between functions of code robustness
The solution to the left-right sliding conflict caused by nesting Baidu MapView in the fragment of viewpager
Vscode replaces commas, or specific characters with newlines
Flink parsing (IV): recovery mechanism
05个人研发的产品及推广-数据同步工具
[elastic] elastic lacks xpack and cannot create template unknown setting index lifecycle. name index. lifecycle. rollover_ alias
【逆向中级】跃跃欲试
Selenium test of automatic answer runs directly in the browser, just like real users.
The NTFS format converter (convert.exe) is missing from the current system
[reverse intermediate] eager to try
关于Selenium启动Chrome浏览器闪退问题
06 products and promotion developed by individuals - code statistical tools
The art of Engineering (2): the transformation from general type to specific type needs to be tested for legitimacy
Automatic operation and maintenance sharp weapon ansible Foundation