


In order to facilitate mini program applications to use the WeChat login state for authorized login, the WeChat mini program provides an open interface for login authorization. At first glance, I feel that the document is very reasonable, but when it comes to implementation, it is really confusing and I don’t know how to manage and maintain the login state. This article will teach you step by step how to access and maintain WeChat login status in business.
Access Process
The flow chart in the official document here is clear enough, so we will directly elaborate and supplement it.
First of all, when you see this picture, you will definitely notice that the mini program communicates and interacts with not only the mini program front end and our own server, but also the WeChat third-party server Also involved, so what role does the WeChat server play in it? Let’s go through the login authentication process together and we’ll understand.
1. Call wx.login to generate code
wx.login() The function of this API is to generate a temporary login credential for the current user. This temporary login credential is only valid for five minutes. After we get this login credentials, we can proceed to the next step: Get openid and session_key
wx.login({ success: function(loginRes) { if (loginRes.code) { // example: 081LXytJ1Xq1Y40sg3uJ1FWntJ1LXyth } } });
2. Get openid and session_key
Let’s introduce openid first. Children's shoes who have used public accounts should be familiar with this logo. In the public platform, it is used to identify each user's unique identity in three different applications: subscription account, service account, and mini program. In other words, each user The openid in each application is inconsistent, so in the mini program, we can use openid to identify the uniqueness of the user.
So what is session_key used for? With the user ID, we need to let the user log in. Then the session_key ensures the validity of the current user's session operation. This session_key is distributed to us by the WeChat server. In other words, we can use this identifier to indirectly maintain the login status of our applet users. So how did we get this session_key? We need to request the third-party interface https://api.weixin.qq.com/sns/jscode2session provided by WeChat on our own server. This interface needs to bring four parameter fields:
From these parameters, we can see that to request this interface, you must first call wx.login() to obtain the code of the user's current session. So why do we need to request this interface on the server side? In fact, it is for security reasons. If we call this interface through request on the front end, we will inevitably need to expose the appid of our mini program and the secret of the mini program to the outside. At the same time, we will also expose the session_key issued by the WeChat server. To "people with good intentions", this brings great risks to our business security. In addition to obtaining session_key on the server side, we also need to pay attention to two points:
session_key corresponds one-to-one with the code distributed by WeChat, and the same code can only be exchanged for session_key once. Each time wx.login() is called, a new code and corresponding session_key will be issued. In order to ensure the user experience and the validity of the login state, developers need to know that the user needs to log in again before calling wx.login()
session_key is invalid. Even if wx.login is not called, the session_key will expire. The expiration time is positively related to the frequency of the user using the mini program, but the specific length of time is not available to developers and users. Arrive
function getSessionKey (code, appid, appSecret) { var opt = { method: \'GET\', url: \'https://api.weixin.qq.com/sns/jscode2session\', params: { appid: appid, secret: appSecret, js_code: code, grant_type: \'authorization_code\' } }; return http(opt).then(function (response) { var data = response.data; if (!data.openid || !data.session_key || data.errcode) { return { result: -2, errmsg: data.errmsg || \'返回数据字段不完整\' } } else { return data } }); }
3. Generate 3rd_session
As mentioned before, session_key is used to "indirectly" maintain the login state. The so-called indirection means that we need to maintain the user's status ourselves. Login status information, security factors are also taken into consideration here. If the session_key distributed by the WeChat server is used directly as the login status of the business party, it will be used by "intentional people" to obtain the user's sensitive information, such as wx.getUserInfo( ) This interface requires session_key to decrypt the sensitive information of WeChat users.
So what if we generate our own login status ID? Here we can use several common irreversible hash algorithms, such as md5, sha1, etc., to generate the login status ID (here we collectively refer to it as \' skey\') is returned to the front end, and the login status identity is maintained at the front end (usually stored in storage). On the server side, we will store the generated skey in the data table corresponding to the user, and the front end will access the user's information by passing the skey.
You can see that we used the sha1 algorithm to generate a skey:
const crypto = require(\'crypto\'); return getSessionKey(code, appid, secret) .then(resData => { // 选择加密算法生成自己的登录态标识 const { session_key } = resData; const skey = encryptSha1(session_key); }); function encryptSha1(data) { return crypto.createHash(\'sha1\').update(data, \'utf8\').digest(\'hex\') }
4. checkSession
前面我们将skey存入前端的storage里,每次进行用户数据请求时会带上skey,那么如果此时session_key过期呢?所以我们需要调用到wx.checkSession()这个API来校验当前session_key是否已经过期,这个API并不需要传入任何有关session_key的信息参数,而是微信小程序自己去调自己的服务来查询用户最近一次生成的session_key是否过期。如果当前session_key过期,就让用户来重新登录,更新session_key,并将最新的skey存入用户数据表中。
checkSession这个步骤呢,我们一般是放在小程序启动时就校验登录态的逻辑处,这里贴个校验登录态的流程图:
下面代码即校验登录态的简单流程:
let loginFlag = wx.getStorageSync(\'skey\'); if (loginFlag) { // 检查 session_key 是否过期 wx.checkSession({ // session_key 有效(未过期) success: function() { // 业务逻辑处理 }, // session_key 过期 fail: function() { // session_key过期,重新登录 doLogin(); } }); ) else { // 无skey,作为首次登录 doLogin(); }
推荐:《小程序开发教程》
The above is the detailed content of How does the mini program access and maintain the WeChat login status?. For more information, please follow other related articles on the PHP Chinese website!

随着移动互联网技术和智能手机的普及,微信成为了人们生活中不可或缺的一个应用。而微信小程序则让人们可以在不需要下载安装应用的情况下,直接使用小程序来解决一些简单的需求。本文将介绍如何使用Python来开发微信小程序。一、准备工作在使用Python开发微信小程序之前,需要安装相关的Python库。这里推荐使用wxpy和itchat这两个库。wxpy是一个微信机器

小程序能用react,其使用方法:1、基于“react-reconciler”实现一个渲染器,生成一个DSL;2、创建一个小程序组件,去解析和渲染DSL;3、安装npm,并执行开发者工具中的构建npm;4、在自己的页面中引入包,再利用api即可完成开发。

微信小程序是一种轻量级的应用程序,可以在微信平台上运行,不需要下载安装,方便快捷。Java语言作为一种广泛应用于企业级应用开发的语言,也可以用于微信小程序的开发。在Java语言中,可以使用SpringBoot框架和第三方工具包来开发微信小程序。下面是一个简单的微信小程序开发过程。创建微信小程序首先,需要在微信公众平台上注册一个小程序。注册成功后,可以获取到

实现思路x01服务端的建立首先,在服务端,使用socket进行消息的接受,每接受一个socket的请求,就开启一个新的线程来管理消息的分发与接受,同时,又存在一个handler来管理所有的线程,从而实现对聊天室的各种功能的处理x02客户端的建立客户端的建立就要比服务端简单多了,客户端的作用只是对消息的发送以及接受,以及按照特定的规则去输入特定的字符从而实现不同的功能的使用,因此,在客户端这里,只需要去使用两个线程,一个是专门用于接受消息,一个是专门用于发送消息的至于为什么不用一个呢,那是因为,只

PHP与小程序的地理位置定位与地图显示地理位置定位与地图显示在现代科技中已经成为了必备的功能之一。随着移动设备的普及,人们对于定位和地图显示的需求也越来越高。在开发过程中,PHP和小程序是常见的两种技术选择。本文将为大家介绍PHP与小程序中的地理位置定位与地图显示的实现方法,并附上相应的代码示例。一、PHP中的地理位置定位在PHP中,我们可以使用第三方地理位

本篇文章给大家带来了关于微信小程序的相关问题,其中主要介绍了如何在小程序中用公众号模板消息,下面一起来看一下,希望对大家有帮助。

随着小程序的广泛应用,越来越多的开发者需要将其与后台服务器进行数据交互,其中最常见的业务场景之一就是上传文件。本文将介绍在小程序中实现文件上传的PHP后台实现方法。一、小程序中的文件上传在小程序中实现文件上传,主要依赖于小程序APIwx.uploadFile()。该API接受一个options对象作为参数,其中包含了要上传的文件路径、需要传递的其他数据以及

苏州健康码的小程序叫“苏康码”,它是苏州市疫情防控指挥部指定的通行服务码,疫情防控期间在全市范围内通用,可以作为广大民众日常出行的重要凭证,同时作为防疫人员查验的主要依据;也是省内所有来苏逗苏人员以及在苏工作学习生活,旅游或临时停留人员申报的键康申报数据为基础,结合相关数据比对后动态生成的个人电子健康凭证。


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

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

Atom editor mac version download
The most popular open source editor
