Mini Program Development--User Login and Maintenance Example Tutorial

零下一度
Release: 2017-05-20 16:55:53
Original
4826 people have browsed it

Providing user login and maintaining the user's login status are generally things that a software application with a user system needs to do. For a social platform like WeChat, if we make a small program application, we may rarely make a pure tool software that is completely separated from and abandons the connection of user information.

Allowing users to log in, identifying users and obtaining user information, and providing services with users as the core are what most small programs will do. Today we will learn how to log in users in the mini program and how to maintain the session (Session) state after login.

In the WeChat mini program, we will generally involve the following three types of login methods:

  • Own account registration and login

  • Use other third-party platform accounts to log in

  • Use WeChat account to log in (that is, directly use the currently logged-in WeChat account to log in as a user of the mini program)

The first and second methods are the two most common methods currently used in Web applications. They can also be used in WeChat mini programs, but need to pay attention to the following: There is no Cookie<a href="http://www.php.cn/wiki/422.html" target="_blank"></a> mechanism in the mini program, so before using these two methods, please confirm whether yours or a third party's API needs to rely on Cookie ; In addition, HTML pages are not supported in mini programs. Those third-party APIs that need to use page redirection for login need to be modified or cannot be used.

Today we will mainly discuss the third method, that is, how to log in using a WeChat account, because this method is most closely integrated with the WeChat platform and has a better user experience.

Login process

Quoting the login flow chart from the official document of the mini program, the entire login process is basically as shown below:

Mini Program Development--User Login and Maintenance Example Tutorial

Login flowchart

In this figure, "mini program" refers to the code part we write using the mini program framework. "Third-party server" is generally our own background service program, and "WeChat server" is WeChat official API server.

Let’s break down this flow chart step by step.

Step 1: Obtain the login credentials (code) of the currently logged-in WeChat user on the client

The first step to log in in the mini program is to obtain the login credentials first . We can use the wx.login() method and get a login credentials.

We can initiate a login credential request in the App code of the mini program, or in any other Page code, mainly based on the actual needs of your mini program.

App({
  onLaunch: function() {
    wx.login({
      success: function(res) {
        var code = res.code;
        if (code) {
          console.log(&#39;获取用户登录凭证:&#39; + code);
        } else {
          console.log(&#39;获取用户登录态失败:&#39; + res.errMsg);
        }
      }
    });
  }
})
Copy after login

Step 2: Send the login credentials to your server, and use the credentials on your server to exchange the WeChat server for the WeChat user's

unique identification (openid)

andSession key (session_key)First, we use the wx.request() method to request a background API implemented by ourselves and carry the login credentials (code), for example, in our Based on the previous code, add:

App({
  onLaunch: function() {
    wx.login({
      success: function(res) {
        var code = res.code;
        if (code) {
          console.log(&#39;获取用户登录凭证:&#39; + code);

          // --------- 发送凭证 ------------------
          wx.request({
            url: &#39;https://www.my-domain.com/wx/onlogin&#39;,
            data: { code: code }
          })
          // ------------------------------------

        } else {
          console.log(&#39;获取用户登录态失败:&#39; + res.errMsg);
        }
      }
    });
  }
})
Copy after login

Your background service (/wx/onlogin) then needs to use the passed login credentials to call the WeChat interface in exchange for openid and session_key. The interface address format is as follows:

api.weixin.qq.com/sns/jscode2session?appid=APPID&secret=SECRET&js_code=JSCODE&grant_type=authorization_code
Copy after login

Here is the code of the background service I built using

Node.js

Express, for reference only:

If this background code is executed successfully, you can Get openid and session_key. This information is the login status of the current WeChat account on the WeChat server.

However, for security reasons, please do not directly use this information as the user ID and session ID of your mini program to be sent back to the mini program client. We should make our own layer on the server side. session, generate a session id from this WeChat account login state and maintain it in our own session mechanism, and then distribute this session id to the mini program client for use as a session identifier.

Regarding how to implement this session mechanism on the server side, we now generally use key-value storage tools, such as redis. We generate a unique string as a key for each session, and then store session_key and openid as values ​​in redis. For safety, a timeout should be set when saving.

Step 3: Save

sessionid on the client

When developing web applications, in the client (browser), we usually store the session id in a cookie , but the mini program does not have a cookie mechanism, so cookies cannot be used. However, the mini program has local storage, so we can use storage to save the sessionid for subsequent background API calls.

在之后,调用那些需要登录后才有权限的访问的后台服务时,你可以将保存在storage中的sessionid取出并携带在请求中(可以放在header中携带,也可以放在querystring中,或是放在body中,根据你自己的需要来使用),传递到后台服务,后台代码中获取到该sessionid后,从redis中查找是否有该sessionid存在,存在的话,即确认该session是有效的,继续后续的代码执行,否则进行错误处理。

这是一个需要session验证的后台服务示例,我的sessionid是放在header中传递的,所以在这个示例中,是从请求的header中获取sessionid:

router.get(&#39;/wx/products/list&#39;, function (req, res, next) {
  let sessionid = req.header("sessionid")
  let sessionVal = redisStore.get(sessionid)
  if (sessionVal) {
    // 执行其他业务代码
  } else {
    // 执行错误处理
  }
})
Copy after login

好了,通过微信账号进行小程序登录和状态维护的简单流程就是这样,了解这些知识点之后,再基于此进行后续的开发就会变得更容易了。

另外,腾讯前端团队也开源了他们封装的相关库,可以借鉴和使用。

  • 服务器端库 weapp-session

  • 小程序端库 weapp-session-client

感谢阅读我的文章,如有疑问或写错的地方请不吝留言赐教。

【相关推荐】

1. 微信小程序完整源码下载

2. 简单的左滑操作和瀑布流布局

3. 微信小程序游戏类demo挑选不同色块

The above is the detailed content of Mini Program Development--User Login and Maintenance Example Tutorial. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!