微信获取手机号

This commit is contained in:
2025-05-25 16:31:13 +08:00
parent 3b3c768bbe
commit 7fd62e9aba

View File

@ -13,6 +13,7 @@ public class WxMpUtil {
private static final String GET_WXA_CODE_URL = "https://api.weixin.qq.com/wxa/getwxacode?access_token=%s"; private static final String GET_WXA_CODE_URL = "https://api.weixin.qq.com/wxa/getwxacode?access_token=%s";
private static final String GET_URL_LICK_URL = "https://api.weixin.qq.com/wxa/generate_urllink?access_token=%s"; private static final String GET_URL_LICK_URL = "https://api.weixin.qq.com/wxa/generate_urllink?access_token=%s";
private static final String ACCESS_TOKEN_URL = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=%s&secret=%s"; private static final String ACCESS_TOKEN_URL = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=%s&secret=%s";
public static final String GET_USER_PHONE_URL = "https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=%s";
private static final Map<String, String> tokens = new ConcurrentHashMap<>(); private static final Map<String, String> tokens = new ConcurrentHashMap<>();
private static final Map<String, Date> expireTimes = new ConcurrentHashMap<>(); private static final Map<String, Date> expireTimes = new ConcurrentHashMap<>();
@ -75,6 +76,22 @@ public class WxMpUtil {
} }
} }
public static String getUserPhone(String appId, String appSecret, String code) throws Exception {
String url = String.format(GET_USER_PHONE_URL, getAccessToken(appId, appSecret));
JSONObject json = new JSONObject();
json.put("code", code);
try (HttpResponse response = HttpUtil.createPost(url).body(json.toJSONString()).header("Content-Type", "application/json").execute()) {
String responseStr = response.body();
JSONObject jsonObject = JSONObject.parseObject(responseStr);
if (jsonObject.getInteger("errcode") != 0) {
throw new Exception("获取用户手机号失败,原因为:" + jsonObject.getString("errmsg"));
}
return jsonObject.getJSONObject("phone_info").getString("phoneNumber");
}
}
public static void main(String[] args) throws Exception { public static void main(String[] args) throws Exception {
generateWXAQRCode("wxe7ff26af70bfc37c", "5252fbbc68513bc77b7cc0052b9f9695", "trial", "pages/home/index?scenicId=3978838215909052416", "dhg_t.jpg"); generateWXAQRCode("wxe7ff26af70bfc37c", "5252fbbc68513bc77b7cc0052b9f9695", "trial", "pages/home/index?scenicId=3978838215909052416", "dhg_t.jpg");
} }