【微信小程序】获取用户openid与电话

331 阅读2分钟

携手创作,共同成长!这是我参与「掘金日新计划 · 8 月更文挑战」的第31天,点击查看活动详情 >>

本文将介绍微信小程序如何获得用户的openid与获取用户的电话授权。

前置知识

  • 会开发Java后台及微信小程序
  • 知道openid含义
  • 有企业商户认证(腾讯要求只有企业号才可以调用授权电话方法

openid获取

在新版本的微信小程序中,需要从微信小程序请求后台的接口,后台再请求微信的服务,以此来获得用户的openid

  • 我们首先需要在微信小程序控制台获取appid及APPSECRET,放在配置文件中(此处用spring举例子
  • 请求微信提供的接口
  • 微信返回包含openid的结果 注意:在调用微信提供的接口之前需要参数code码,code是前端请求微信获得的,有时效性。 前端获取code码及请求后端接口
wx.login({
      success(res) {
        if (res.code) {
          getOpenid(res.code)
            .then(res => {
              if (res.data.result) {
                wx.setStorage({
                  key: "openid",
                  data: res.data.result,
                })
                _this.setData({
                  openid: res.data.result,
                })
                console.log("后台" + res.data.result);
              } else {
                $wuxToast().show({
                  type: 'text',
                  duration: 2500,
                  color: '#57a6bec0',
                  text: '请检查网络设置',
                  success: () => console.log('文本提示')
                })
              }
            })
        }
      }
    })

  • 后端接口:
public String getOpenid(String code) {
    String url = String.format("https://api.weixin.qq.com/sns/jscode2session?appid=%s&secret=%s&js_code=%s&grant_type=authorization_code", APPID, APPSECRET, code);
    ResponseEntity<String> response = restTemplate.getForEntity(url, String.class);
    JSONObject resObj = JSONObject.parseObject(response.getBody());
    return resObj.get("openid") != null ? (String) resObj.get("openid") : null;
}

参照微信小程序官方文档,后台携带 APPID, APPSECRET, code进行请求微信服务端。

获取手机号

小程序获取手机号首先需要获取一个AccessToken,后携带此token去请求获取手机号的接口,其中code码也需要从前端获取,前端在请求getUserPhone方法时需要携带获取的code码,此方法是post请求,code需要放在请求体中,使用json格式进行请求。

public String getAccessToken() {
    String url = String.format("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=%s&secret=%s", APPID, APPSECRET);
    ResponseEntity<String> response = restTemplate.getForEntity(url, String.class);
    JSONObject resObj = JSONObject.parseObject(response.getBody());
    return resObj.get("access_token") != null ? (String) resObj.get("access_token") : null;
}

public String getUserPhone(String code){
    String url = "https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token="+getAccessToken();
    Map<String, String> map = new HashMap<>(1);
    map.put("code", code);
    String json= JSON.toJSONString(map);
    String result = HttpRequest.post(url)
            .body(json)
            .execute()
            .body();
    JSONObject resObj = JSONObject.parseObject(result);
    return (String) resObj.get("phone_info");
}