微信小程序获取手机号的完整实例(Java后台实现)

网友投稿 863 2022-07-23


目录小程序后端接口总结

小程序端:https://developers.weixin.qq.com/miniprogram/dev/framework/open-ability/getPhoneNumber.html

获取手机号码:https://developers.weixin.qq.com/miniprogram/dev/api-backend/open-api/phonenumber/phonenumber.getPhoneNumber.html

获取token:https://developers.weixin.qq.com/miniprogram/dev/api-backend/open-api/access-token/auth.getAccessToken.html

现在的获取手机号码变得很简单,不需要像之前那样去根据偏移量解析密文了,现在直接使用code去微信后台换取号码即可,这里简单记录一下。

小程序

首先小程序端很简单,直接调用API获取code即可,然后将code作为参数传递给接口。

Page({

getPhoneNumber (e) {

console.log(e.detail.code)

}

})

参数类型说明最低版本codeString动态令牌。可通过动态令牌换取用户手机号。使用方法详情 phonenumber.getPhoneNumber 接口

后端接口

开发接口的时候需要注意以下几点:

首先需要获取一个access_tokenaccess_token是直接跟在url后面的,不需要作为参数处理code参数是json格式的

调用地址如下:

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

请求参数:

属性类型默认值必填说明access_token / cloudbase_access_tokenstring 是接口调用凭证codestring 是手机号获取凭证

了解了这些之后,我们就可以直接编写我们的接口了。

@Autowired

private RestTemplate restTemplate;

@PostMapping("/wx/getPhone")

public R getPhone(@RequestParam(value = "code", required = false) String code) {

// 获取token

String token_url = String.format("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=%s&secret=%s", WXConstant.APPID, WXConstant.SECRET);

JSONObject token = JSON.parseObject(HttpUtil.get(token_url));

// 使用前端code获取手机号码 参数为json格式

String url = "https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=" + token.getString("access_token");

Map paramMap = new HashMap<>();

paramMap.put("code", code);

HttpHeaders headers = new HttpHeaders();

HttpEntity> httpEntity = new HttpEntity<>(paramMap, headers);

System.out.println(httpEntity);

ResponseEntity response = restTemplate.postForEntity(url, httpEntity, Object.class);

return R.ok().message("获取手机号码成功.").data(response.getBody());

}

这里获取token的时候我是直接使用Hutool工具包提供的工具类开发的,大家可以自行引入,

cn.hutool

hutool-all

5.7.16

然后,获取手机号码这里我是采用RestTemplate来调用的,相关配置文件如下:

@Configuration

public class RestTemplateConfig {

@Bean

public RestTemplate restTemplate() {

return new RestTemplate();

}

@Bean

public ClientHttpRequestFactory simpleClientHttpRequestFactory() {

SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory();

factory.setReadTimeout(5000);//ms

factory.setConnectTimeout(15000);//ms

http:// return factory;

}

}

总结


版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:Java Agent探针技术详解示例
下一篇:Java开发学习之Bean的生命周期详解
相关文章

 发表评论

暂时没有评论,来抢沙发吧~