


Mini 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', }) } } })
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:
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!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



With the popularity of mobile Internet technology and smartphones, WeChat has become an indispensable application in people's lives. WeChat mini programs allow people to directly use mini programs to solve some simple needs without downloading and installing applications. This article will introduce how to use Python to develop WeChat applet. 1. Preparation Before using Python to develop WeChat applet, you need to install the relevant Python library. It is recommended to use the two libraries wxpy and itchat here. wxpy is a WeChat machine

Mini programs can use react. How to use it: 1. Implement a renderer based on "react-reconciler" and generate a DSL; 2. Create a mini program component to parse and render DSL; 3. Install npm and execute the developer Build npm in the tool; 4. Introduce the package into your own page, and then use the API to complete the development.

Implementing card flipping effects in WeChat mini programs In WeChat mini programs, implementing card flipping effects is a common animation effect that can improve user experience and the attractiveness of interface interactions. The following will introduce in detail how to implement the special effect of card flipping in the WeChat applet and provide relevant code examples. First, you need to define two card elements in the page layout file of the mini program, one for displaying the front content and one for displaying the back content. The specific sample code is as follows: <!--index.wxml-->&l

According to news from this site on October 31, on May 27 this year, Ant Group announced the launch of the "Chinese Character Picking Project", and recently ushered in new progress: Alipay launched the "Chinese Character Picking-Uncommon Characters" mini program to collect collections from the society Rare characters supplement the rare character library and provide different input experiences for rare characters to help improve the rare character input method in Alipay. Currently, users can enter the "Uncommon Characters" applet by searching for keywords such as "Chinese character pick-up" and "rare characters". In the mini program, users can submit pictures of rare characters that have not been recognized and entered by the system. After confirmation, Alipay engineers will make additional entries into the font library. This website noticed that users can also experience the latest word-splitting input method in the mini program. This input method is designed for rare words with unclear pronunciation. User dismantling

How uniapp can achieve rapid conversion between mini programs and H5 requires specific code examples. In recent years, with the development of the mobile Internet and the popularity of smartphones, mini programs and H5 have become indispensable application forms. As a cross-platform development framework, uniapp can quickly realize the conversion between small programs and H5 based on a set of codes, greatly improving development efficiency. This article will introduce how uniapp can achieve rapid conversion between mini programs and H5, and give specific code examples. 1. Introduction to uniapp unia

Implementation idea: Establishing the server side of thread, so as to process the various functions of the chat room. The establishment of the x02 client is much simpler than the server. The function of the client is only to send and receive messages, and to enter specific characters according to specific rules. To achieve the use of different functions, therefore, on the client side, you only need to use two threads, one is dedicated to receiving messages, and the other is dedicated to sending messages. As for why not use one, that is because, only

Mini program registration operation steps: 1. Prepare copies of personal ID cards, corporate business licenses, legal person ID cards and other filing materials; 2. Log in to the mini program management background; 3. Enter the mini program settings page; 4. Select " "Basic Settings"; 5. Fill in the filing information; 6. Upload the filing materials; 7. Submit the filing application; 8. Wait for the review results. If the filing is not passed, make modifications based on the reasons and resubmit the filing application; 9. The follow-up operations for the filing are Can.

1. Open the WeChat mini program and enter the corresponding mini program page. 2. Find the member-related entrance on the mini program page. Usually the member entrance is in the bottom navigation bar or personal center. 3. Click the membership portal to enter the membership application page. 4. On the membership application page, fill in relevant information, such as mobile phone number, name, etc. After completing the information, submit the application. 5. The mini program will review the membership application. After passing the review, the user can become a member of the WeChat mini program. 6. As a member, users will enjoy more membership rights, such as points, coupons, member-exclusive activities, etc.
