Home  >  Article  >  Backend Development  >  Mini program and ThinkPHP5 combined to achieve login status (code attached)

Mini program and ThinkPHP5 combined to achieve login status (code attached)

不言
不言Original
2018-08-11 14:00:3210804browse

The content of this article is about the combination of small programs and ThinkPHP5 to achieve login status (with code). It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

In WeChat mini programs, there are generally three login methods:
1. Log in using WeChat account
2. Register and log in with your own account
3. Use other third-party platform accounts to log in

WeChat account login process:

1. The applet obtains the code through wx.login and sends it to the backend, which exchanges the session_key and openid;
2. Randomly generate a string as sessionid (key), session_key and openid as value, and store them in redis. For safety,
a timeout should be set when saving;
3 . The client will store the returned sessionid in storage, and when calling background services that require login for access,
You can take out the sessionid saved in storage and carry it in the request, and obtain it in the background code After the sessionid,
Check whether the sessionid exists in redis. If it exists, it is confirmed that the session is valid.
Continue the subsequent code execution, otherwise error handling will be performed.

This article uses free account registration and login. The main ideas and processes are as follows:

1. To enter the mini program, first obtain the code through wx.login, and send it to the backend through the backend interface. The backend uses this to WeChat API exchanges session_key and openid;
2. Determine whether the openid exists in the database [unique identification, needs to be bound to the account (mobile phone number)],
-- If the openid does not exist in the database (it means there is no such account) ):
Determine whether the passed mobile phone number is empty (the mobile phone number will be saved in the global variable when logging in). If it is not empty, it means you have just logged in, and then bind openid and openid_time (current time) ,
If the mobile phone number is also empty, it means that you have not logged in, then the login failure message will be returned, causing the client to jump to the login page;
-- If there is the openid in the database (it means there is a corresponding mobile phone in the database ),
Determine whether openid_time is greater than 4 hours from the present time. If it is greater, return login failure information and cause the client to jump to the login page;
If it is less than, update openid_time to the current time, and then return login success information and mobile phone number.
3. Login page: Determine whether the mobile phone number exists in the database. If it exists, update openid_time to the current time. If it does not exist, add the user with the mobile phone number. Then jump to the home page and execute the wx.login method. The login is successful and the login status remains.

Detailed process:

Step 1: When entering the mini program, first obtain the code through wx.login, and send it to the backend through the backend interface. The backend exchanges this for session_key and openid with the WeChat API;

var user_phone = app.globalData.user_phone;
wx.login({
    success: res => {      
    // 发送 res.code 到后台换取 openId, sessionKey, unionId
      wx.request({
        url: 'http://www.tphoutai.com/wx/index', 
        data: {
          code: res.code,
          user_phone: user_phone,
        },
        success: function (result) {
          var res = result.data;
          console.log(res);          
          if(res.sendsure == 0){
            wx.reLaunch({
              url: '../login/login',
            })
          }else if(res.sendsure == 1){
            wx.reLaunch({
              url: '../index/index',
            })
          }
        }
      })
    }
  })

Step 2: Determine whether the openid exists in the database [unique identification, needs to be bound to the account (mobile phone number)];

