微信小程序获取手机号phonenumber.getPhoneNumber接口开发

1、接口规范

小程序获取手机号phonenumber.getPhoneNumber接口规范参考链接

1.1、接口请求地址

POST https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=ACCESS_TOKEN

注意:是POST方式

1.2、接口请求参数

access_token:接口调用凭证,需要使用表单方式请求;
code:手机号获取凭证,跟用户登录的code不一样!,需要使用JSON方式请求;

1.3、接口响应参数(返回的 JSON 数据包)

phone_info:用户手机号信息,返回的是个Object对象,里边包含了手机号信息
errcode:错误码(异常情况才会有错误码返回,正常是没有该字段返回的)
errmsg:错误信息

2、准备工作

需要准备请求接口的2个参数:
access_token:接口调用凭证,其实就是token,获取token可以参考之前的博文 点我跳转
code:获取手机号 code,需要前端配置小程序信息获得,前端支持一下即可;

3、代码

//getWxPhone()方法用来将所有请求参数拼接起来形成最终的请求URL,可以在postman/apifox里面先行测通
//将code参数封装到JSON对象中进行请求
//将access_token拼接到接口URL中进行请求
String urlPhone = getWxPhone(accessToken);
Map<String, Object> params = new HashMap<>();
params.put("code",code2);
//发起请求
String respPhone = HttpUtil.post(urlPhone, params);
if(StringUtil.isNull(respPhone)){
    
    
    throw new ServiceException("805","请求phone失败");
}
//将响应转为JSON对象
JSONObject respPhoneObj = JSONObject.parseObject(respPhone);
JSONObject phoneObj = (JSONObject) respPhoneObj.get("phone_info");
if(phoneObj==null){
    
    
    throw new ServiceException("906","获取phone失败");
}
//获取手机号
String phone = phoneObj.getString("phoneNumber");

猜你喜欢

转载自blog.csdn.net/csdn_avatar_2019/article/details/126067917