小程序获取手机号

发布时间 2023-06-09 13:36:38作者: zno2

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

从基础库 2.21.2 开始,对获取手机号的接口进行了安全升级,以下是新版本接口使用指南。(旧版本接口目前可以继续使用,但建议开发者使用新版本接口,以增强小程序安全性)

因为需要用户主动触发才能发起获取手机号接口,所以该功能不由 API 来调用,需用 button 组件的点击来触发。另外,新版本接口不再需要提前调用wx.login进行登录。

注意:目前该接口针对非个人开发者,且完成了认证的小程序开放(不包含海外主体)。需谨慎使用,若用户举报较多或被发现在不必要场景下使用,微信有权永久回收该小程序的该接口权限。

 

获取access_token

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

HttpUtils.getD("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=<changeit>&secret=<changeit>");

 

结果:

{"access_token":"52_Hh8vb-7WBXjzoaveD3aBBwZ3VRg7lQ-CHtG_yH7knlx-Vop73rDBlvEbK6Cc96HVNeWnx86L9iTjHs7SeNlXtuI2eKuO6VdnOQwvCRTyp0Exn8ZABrykRLqTkM-qQo8M0MB9yGBqDp8xP7qJPLCcABASOF","expires_in":7200}

 

获取手机号

https://developers.weixin.qq.com/miniprogram/dev/api-backend/open-api/phonenumber/phonenumber.getPhoneNumber.html

curl 
-H "Accept: application/json"
-H "Content-type: application/json"
-X POST
-d '{"code": "e31968a7f94cc5ee25fafc2aef2773f0bb8c3937b22520eb8ee345274d00c144"}'
https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=ACCESS_TOKEN&

 或

    public static String getPhoneByCode(String code, String appid, String secret) {
        String body = null;
        try {
            Response d = HttpUtils.getD("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid="
                    + appid + "&secret=" + secret + "");
            String accessToken = JSONObject.parseObject(d.getBody()).getString("access_token");
            JSONObject jo = new JSONObject();
            jo.put("code", code);
            Response postD = HttpUtils.postD(
                    "https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=" + accessToken + "&",
                    Content.json(jo.toJSONString()));
            body = postD.getBody();
            return JSONObject.parseObject(body).getJSONObject("phone_info").getString("phoneNumber");
        } catch (Exception e) {
            log.error("获取手机号失败" + body,e);
            return null;
        }
    }

 

结果:

{"errcode":0,"errmsg":"ok","phone_info":{"phoneNumber":"15120076220","purePhoneNumber":"15120076220","countryCode":"86","watermark":{"timestamp":1641805502,"appid":"wx289e0c7f70450520"}}}