search
HomeBackend DevelopmentPHP TutorialMini program and ThinkPHP5 combined to achieve login status (code attached)

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
PHP Dependency Injection Container: A Quick StartPHP Dependency Injection Container: A Quick StartMay 13, 2025 am 12:11 AM

APHPDependencyInjectionContainerisatoolthatmanagesclassdependencies,enhancingcodemodularity,testability,andmaintainability.Itactsasacentralhubforcreatingandinjectingdependencies,thusreducingtightcouplingandeasingunittesting.

Dependency Injection vs. Service Locator in PHPDependency Injection vs. Service Locator in PHPMay 13, 2025 am 12:10 AM

Select DependencyInjection (DI) for large applications, ServiceLocator is suitable for small projects or prototypes. 1) DI improves the testability and modularity of the code through constructor injection. 2) ServiceLocator obtains services through center registration, which is convenient but may lead to an increase in code coupling.

PHP performance optimization strategies.PHP performance optimization strategies.May 13, 2025 am 12:06 AM

PHPapplicationscanbeoptimizedforspeedandefficiencyby:1)enablingopcacheinphp.ini,2)usingpreparedstatementswithPDOfordatabasequeries,3)replacingloopswitharray_filterandarray_mapfordataprocessing,4)configuringNginxasareverseproxy,5)implementingcachingwi

PHP Email Validation: Ensuring Emails Are Sent CorrectlyPHP Email Validation: Ensuring Emails Are Sent CorrectlyMay 13, 2025 am 12:06 AM

PHPemailvalidationinvolvesthreesteps:1)Formatvalidationusingregularexpressionstochecktheemailformat;2)DNSvalidationtoensurethedomainhasavalidMXrecord;3)SMTPvalidation,themostthoroughmethod,whichchecksifthemailboxexistsbyconnectingtotheSMTPserver.Impl

How to make PHP applications fasterHow to make PHP applications fasterMay 12, 2025 am 12:12 AM

TomakePHPapplicationsfaster,followthesesteps:1)UseOpcodeCachinglikeOPcachetostoreprecompiledscriptbytecode.2)MinimizeDatabaseQueriesbyusingquerycachingandefficientindexing.3)LeveragePHP7 Featuresforbettercodeefficiency.4)ImplementCachingStrategiessuc

PHP Performance Optimization Checklist: Improve Speed NowPHP Performance Optimization Checklist: Improve Speed NowMay 12, 2025 am 12:07 AM

ToimprovePHPapplicationspeed,followthesesteps:1)EnableopcodecachingwithAPCutoreducescriptexecutiontime.2)ImplementdatabasequerycachingusingPDOtominimizedatabasehits.3)UseHTTP/2tomultiplexrequestsandreduceconnectionoverhead.4)Limitsessionusagebyclosin

PHP Dependency Injection: Improve Code TestabilityPHP Dependency Injection: Improve Code TestabilityMay 12, 2025 am 12:03 AM

Dependency injection (DI) significantly improves the testability of PHP code by explicitly transitive dependencies. 1) DI decoupling classes and specific implementations make testing and maintenance more flexible. 2) Among the three types, the constructor injects explicit expression dependencies to keep the state consistent. 3) Use DI containers to manage complex dependencies to improve code quality and development efficiency.

PHP Performance Optimization: Database Query OptimizationPHP Performance Optimization: Database Query OptimizationMay 12, 2025 am 12:02 AM

DatabasequeryoptimizationinPHPinvolvesseveralstrategiestoenhanceperformance.1)Selectonlynecessarycolumnstoreducedatatransfer.2)Useindexingtospeedupdataretrieval.3)Implementquerycachingtostoreresultsoffrequentqueries.4)Utilizepreparedstatementsforeffi

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool