微信小程序中获取用户的唯一标识openid,用于做业务判断处理

我是小程序加载时就调用,执行顺序如下:
1、进入小程序时会调用onLoad,onLoad函数是监听页面加载的;
2、在onLoad引用wx.login,获取一个临时访问code,当前code有效时间为5分钟,并且只能使用一次;
3、将code传入后端,在后端访问https://api.weixin.qq.com/sns/jscode2session?appid=APP_ID&secret=SECRET&js_code=code&grant_type=authorization_code链接,获取openId并且关联用户;

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var tempThis = this;
    wx.login({
      success: function (res) {
        wx.request({
          url: 'https://127.0.0.1/student/getStudentJointInfo', //接口地址
          data: { wxId: res.code },//res.code就是当前调用wx.login生成的,有效时间5分钟
          success: function (d) {
            if (d.data == null || d.data == "") {
              tempThis.setData({ hiddenmodalput: false, wxId: res.code });//意味着没有关联需要进行关联
              console.log(d.data);
            } else {
              tempThis.setData({ phoneNum: d.data, wxId: res.code });//意味着没有关联需要进行关联
            }
          }
        });
      }
    });
  },

后端访问代码

    /**
     * 获取微信用户唯一标识ID
     *
     * @param wxId 也就是wx.login生成的code,有效时间五分钟,只能使用一次
     * @return 验证成功则返回openid,失败则为null
     */
    public static String getOpenId(String wxId) {
        String url = new StringBuilder("https://api.weixin.qq.com/sns/jscode2session?appid=").append(APP_ID)
                .append("&secret=").append(SECRET)
                .append("&js_code=").append(wxId).append("&grant_type=authorization_code").toString();
        String body = OkHttpClientUtil.getBody(url, 8L, new HashMap<>());
        JSONObject jsonObject = JSONObject.fromObject(body);
        if (!jsonObject.containsKey("openid")) return null;
        return jsonObject.getString("openid");
    }
  • 4
    点赞
  • 21
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Acmen-zym

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值