1. The background
It is a cliche that small programs can easily obtain the user identification provided by wechat through the login ability provided by wechat official, and quickly establish the user system in small programs, that is, “silent login”. The author mentioned in the previous three articles “Diagram of small program silent login things”, “Small program silent login scheme design”, “small program user login architecture Design”, through the analysis of the front-end monitoring data, found that there is a lot of room for improving the success rate and time consumption of silent login. According to the statistics of the reasons for the failure of silent login request, 71.4% of the failed cases were found to be due to the request timeout problem. The “culprit” was the interface that the small program end exchanged the temporary login certificate code for Auth-Token and user information. The interface invocation link length resulted in high time consumption. The developer obtains the code by calling wx.login and sends it to the developer backend, which invokes auth.code2Session interface to obtain the user’s unique identification of OpenID and session key session_key. After associating the auth-Token and initializing user information, the request result is returned to the applet.
Ideally, silent login success has created a unique business identity for each user. However, for a complex cross-terminal application, such as an e-commerce application consisting of PC, H5 and small program, the user identity (UID) registered in different channels is different, and it is difficult for users to integrate data such as transaction, promotion and collection of various channels after login. Therefore, in order to achieve cross-terminal user system data communication, it is necessary to provide a unique user id — mobile phone number, that is, “user login”. The most common user login scheme is to let the user click button to trigger the authorization mobile phone number popup. After the user agrees to authorize, the small program end will send the encrypted mobile phone number data to the developer back-end, which uses session_key (symmetric decryption key) for symmetric decryption to obtain the mobile phone number to bind the user ID. And update the user identity (tourist -> ordinary user), and finally the updated user information data back to the small program end. However, session_key has a validity period. Therefore, before the small program initiates the login, the wechat open interface wx.checkSession is called to verify the validity of session_key, which virtually increases the complexity of the login request link and the login time of the user.
As can be seen from the above two cases of “silent login” and “user login”, for security reasons, the invocation of wechat open capability requires additional request for signature and key authentication, which virtually makes the invocation link more complex, improves the request time and reduces the user experience.
So how do you optimize these two links? Small programmers come up with cloud development solutions.
Cloud development is a native Serverless cloud service integrated into the applets console. Its core functions include cloud functions, cloud databases and cloud storage. The unique advantage of cloud function of cloud development lies in its seamless integration with wechat login authentication. When the cloud function is called from the small program side, the developer can use the getWXContext method provided by WX-server-SDK to obtain the context of each call (appID, OpenID, UnionID, etc.) in the cloud function without maintaining complex authentication mechanism. You can get a naturally trusted user login state. At the same time, Tencent Cloud provides Virtual Private Cloud (VPC) to construct logically isolated and user-defined network Spaces for Cloud servers, databases and other resources, ensuring security and isolation, and automatically scaling based on requests. Different VPCS can communicate with each other over the cloud using peer-to-peer links and cloud networking to shorten the link request time. According to our statistics, the silent login request time of cloud development is shortened by more than 45%, and the success rate of a login request is also increased from 97.78% to 99.98%.
Perhaps some people will question, small program cloud development process has become increasingly mature and rich cases, whether it is necessary to spend a length to write a login transformation experience. In fact, the business scene we are in is more complex. Cloud Mall is an e-commerce saas product based on wechat small program, and is committed to providing comprehensive and reliable small program Mall business services. As a service provider, batch support for 500+ business cloud development access is a huge project, is also a small program third-party batch generation cloud development of the first practitioners, the team felt the stones across the river, during the numerous pit, hope to be able to sum up some experience, feedback wechat ecological development.
Therefore, this chapter mainly focuses on the following two aspects: First, it describes the overall architecture and operation process of cloud MALL batch cloud development mode. Second, through the typical login cases to transform cloud development before and after the data comparison, verify the advantages of cloud development.
2. Understand third-party batch cloud development
2.1 Common applets cloud development
Ordinary small program development mode only in WeChat public platform (hereinafter referred to as mp) fill in the information registered small programs, AppId for small programs, in the developer tools to fill in the corresponding AppId, small program function for development and debugging, and corresponding small program to upload code to mp version management background, and then the artificial commit review and release.
If the small program wants to access cloud development, it can click “wechat Cloud Development” in the developer tool and select “Cloud Development Service Terms” and click “Cloud development button” to initialize the cloud environment. An environment corresponds to a set of independent cloud development resources, including database, storage space, cloud functions and other resources. In actual development, it is recommended that each formal environment be equipped with a test environment, and all functions be tested in the formal environment after the test environment is completed. You can pass the online cloud environment ID in the wx.cloud.init input parameter env to ensure that the online call is a formal environment. Developers do not need to manage the server, they can create cloud functions freely in the development tool, write, upload and deploy the cloud function code can be run with one click.
Since then, the applets on the publishing line normally call the cloud functions of the formal environment, so you can see that the deployment of the cloud functions is completely decouple-ed from the publishing process of the applets.
2.2 Third-party applets development
The development process of third-party applets is shown in the figure above. Applets operators can authorize third-party platforms with one click and complete services through third-party platforms. It can also be completely hosted to a third party and registered by the third party platform. The applets authorized by merchants are defined as “business applets”. Another “development applets” refer to the applets account used by service providers for development purposes. This account is usually not published online, but only used to log in to wechat developer tools for code writing and submission. Service providers using “development of small programs” for development and debugging, by developer tools to upload code draft will be submitted to the third party platform, higher authority of managers can be through a third party management background call interface will draft box code submitted to the template library, template library code can batch submitted to thousands of businesses use small programs, It is also possible to batch call the interface to help merchants review and publish.
2.3 Batch cloud Generation Development
The batch cloud generation development mode is provided for the scenarios where service providers develop and deploy small program templates in batches. In this mode, the service provider can create a cloud environment for the applets authorized by the merchant under the name. The cloud environment resources belong to the third-party platform, and the service provider can purchase and maintain the resources. In this mode, batch operation interface is provided for batch development.
In batch generation cloud development mode, small program development is still used to develop and debug small program code and cloud functions. After testing, cloud functions can be packaged and uploaded to the third-party cloud function management library.
Here, we derive the concept of “library”, the code for the template library business level of encapsulation, the past is directly to the template library code to the businessman small program, it does not meet the needs of businesses differentiation, for example, assume that only partial businessman would open cloud development capabilities, or businessmen would only call individual cloud function function, Creating a cloud environment for all merchants and deploying all cloud functions of a third-party cloud function management library is obviously a serious waste of resources. The code base solves this problem by selecting a list of cloud functions that the template library code needs to be associated with before it is transferred to the code base, and then successfully transferred to the third-party code base.
As is known to all, by a third party in batch generation of cloud development mode to create ownership of the cloud environment belonging to a third party, the third party AppID is carrying bulk account ID, cloud pattern associated with corresponding only tencent cloud account for carrying all the cloud resources in this mode, it is through the interface binding environment Shared small program to clients using the environment, therefore, The resource provider environment ID and the third-party AppID must be explicitly specified in the cloud environment initialization function of the applet code wx.cloud. cloud. Otherwise, the applet backend resources will invoke the cloud environment resources of the original client applet, resulting in service exceptions.
Service providers create cloud environments for each merchant applets with unique resource side environment ids. For such differentiated configurations, code for each merchant can be uploaded to an ext.json file. So, when the code base code is uploaded to the merchant applet, the following logic is executed:
- Judge whether the merchant agrees to open the cloud development; if so, judge whether the small program of the merchant is bound to the cloud environment; if not, help the merchant to create and bind the cloud environment.
- Iterate through the list of cloud functions associated with the current code base to create or update the cloud function code for the cloud environment where the business is located. If the cloud function is created, it also needs to update the cloud function configuration, such as private network configuration, public network access configuration, etc.
- willResource party environment ID and third-party AppIDAnd other service required differential configuration information is written
ext.json
, and injection of small program code package, upload to the business small program, after the release of small program side can be calledwx.getExtConfigSync()
orwx.getExtConfig()
The interface gets the required configuration information.
3. Small program side cloud development architecture
Small program end cloud development architecture, as shown in the figure to encapsulate a cloud function instance class for business layer calls, initialization method provides the basis for the cloud, and cloud call switch initialization, providing business approach to secondary packaging of cloud function calls, such as injection monitoring report logic, process and returns the result of the cloud function call.
3.1 initCloudInstance – Initializing the cloud environment
3.1.1 cloudcloud
Instance initialization
From the previous section, cloud environment resources created by a third party in batch generation cloud development mode are centrally managed and maintained by a third party. By binding environment interfaces, the third party authorizes cloud development resources to be used by small programs of customers, which is also called environment sharing. Therefore, if the applets want to use cloud development resources, they need to initialize the cloud instance, as shown in the following code:
The client applet calls the method wx.cloud. cloud and passes in the cloud environment ID authorized by the third party and the AppID of the third party to obtain the cloud instance. At this point, can the client applet call the cloud development API to access cloud resources?
Those of you who know a little about security principles must understand that things are not so simple, and you need to authenticate small programs for customers. Therefore, after the caller obtains the cloud Cloud instance, it needs to execute the init method, which will call the cloudbase_auth cloud function of the resource to authenticate the identity of the caller and set relevant permissions. After the init method is successfully executed, the cloud Cloud instance can be truly initialized.
Note that the small program base library 2.13.0 and above supports the wx.cloud. cloud method. For lower base library versions, no cloud calls are made.
3.1.2 Initialization Time
The unique advantage of cloud development is that it can obtain wechat login status without authentication, and the first is the login process transformation. As we all know, silent login is a very pre-stage process. Before silent login initiates a cloud call, the cloud Cloud instance needs to be initialized. It can be inferred that the initialization timing of cloud instances is also front-loaded. The initCloudInstance method is called during the onLaunch life cycle of the applet.
Because in the native applet startup process, the App, Page, and Component lifecycle hook functions do not support asynchronous blocking. Therefore, a cloud Cloud instance may not have been successfully initialized when the business logic (such as silent login) initiates a cloud call. Based on this, we encapsulate the waitCloudInstanceInit method and wait until the cloud instance is successfully initialized before initiating the business layer cloud call.
Here we use the Promise singleton pattern, abstracting a singleInstancePromise function for multiple business scenarios, as shown in the following code, maintaining a promiseInstance, and returning the instance when it exists. Otherwise initiated CloudFunctionInstance waitCloudInstanceInit function calls, and consumer call results.
So how do you ensure that cloud instances are initialized only once? Just CloudFunctionInstance class to maintain a private variable isInitCloudInstanceSuccess to tag cloud cloud instance, initial success.
3.1.3 Initialization Time Problem
For security reasons, the cloudbase_auth cloud function of the resource side must be invoked to authenticate and obtain related permissions when the client cloud instance is initialized. According to our monitoring and reported data statistics, the average initialization time of cloud instance is about 400ms, but there will be 1500ms-3000ms burr.
After analyzing the reason, it is caused by the resource allocation logic of the cloud server. Since the cloud function is not always running, but triggered by events, the trigger time is not controllable, so it will obviously cause serious resource waste to reserve enough instances for each cloud function. In order to support high concurrency, the cloud function platform provides “automatic elastic scaling capability” to start more instances to handle event requests when there are a large number of requests coming, and to shrink function instances to zero when there are no events coming. SCF platform is responsible for the creation, management and deletion of containers for all functions. Container startup takes some time. The method to reduce the delay of container startup is to reuse the container, that is, the container is not destroyed after the function call, but persists for a period of time. But not being used for a long time destroys the container.
Therefore, when a cloud function is called for the first time, updated, or re-called after a long absence, the container (that is, the execution environment of the function) needs to be restarted, which takes a certain amount of time, leading to burrs.
3.2 initSwitch – Initializes the cloud function switch configuration
It is known that cloud development resources are paid by volume, which requires a certain cost. Merchants have different requirements for cloud development capabilities. Therefore, as a third party, it is necessary to provide the cloud function switch setting service on the merchant side, so that the merchant can open the cloud function as required. After the merchant saves the editing result, the configuration information of the configuration center will be updated. When users enter the business applet, they will request to obtain the configuration center data, get the cloud function switch configuration, and call the cloud function as required.
As shown in the figure above, after the merchant has opened two cloud function services, namely login and message subscription, the user will call the corresponding cloud function when entering the merchant applets, while other unopened functions, such as short chain and two-dimensional code, will still request the services provided by the service provider to obtain the corresponding capabilities.
The advantage of the cloud function switch setting service provided by the merchant side lies in that the merchant can switch the switch state at any time, and can do emergency treatment when one party fails. When the data of the configuration center is updated, the small program has a certain policy to update the configuration in time, and then switch the invocation mode of each function in time.
As shown in the preceding code, the initSwitch method is used to initialize the switch configuration. The switch configuration of the cloud function can be initialized only after the configuration center data is obtained successfully. The getSwitchInitResult method is used to obtain the switch status of the corresponding cloud function. As can be seen from line 15, we do not wait for the successful initialization of the switch configuration of the cloud function before taking the value. This is because it is understood that calls to cloud functions should not be blocked by requests to get/update configuration center data, but should be completely decoupled. For example, one of the advantages of cloud development’s revamping of the silent login process, which is a very pre-emptive process, is time saving. However, if the initiation of the silent login request depends on the switch status of the cloud function, the corresponding silent login request can be initiated only after the configuration center successfully delivers the switch status of the cloud function. In fact, if silent logins are blocked by configuration center data retrieval requests, cloud cloud initialization, then the advantage of reduced time consumption for cloud development is wiped out.
3.3 Business method encapsulation
Cloud Cloud functions can be called using the callFunction method after the cloud instance is successfully initialized. We believe that there are risks in directly exposing cloud instances to the invocation of the business layer. Firstly, the input parameters are not controllable, and the invocation of cloud functions involves logic such as time-consuming reporting, monitoring reporting and environment switching, which virtually increases the complexity of the code of the business layer. Therefore, we encapsulate business methods in CloudFunctionInstance, as shown in the following figure.
4. Upgrade the login process
The purpose of common request silent login is to obtain the OpenID that uniquely identifies the user and the session key session_key. OpenID is mainly used to generate custom login state, user ID, and initializing user information data, and session_key is mainly used to decrypt the mobile phone number of wechat authorized login. The cloud function silent login process directly uses the getWXContext method provided by WX-server-SDK in the cloud function to obtain the context (AppID, OpenID, UnionID) of each invocation, and then sends it to the developer server. The difference between the two is that the developer server does not get the session_key using the cloud function silent login.
Therefore, the switch of the silent login function of the cloud function and the switch of the user login function are combined into the same login switch. Otherwise, if the silent login is performed using the cloud function and the authorized mobile phone number is logged in using the ordinary request, the developer server does not store the user’s Session_key and cannot decrypt the mobile phone number, the login will fail.
The login flow chart of cloud development and transformation is shown in the figure above. When visitors enter the mini program for the first time, they will judge whether to initiate silent login by cloud function according to the switch status of the configuration center (due to the blocking problem, the default configuration of new users entering the mini program for the first time is on). If yes, use the cloud function to initiate the silent login process. If the cloud function fails, switch to the common request and retry to initiate the silent login process. Note that silent login has added a second retry mechanism, and two consecutive failed requests are considered a true failure. It should be added that a cloud function call failure refers to an exception thrown when the cloud function is called, while a request failure refers to a request made by the cloud function to the developer server, and the server returns the failure result. After a silent login request is successful, isCloudSilentLogin is stored locally for subsequent requests to determine the silent login mode.
When visitors click the authorized mobile phone number to log in, they will first obtain the local storage id isCloudSilentLogin to determine the silent login mode. If silent login is used, the cloud function will be called for user login. If the developer server returns a failure result, they will wait for the user to retry. If the cloud function fails to be called, it will switch to a common request for user login. Since the developer server does not store session_key at this time, it needs to initiate a common request for silent login again, and then wait for the user to click authorize login again.
4.1 Silent Login for cloud Functions
In wechat mini program ecology, OpenId is used to identify a user. The OpenId of the same user is permanent for the same mini program. Even if the user changes the phone or deletes the mini program, the developer can still identify the user through background records next time he enters the mini program.
Therefore, the purpose of silent login is to obtain the unique user id OpenID and session key session_key. OpenID is mainly used to generate custom login state, user ID, and initialization user information data.
In the silent login process before the transformation, the small program side needs to call wx.login() to obtain the temporary login certificate code and send it back to the developer server. Code2Session interface is called on the server side to obtain the user’s unique identifier OpenID and session key Session_key, generate the custom login auth-Token, assign a unique user ID (UID) to each user, and initialize the user information. It is then returned to the applet side.
As shown in the figure, the flow chart of silent login after cloud development and transformation is mainly divided into the following three steps:
- Applet side call
silentLogin
Cloud function services. silentLogin
A cloud function is a piece of code that runs in the cloud and is used within the cloud functionwx-server-sdk
To provide thegetWXContext
Method to obtainappid
,openid
,unionid
, and send it to the developer server.- The developer server gets it
openid
, associate custom login state and generate business identity (uid
), initialize user information, etcauth-token
And user information data are returned to the cloud function service, which encapsulates the request result and returns it to the applet side.
The getWXContext() method can obtain the wechat context in the cloud function. In the batch generation cloud development mode, the service provider shares the cloud environment with the business applet. Therefore, the business applet’s call to the cloud function belongs to cross-account call. You should get FROM_OPENID, FROM_UNIONID, FROM_APPID for the caller’s source applet.
There must be some question here, the cloud function calls the developer server interface, directly appID, OpenID, UnionID as the pass parameter, does not exist CSRF vulnerability? The solution is as follows: Cloud function services and services provided by developers’ backends can be deployed on private networks (VPCS). Private networks communicate with each other through peer-to-peer connections, accelerating communication speed and ensuring security. When the small program invokes the silentLogin cloud function, the wechat cloud function gateway will forward it to the cloud function service deployed by the developer, run the cloud function code, communicate with the service provided by the developer back end through peer connection, and return the request result to the small program end.
4.2 Cloud Function User Login
Before the transformation, the small program sends the encryptedData and IV data returned by the callback of the authorized phone number to the developer server. The developer server uses session_key (symmetric decryption key) for symmetric decryption to obtain the phone number to bind the user ID. And updates the user identity (tourist -> common user), and finally returns the updated user information data to the small program, which updates the user information stored in the local storage.
If you use cloud development to transform the silent login process, the developer server can not get the session_key, so how to decrypt the phone number?
Open data can be retrieved directly using cloud calls.
The operation of cloud development and transformation of authorized mobile phone number login process is shown in the figure above, which is divided into the following three steps:
- Small program end will be authorized phone number callback return
cloudID
And stored locally after a successful silent loginauth-token
Call as an argumentuserLogin
Cloud function services. userLogin
Cloud function running code, the first cloud call wechat open interfacegetOpenData
Get the mobile phone number of the cloud function caller, construct the request header and parameters, and add the mobile phone number andauth-token
To the developer server.- Developer server authentication, authentication through the mobile phone number to bind users
id
And update the user identity (tourist -> ordinary user). Finally, the updated user information data is returned to the cloud function service. The cloud function service encapsulates the request result and returns it to the small program end, which updates the localstorage
Stored user information.
According to our observation of monitoring data, cloudID will have a probability of loss, so before initiating user login cloud function call, it is necessary to determine whether the user’s authorized mobile phone number has been obtained by cloudID. If it is empty, the process will be terminated and the user will be reminded to try again.
4.3 Optimization Effect
Cloud development and transformation login process has been online for three months, according to our monitoring data statistics. The silent login request time of cloud development is shortened by more than 45%, the success rate of one login request is increased from 97.78% to 99.98%, and the success rate of retry login request is increased from 99.17% to 99.999%.
However, silent login is a very pre-emptive process that is blocked by cloud instance initialization. To further reduce the time consuming, it is necessary to promote wechat to optimize the initialization link of cloud instance, such as the authentication process by calling the cloudbase_Auth cloud function of the resource side.
Common user login requests require session_key to decrypt mobile phone numbers and encrypt data. Therefore, wx.checkSession is required to check whether session_key expires before initiating a request. This process blocks the initiation of user login requests. After the transformation into cloud function call, the time of user login is not significantly increased compared with that before the transformation. The reason is analyzed as follows: the cloud function needs to call wechat open interface getOpenData, and the average time of this open interface is about 300ms. However, by not relying on session_key to decrypt the phone number, the success rate of user login requests increased from 97.322% to 99.999%
Note that this data comes from the monitoring data of the author’s business in the past two weeks. The author makes a rough statistics of the data for reference only.
The last 5
Through the transformation of the login process, we verified that the batch cloud generation development mode can significantly shorten the call link time, improve user experience, and provide security guarantee. Our team has reached in-depth cooperation with wechat and Tencent Cloud. As one of the first service providers to access and use the cloud, we found many problems in the access process, and also promoted Tencent Cloud and wechat to optimize the link and feedback the ecological development of wechat’s batch generation cloud development mode.
Batch generation cloud development mode has a wide application prospect, and the transformation of wechat login process is only a touchstone. We are also trying to sort out the team’s experience into best practices and feed back to the wechat service provider cloud development community to help service provider developer ecology develop better.