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

所需工具:

Java

聪明的大脑

勤劳的双手

 

注意:本站只提供教程,不提供任何成品+工具+软件链接,仅限用于学习和研究,禁止商业用途,未经允许禁止转载/分享等

 

教程如下

小程序端: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作为参数传递给接口。

 	<button open-type="getPhoneNumber" bindgetphonenumber="getPhoneNumber"></button>
 	Page({
 	     getPhoneNumber (e) {
 	     console.log(e.detail.code)
 	     }
 	})
参数 类型 说明 最低版本
code String 动态令牌。可通过动态令牌换取用户手机号。使用方法详情 phonenumber.getPhoneNumber 接口

后端接口

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

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

调用地址如下:

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

请求参数:

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

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

 	@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<String, String> paramMap = new HashMap<>();
 	     paramMap.put("code", code);
 	     HttpHeaders headers = new HttpHeaders();
 	     HttpEntity<Map<String, String>> httpEntity = new HttpEntity<>(paramMap, headers);
 	     System.out.println(httpEntity);
 	     ResponseEntity<Object> response = restTemplate.postForEntity(url, httpEntity, Object.class);
 	     return R.ok().message("获取手机号码成功.").data(response.getBody());
 	}

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

 	<dependency>
 	     <groupId>cn.hutool</groupId>
 	     <artifactId>hutool-all</artifactId>
 	     <version>5.7.16</version>
 	</dependency>

然后,获取手机号码这里我是采用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
 	     return factory;
 	     }
 	}

 

 

标签

发表评论