微信小程序获取手机号登录(Java后端)

1.添加依赖

        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
        </dependency>
        
        <dependency>
            <groupId>cn.hutool</groupId>
            <artifactId>hutool-all</artifactId>
            <version>5.4.0</version>
        </dependency>

2.获取手机号流程

1.前端请求getPhoneNumber方法获取code传给后端接口;
2.后端接口通过配置的appid、secretKey请求接口https://api.weixin.qq.com/cgi-bin/token获取access_token参数;
3.后端通过参数code和参数access_token,去请求接口https://api.weixin.qq.com/wxa/business/getuserphonenumber来获取手机号。

3.参数信息

@Data
public class WeChatPhoneDTO {
    // getPhoneNumber接口返回的code
    private String code;
    // 小程序的appid(一般是在程序中配置,不需要前端传参)
    private String appid;
    // 小程序的secretKey(一般是在程序中配置,不需要前端传参)
    private String secretKey;
}

@Data
public class WeChatPhoneInfo {
    // 用户绑定的手机号(国外手机号会有区号)
    private String phoneNumber;
    // 没有区号的手机号
    private String purePhoneNumber;
    // 区号
    private String countryCode;
    // 数据水印
    private String watermark;
}

4.后端发请求的util的工具类

public class WeChatUtil {
    /**
     * 请求微信接口服务,获取小程序全局唯一后台接口调用凭据(access_token)
     * https://developers.weixin.qq.com/miniprogram/dev/api-backend/open-api/access-token/auth.getAccessToken.html
     *
     * @param appid
     * @param secretKey
     * @return
     */
    public static JSONObject getAccessToken(String appid, String secretKey) {
        String result = null;
        try {
            String baseUrl = "https://api.weixin.qq.com/cgi-bin/token";
            HashMap<String, Object> requestParam = new HashMap<>();
            // 小程序 appId
            requestParam.put("grant_type", "client_credential");
            // 小程序唯一凭证id appid:(换成自己的)
            requestParam.put("appid", appid);
            // 小程序 appSecret(小程序的唯一凭证密钥,换成自己的)
            requestParam.put("secret", secretKey);
            // 发送GET请求读取调用微信接口获取openid用户唯一标识
            result = HttpUtil.get(baseUrl, requestParam);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return JSONUtil.parseObj(result);
    }

    /**
     * 请求微信接口服务,用code换取用户手机号(每个code只能使用一次,code的有效期为5min)
     * https://developers.weixin.qq.com/miniprogram/dev/api-backend/open-api/phonenumber/phonenumber.getPhoneNumber.html
     *
     * @param code
     * @param accessToken
     * @return
     */
    public static JSONObject getPhoneNumber(String code, String accessToken) {
        String result = null;
        try {
            // 接口调用凭证:accessToken
            String baseUrl = "https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=" + accessToken;
            HashMap<String, Object> requestParam = new HashMap<>();
            // 手机号调用凭证
            requestParam.put("code", code);
            // 发送post请求读取调用微信接口获取openid用户唯一标识
            String jsonStr = JSONUtil.toJsonStr(requestParam);
            HttpResponse response = HttpRequest.post(baseUrl)
                    .header(Header.CONTENT_ENCODING, "UTF-8")
                    // 发送json数据需要设置contentType
                    .header(Header.CONTENT_TYPE, "application/x-www-form-urlencoded")
                    .body(jsonStr)
                    .execute();
            if (response.getStatus() == HttpStatus.HTTP_OK) {
                result = response.body();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return JSONUtil.parseObj(result);
    }
}

5.获取手机号的接口

@RestController
@RequestMapping("/login")
public class WeChatUserLoginController {
    /**
     * 用前端请求接口获取的code换取用户手机号
     * 前端需要请求的接口:https://developers.weixin.qq.com/miniprogram/dev/framework/open-ability/getPhoneNumber.html
     * @param weChatPhone
     * @return
     */
    @PostMapping("/phone")
    public String getPhone(@RequestBody WeChatPhoneDTO weChatPhone){
        // 1.请求微信接口服务,获取accessToken
        JSONObject accessTokenJson = WeChatUtil.getAccessToken(weChatPhone.getAppid(), weChatPhone.getSecretKey());
        String accessToken = accessTokenJson.get("access_token",String.class);
        // 2.请求微信接口服务,获取用户手机号信息
        JSONObject phoneNumberJson = WeChatUtil.getPhoneNumber(weChatPhone.getCode(), accessToken);
        WeChatPhoneInfo phoneInfo = phoneNumberJson.get("phone_info", WeChatPhoneInfo.class);
        return phoneInfo.getPurePhoneNumber();
    }
}

  • 7
    点赞
  • 17
    收藏
    觉得还不错? 一键收藏
  • 7
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 7
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值