diff --git a/src/main/java/com/ycwl/basic/utils/WxMpUtil.java b/src/main/java/com/ycwl/basic/utils/WxMpUtil.java index c27d180..703a1cb 100644 --- a/src/main/java/com/ycwl/basic/utils/WxMpUtil.java +++ b/src/main/java/com/ycwl/basic/utils/WxMpUtil.java @@ -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_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"; + public static final String GET_USER_PHONE_URL = "https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=%s"; private static final Map tokens = new ConcurrentHashMap<>(); private static final Map 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 { generateWXAQRCode("wxe7ff26af70bfc37c", "5252fbbc68513bc77b7cc0052b9f9695", "trial", "pages/home/index?scenicId=3978838215909052416", "dhg_t.jpg"); }