0
点赞
收藏
分享

微信扫一扫

新老版本根据微信小程序api获取手机号

玩物励志老乐 2022-01-13 阅读 195

新版本:

  1. 第一步,获取Access_token
	我使用的是RestTemplate的get、post方法进行访问
	第一个接口要获取access_token
	根据官方文档,Get方式提交,将appid,grant_type,secret参数传过去,获取access_token
	https://api.weixin.qq.com/cgi-bin/token?grant_type=xx&appid=xx&secret=xx

在这里插入图片描述
2. 第二步

   获取到access_token以后进行第二个接口访问
    String url="https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token="+accessToken;
注意:微信小程序新改版api,access_token要在地址栏中进行传递,code放在body中进行传递
code:前端点击获取code按钮,将code传递给后端接口
末尾有完整代码,没有耐心可移至末尾。



// 注意:前端获取code的按钮要注意,老版本获取的code是通过wx.login()获取,如采用新版本前端也要更新获取code按钮
 @ResponseBody
    @PostMapping("getPhones")
    public RespInfo getPhoneBycode(@RequestBody PhoneForm phoneForm) throws Exception {
        Map<String,String> params=new HashMap<>();
        params.put("grant_type",grant_type);
        params.put("appid",appid);
        params.put("secret",appsecret);
        ResponseEntity<String> responseEntity=restTemplate.getForEntity("https://api.weixin.qq.com/cgi-bin/token?grant_type={grant_type}&appid={appid}&secret={secret}",String.class,params);
        Map map = JSONObject.parseObject(responseEntity.getBody(), Map.class);
        if(!StringUtils.isEmpty(map.get("errcode"))){
            return RespInfo.mobiError("获取token参数有误");
        }
        if(!StringUtils.isEmpty(map.get("access_token"))){
            String accessToken=map.get("access_token").toString();
            String code=phoneForm.getCode();

            Map<String,String> param = new HashMap<>();
            if(!StringUtils.isEmpty(code)){
                param.put("code",code);
            }
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON);
            headers.set("Accept", "application/json");
            HttpEntity<Map<String, String>> httpEntity = new HttpEntity< Map<String, String>>(param,headers);
            String url="https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token="+accessToken;
            ResponseEntity<String> postResponseEntity=restTemplate.postForEntity(url,httpEntity,String.class);
            System.out.println(postResponseEntity.getBody());
            Map postMap=JSONObject.parseObject(postResponseEntity.getBody(),Map.class);
            if(!StringUtils.isEmpty(postMap.get("errcode"))){
                String errcode=postMap.get("errcode").toString();
                if(errcode.equals("-1")){
                    return RespInfo.mobiError("系统繁忙,请稍后重试");
                }
                if(errcode.equals("40029")){
                    return RespInfo.mobiError("code不存在或已过期,请重试");
                }
                if(errcode.equals("40013")){
                    return RespInfo.mobiError("不合法AppId");
                }
                if(errcode.equals("0")){
                    return RespInfo.mobiSuccess(postMap);
                }
            }
        }
        return RespInfo.mobiError("未获取到手机号");
    }



举报

相关推荐

0 条评论