// 后台代码:
public function index(Request $request){
        $url = "https://api.weixin.qq.com/sns/jscode2session";        
        // 参数
        $params['appid']= '小程序的appid';        
        $params['secret']= '小程序的AppSecret';        
        $params['js_code']= $request -> param('code');        
        $params['grant_type']= 'authorization_code';        
        $user_phone= $request -> param('user_phone');        
        // 微信API返回的session_key 和 openid
        $arr = httpCurl($url, $params, 'POST');        
        $arr = json_decode($arr,true);        
        // 判断是否成功
        if(isset($arr['errcode']) && !empty($arr['errcode'])){            
        return json(['code'=>'2','message'=>$arr['errmsg'],"result"=>null]);
        }        
        $openid = $arr['openid'];        
        $session_key = $arr['session_key'];        
        // 从数据库中查找是否有该openid
        $is_openid = Db::table('user_info')->where('openid',$openid)->find();        
        // 如果openid存在,更新openid_time,返回登录成功信息及手机号
        if($is_openid){            
        // openid存在,先判断openid_time,与现在的时间戳相比,如果相差大于4个小时,则则返回登录失败信息,使客户端跳转登录页,如果相差在四个小时之内,则更新openid_time,然后返回登录成功信息及手机号;
            // 根据openid查询到所在条数据
            $data = Db::table('user_info')->where('openid',$openid)->find();            
            // 计算openid_time与现在时间的差值
            $time = time() - $data['openid_time'];            
            $time = $time / 3600;            
            // 如果四个小时没更新过,则登陆态消失,返回失败,重新登录
            if($time > 4){                
            return json(['sendsure'=>'0','message'=>'登录失败',]);
            }else{                
            // 根据手机号更新openid时间
                $update = Db::table('user_info')->where('openid', $openid)->update(['openid_time' => time()]);                
                // 判断是否更新成功
                if($update){                    
                return json(['sendsure'=>'1','message'=>'登录成功','user_phone' => $data['user_phone']]);
                }else{                    
                return json(['sendsure'=>'0','message'=>'登录失败']);
                }
            }        
            // openid不存在时
        }else{            
        // dump($user_phone);
            // 如果openid不存在, 判断手机号是否为空
            if(isset($user_phone) && !empty($user_phone)){                
            // 如果不为空,则说明是登录过的,就从数据库中找到手机号,然后绑定openid,+时间

                // 登录后,手机号不为空,则根据手机号更新openid和openid_time
                $update = Db::table('user_info')
                    ->where('user_phone', $user_phone)
                    ->update([                        
                    'openid'  => $openid,                        
                    'openid_time' => time(),
                    ]);                
                    if($update){                    
                    return json(['sendsure'=>'1','message'=>'登录成功',]);
                }
            }else{                
            // 如果也为空,则返回登录失败信息,使客户端跳转登录页
                return json(['sendsure'=>'0','message'=>'读取失败',]);
            }
        }
    }

Step 3: Login page: After successful login, jump to the home page for execution wx.login method, then the login is successful and the login status is maintained.

// 前台登录
    wx.request({
      url: 'http://www.tphoutai.com/wx/login', 
      data: {
        user_phone: user_phone
      },
      success: function (result) {
        var res = result.data;        
        if (res.sendsure == 1){
          app.globalData.user_phone = that.data.user_phone;
          wx.reLaunch({
            url: '../loading/loading',
          })
        }
      }
    })
rrree
Method to obtain sessionkey and openid based on WeChat API
// 后台登录方法
    public function login(Request $request){

        // 获取到前台传输的手机号
        $user_phone = $request -> param('user_phone');        
        // 判断数据库中该手机号是否存在
        $is_user_phone = Db::table('user_info')->where('user_phone',$user_phone)->find();        
        if(isset($is_user_phone) && !empty($is_user_phone)){            
        // 登录时,数据库中存在该手机号,则更新openid_time
            $update = Db::table('user_info')
                    ->where('user_phone', $user_phone)
                    ->update([                        
                    'openid_time' => time(),
                    ]);            
                    if($update){                
                    return json(['sendsure'=>'1','message'=>'登录成功',]);
            }
        }else{            
        $data = [                
        "user_phone" => $user_phone,                
        "pass" => '12345'
            ];            
            // 如果数据库中不存在该手机号,则进行添加
            Db::table('user_info')->insert($data);
        }        return json(['sendsure'=>'1','message'=>'登录成功',]);
    }

Test results:
Mini program and ThinkPHP5 combined to achieve login status (code attached)

Related recommendations:

Solve the naming problem of belongsToMany() module name in thinkphp5

Detailed analysis of the adapter mode in php (with code)

The above is the detailed content of Mini program and ThinkPHP5 combined to achieve login status (code attached). For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn