微信小程序:如何獲取openid?


官方解釋:https://developers.weixin.qq.com/community/develop/article/doc/000c80906b4210625f3bde3775bc13

我們看看不使用雲開發的情況:

第一步、調用wx.login獲取code,再攜帶code像后台發起請求

(1)、首先需要在微信小程序調用登錄開放接口 wx.login() 獲取用戶登陸憑證code。

onLaunch() {
    // 登錄
    wx.login({
      success: res => {
        console.info(res);
        // 發送 res.code 到后台換取 openId, sessionKey, unionId
      }
    })
  },

res的結果如下:

 

注意:這里的success雖然是接口調用成功的回調函數,但是它只是參數。

success回調函數也有參數res,res的屬性為code

(2)、向自己的服務器發送請求,並將code一起發送過去。

在App.js的onLaunch生命周期函數中調用wx.login接口

onLaunch() {
      //隱藏系統tabbar
      this.hideTabBar();
      //獲取設備信息
      this.getSystemInfo();
  
      // 登錄
      const requestUrl = this.globalData.apiBaseUrl + '/api/login/code2session';
      wx.login({
        success: res => {
          // 發送 res.code 到后台換取 openId, sessionKey, unionId
          console.info(res)
          wx.request({
            url: requestUrl,
            method:"POST",
            data:{
              "code":res.code
            },
            header:{
              "Content-Type":"application/json"
            },
            success(res){
              console.log(res)
            }
          })
        }
      })
  },

res結果如下:

從wx.login(Object object)官方的API文檔:https://developers.weixin.qq.com/miniprogram/dev/api/open-api/login/wx.login.html 可知,

調用接口獲取登錄憑證(code)。通過憑證進而換取用戶登錄態信息,包括用戶在當前小程序的唯一標識(openid)、微信開放平台帳號下的唯一標識(unionid,若當前小程序已綁定到微信開放平台帳號)及本次登錄的會話密鑰(session_key)等。

接口的參數:object

在App.js的onLaunch生命周期函數中調用wx.login接口

onLaunch: function () {// 登錄
    wx.login({
        success: res => {
            // 發送 res.code 到后台換取 openId 驗證平台賬號是否登錄綁定過
            var that = this;
            wx.request({
                method: 'GET',
                url: this.globalData.serverApi + "/mobileApi/user/checkBind?code="+res.code,
                header: {
                    'content-type': 'application/json'
                },
                success (res) {
                    if(res.data.code == 301){
                        //未登錄
                        var openId = res.data.openId;
                        wx.reLaunch({
                          url: '/pages/login/login?openId='+openId
                        })
                    }else if(res.data.code == 1){
                        //已登錄
                        that.globalData.userInfo = res.data.userInfo;
                        that.globalData.token = res.data.token;
                    }else if(res.data.code == 0){
                        //獲取openId失敗
                        wx.showToast({
                          title: res.data.msg,
                          icon: 'none',
                          duration: 2000
                        })
                    }

                    // 由於 checkBind 是網絡請求,可能會在 Page.onLoad 之后才返回
                    // 所以此處加入 callback 以防止這種情況
                    if (that.checkBindCallback) {
                      that.checkBindCallback(res)
                    }
                }
            })
      }
    })
  },

二、在自己的后台服務端調用auth.code2Session接口

官方文檔:https://developers.weixin.qq.com/miniprogram/dev/api-backend/open-api/login/auth.code2Session.html

登錄憑證校驗。通過 wx.login 接口獲得臨時登錄憑證 code 后傳到開發者服務器調用此接口完成登錄流程。

請求地址:

GET https://api.weixin.qq.com/sns/jscode2session?appid=APPID&secret=SECRET&js_code=JSCODE&grant_type=authorization_code

后台代碼

/**
     * 根據code獲取openId去檢查是否綁定平台用戶
     * @param code
     * @return JSONObject
     */
    @GetMapping("/checkBind")
    public JSONObject checkBind(@RequestParam String code){
        JSONObject object = new JSONObject();
        String getOpenIdUrl = getOpenIdURL.replace("APPID",appId).replace("SECRET",appSecret).replace("JSCODE",code);
        try {
            //獲取openId信息
            String resultStr = httpUtil.doGet(getOpenIdUrl,null,null);
            JSONObject resultObj = JSON.parseObject(resultStr);
            if(StringUtils.isNotEmpty(resultObj.getString("openid"))){
                //根據openId判斷是否和平台用戶綁定
                String openId = resultObj.getString("openid");
                Result result = appletUserService.appletUserQuery(openId);
                if(result.isSuccess()){
                    //已綁定
                    AppletUser appletUser = (AppletUser)result.getData();
                    String token = appletUser.getToken();
                    //獲取用戶信息
                    User userInfo = (User)redisUtilService.get(pre + "TOKEN" + token);
                    //根據登錄token獲取后台的權限菜單
            ...
                    object.put("token",token);
                    object.put("userInfo",userInfo);
                    object.put("code",ResultCode.SUCCESS);
                    object.put("msg","已經登錄");
                }else{
                    //未綁定
                    object.put("openId",openId);
                    object.put("code",ResultCode.NO_LOGIN);
                    object.put("msg","未登錄");
                }
            }else{
                object.put("code",ResultCode.FAILURE);
                object.put("msg",resultObj.getString("errmsg"));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return object;
    }

其中getOpenIdURL為:https://api.weixin.qq.com/sns/jscode2session?appid=APPID&secret=SECRET&js_code=JSCODE&grant_type=authorization_code

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM