微信小程序登錄實現,前端+后端PHP代碼(前端獲得CODE,后端獲取微信用戶的OPEN ID 和 UNION ID)


說說獲取openid 和 union id 的條件
1.AppID(小程序ID);
2.AppSecret(小程序密鑰);
3.登錄時獲取code;

獲取流程:

1.公眾平台上找到AppID(小程序ID)和AppSecret(小程序密鑰);
公眾平台

2.微信小程序中調用API獲取code

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

示例代碼:

 wx.login({ success: function(res) { console.log(res.code)//這就是code });

 

3.code 換取 session_key和openid
用戶允許登錄后,回調內容會帶上 code(有效期五分鍾),開發者需要將 code 發送到開發者服務器后台,使用code 換取 session_key api,將 code 換成 openid 和 session_key

接口地址:GET 請求  https://api.weixin.qq.com/sns/jscode2session?appid=APPID&secret=SECRET&js_code=JSCODE&grant_type=authorization_code

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

接口


后台訪問微信服務器接口就能拿到openid 和 session_key, 至於會不會返回 union id ,需要有條件,見微信官方的文檔說明: https://developers.weixin.qq.com/miniprogram/dev/framework/open-ability/union-id.html

 

說明
文檔說不應該把openid或者session_key作為用戶標識;
我就不折騰了.直接用openid做唯一標識.沒啥毛病.

當然也可以按照官方文檔,后台生成session,以3rd_session為key,session_key+ opneid為value.

登錄時序圖

 

 

 

有人要問了,session_key 有啥用呢?見下面的回答

 

相關官方文檔列表:

小程序登錄:https://developers.weixin.qq.com/miniprogram/dev/framework/open-ability/login.html

前端獲得CODE:https://developers.weixin.qq.com/miniprogram/dev/api/open-api/login/wx.login.html

后端根據CODE獲得 OPEN ID 和 SESSION KEY : https://developers.weixin.qq.com/miniprogram/dev/api-backend/open-api/login/auth.code2Session.html

流程圖:

前端代碼:獲得CODE https://developers.weixin.qq.com/miniprogram/dev/api/open-api/login/wx.login.html

 

wx.login({
      success: function (res) {
        var code = res.code
        if (code) {
          that.globalData.code = code;
          globalData: {
            code: code
          }
          wx.request({
            url: 'https://www.nidedyuming.com/index.php/index/index/login',
            method: 'POST',
            data: {code: code},
            success: function (res) {
              that.globalData.openid = res.data.openid;
              console.log(res.data.openid);
            }
          })
        }
      }
    })

后端PHP:拿着CODE去獲取 OPEN ID 等信息 https://developers.weixin.qq.com/miniprogram/dev/api-backend/open-api/login/auth.code2Session.html

        function oauth2($code)
        {
            //$code = $_GET['code'];//小程序傳來的code值
            $url = 'https://api.weixin.qq.com/sns/jscode2session?appid="你的APPID"&secret="你的app密鑰"&js_code=' . $code . '&grant_type=authorization_code';
            //yourAppid為開發者appid.appSecret為開發者的appsecret,都可以從微信公眾平台獲取;
            $info = file_get_contents($url);//發送HTTPs請求並獲取返回的數據,推薦使用curl
            $json = json_decode($info);//對json數據解碼
            $arr = get_object_vars($json);
            // dump($arr);die;
            $openid = $arr['openid'];
            return $openid;
        }

 


免責聲明!

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



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