溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

微信小程序的登錄功能如何實現(xiàn)

發(fā)布時間:2022-04-18 15:34:34 來源:億速云 閱讀:143 作者:iii 欄目:開發(fā)技術(shù)

這篇“微信小程序的登錄功能如何實現(xiàn)”文章的知識點大部分人都不太理解,所以小編給大家總結(jié)了以下內(nèi)容,內(nèi)容詳細,步驟清晰,具有一定的借鑒價值,希望大家閱讀完這篇文章能有所收獲,下面我們一起來看看這篇“微信小程序的登錄功能如何實現(xiàn)”文章吧。

微信小程序登錄

一. 小程序不支持cookie會話

  1. 通過傳遞與檢驗3rd_session來保持會話

  2. 3rd_session可以執(zhí)行‘`head -n 80 /dev/urandom | tr -dc A-Za-z0-9 | head -c 168`該命令生成

  3. 使用Redis或者數(shù)據(jù)庫存儲session

  4. 生成的3rd_session發(fā)送給客戶端,寫入storage

  5. 客戶端的每次請求必須帶上3rd_session

二、加密數(shù)據(jù)解碼

  1. $iv,$code是被加密過的數(shù)據(jù),由于請求過程中因為編碼原因+號變成了空格,所以我們需要用下面的方法轉(zhuǎn)換回來

 

function define_str_replace($data){
    return str_replace(' ','+',$data);
  }

 三、例子:

php

  // 微信登錄
  public function weixin_login(){
    $session_db=D('Session');
    $session_id=I('get.sessionid','');
    $session=$session_db->getSession($session_id);
    if( !empty( $session ) ){
      $this->ajaxReturn(['error_code'=>0,'sessionid'=>$session_id]);
    }else{
      $iv=define_str_replace(I('get.iv')); //把空格轉(zhuǎn)成+
      $encryptedData=urldecode(I('get.encryptedData'));  //解碼
      $code=define_str_replace(I('get.code')); //把空格轉(zhuǎn)成+
      $msg=D('Weixin')->getUserInfo($code,$encryptedData,$iv); //獲取微信用戶信息(openid)
      if($msg['errCode']==0){
        $open_id=$msg['data']->openId;
        $users_db=D('Users');
        $info=$users_db->getUserInfo($open_id);
        if(!$info||empty($info)){
          $users_db->addUser(['open_id'=>$open_id,'last_time'=>['exp','now()']]); //用戶信息入庫
          $info=$users_db->getUserInfo($open_id);                  //獲取用戶信息
          $session_id=`head -n 80 /dev/urandom | tr -dc A-Za-z0-9 | head -c 168`;  //生成3rd_session
          $session_db->addSession(['uid'=>$info['id'],'id'=>$session_id]); //保存session
        }
        if($session_id){
          $this->ajaxReturn(['error_code'=>0,'sessionid'=>$session_id]);  //把3rd_session返回給客戶端
        }else{
          $this->ajaxReturn(['error_code'=>0,'sessionid'=>$session_db->getSid($info['id'])]);
        }
        
      }else{
        $this->ajaxReturn(['error_code'=>'用戶信息獲取失敗!']);
      }
      
    }
  }

獲取微信信息模型(包括信息解密,官方例子點擊下載)

require_once ABS_APP_PATH.'/Addon/Aes/wxBizDataCrypt.php';
class WeixinModel{
  // 獲取微信的用戶信息(openid)
  public function getUserInfo($code,$encryptedData,$iv){
    $appid=C('appid');
    $secret=C('secret');
    $grant_type='authorization_code';
    $url='https://api.weixin.qq.com/sns/jscode2session';
    $url= sprintf("%s?appid=%s&secret=%s&js_code=%s&grant_type=%",$url,$appid,$secret,$code,$grant_type);
    $user_data=json_decode(file_get_contents($url));
    $session_key= define_str_replace($user_data->session_key);
    $data="";
    $wxBizDataCrypt=new \WXBizDataCrypt($appid,$session_key);
    $errCode=$wxBizDataCrypt->decryptData($encryptedData,$iv,$data);
    return ['errCode'=>$errCode,'data'=>json_decode($data),'session_key'=>$session_key];
  }
  }

javascript

  getUserInfo: function(cb) {
    var that = this
    if (this.globalData.userInfo) {
      typeof cb == "function" && cb(this.globalData.userInfo)
    } else {
      //調(diào)用登錄接口
      wx.login({
        success: function(r) {
          wx.getUserInfo({
            success: function(res) {
              that.login({
                code: r.code,
                iv: res.iv,
                encryptedData: encodeURIComponent(res.encryptedData),
              })
              that.globalData.userInfo = res.userInfo
              typeof cb == "function" && cb(that.globalData.userInfo)
            }
          })
        }
      })
    }
  },
  login: function(param) {
    wx.request({
      url: this.requestUrl('Index/weixin_login'),
      data: param,
      header: {
        'content-type': "application/json",
      },
      success: function(res) {
        var data = JSON.parse(res.data.trim());
        wx.setStorageSync('sessionid', data.sessionid);
      }
    })
  },

以上就是關(guān)于“微信小程序的登錄功能如何實現(xiàn)”這篇文章的內(nèi)容,相信大家都有了一定的了解,希望小編分享的內(nèi)容對大家有幫助,若想了解更多相關(guān)的知識內(nèi)容,請關(guān)注億速云行業(yè)資訊頻道。

向AI問一下細節(jié)

免責聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI