/**
* 微信获取微信手机号码
*/
public class WeChatPhoneNumber {
private static final String APP_ID = "wxdccb07c021632aa5";
private static final String APP_SECRET = "ad50162bbf96b0561911c3264acd267a";
public static void main(String[] args) {
String code = "7d0ff3e86deb0c934b9b4b050b06c14096e3c117308412671edcd605db1d97b7";
System.out.println("Phone number: " + getWxPhone(code,APP_ID,APP_SECRET));
}
/**
* 获取微信手机号码
* @param code 前端获取,传入
* @param appId
* @param appSecret
* @return
*/
public static String getWxPhone(String code,String appId,String appSecret) {
String url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid="+appId+"&secret="+appSecret;
String resultString = HttpUtil.get(url);
System.out.println("resultString: " + resultString);
if (!StringUtils.isEmpty(resultString)) {
JSONObject json = JSONObject.parseObject(resultString);
String accessToken = json.getString("access_token");
System.out.println("accessToken: " + accessToken);
String phoneUrl="https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token="+accessToken;
Map<String, Object> map = new LinkedHashMap<>();
map.put("code",code);
String res = HttpUtil.post(phoneUrl,JSONObject.toJSONString(map));
JSONObject phoneJson = JSONObject.parseObject(res);
System.out.println("phoneJson: " + phoneJson);
if("0".equals( phoneJson.get("errcode").toString())){
String phoneInfo = phoneJson.get("phone_info").toString();
JSONObject phoneInfojson = JSONObject.parseObject(phoneInfo);
return phoneInfojson.get("phoneNumber").toString();
}
} else {
throw new RuntimeException("返回值为空,请检查请求报文或者请求地址是否正确");
}
return null;
}
}
前端获取code代码
<button open-type="getPhoneNumber" bindgetphonenumber="getPhoneNumber"></button>
Page({
getPhoneNumber (e) {
console.log(e.detail.code) // 动态令牌
console.log(e.detail.errMsg) // 回调信息(成功失败都会返回)
console.log(e.detail.errno) // 错误码(失败时返回)
}
})