Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to realize the login status of WeChat Mini Programs and the app.js that has not been registered?

2025-04-09 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

Editor to share with you WeChat Mini Programs login status and check the registration of the app.js how to achieve, I believe that most people do not know much, so share this article for your reference, I hope you will learn a lot after reading this article, let's go to know it!

0. Official page that can be referenced

Get login credentials: https://developers.weixin.qq.com/miniprogram/dev/api/wx.login.html

Check whether the login status is expired: https://developers.weixin.qq.com/miniprogram/dev/api/wx.checkSession.html

Note: you have to understand what the login status is: the login status here is WeChat Mini Programs's own login status, and we can write a login page as our own login status. However, for the sake of a good user experience, I directly use Wechat login status as my login status. So my entire Mini Program is logged in automatically.

Note: WeChat Mini Programs cache is easy to clear, so you must always beware of what to do when Mini Program cache is cleared.

Note: the format of the object I returned to Mini Program from the background is:

Public ResultCode resultCode; / / Service response code public String resultMsg = ""; / / return message description public String errCode; / / error code public String errCodeDes = ""; / / error description public Object data; / / return business data public enum ResultCode {SUCCESS, / / Business processing succeeded FAIL; / / Business processing failed}

1. Process

(1) call wx.checkSession to check whether the login status of the user expires. If not, check whether the user has registered for ①. If it expires, re-execute the login process ②.

(2) the process of ② is: call wx.login to obtain login credentials (code), then send the code to the backend, call auth.code2Session at the backend, use code in exchange for openid and other information to obtain openId, return the openId to Mini Program, then put the openId in Mini Program cache, and then check whether the user has registered ①.

(3) the process of ① is as follows: first check whether the user is registered from the cache (by checking whether the cache variable registered exists). If there is a regular user, go to the backend to check whether there is this user through openId, and return the result to Mini Program. If there is such a user at the backend, it indicates that the user has been registered, then add a registered to the cache and assign a true.

(4) then we can use registered on other pages to determine whether the user has registered or not, and then jump to the registration page or the home page.

2. App.js code

App ({globalData: {serverHost: 'http://localhost:8080', / / server domain name}, onLaunch: function () {var that = this; / / check whether the login status expires wx.checkSession ({success () {/ / session_key has not expired and has been valid for the current lifecycle ("[user Mini Program login status has not expired]") That.isRegister ();}, fail () {/ / session_key has expired. You need to re-execute the login process that.wxLogin ();}})}, / / check whether the current user has registered for isRegister: function () {var that = this; var host = this.globalData.serverHost / / (first check the user from the cache, there is an old user, without checking whether there is a user in the background, slow down if the user is found in the background, if not, it is a new user) wx.getStorage ({key: 'registered', success (res) {console.log ("[query through cache that the user is already registered]") Console.log ("[current user's openid is:]" + wx.getStorageSync ('openid'));}, fail (res) {var openid; openid = wx.getStorageSync (' openid') Wx.request ({url: host + 'write your own background request to check whether the user exists URL', method:' POST', data: {openId: openid,}, header: {"Content-Type": "application/x-www-form-urlencoded"}) Success: (res) = > {if (the backend returned registered ") {if (res.data.data) {console.log (" [the user has been registered by querying the backend] ") Wx.setStorage ({key: "registered", data: true});} else {console.log ("[the user has not been registered through background query]") })},})}, / / wxLogin used by this function to log in: function () {var that = this; / / set background host var host = this.globalData.serverHost; console.log ("[user re-executes Mini Program login process]") Wx.login ({success (res) {/ / initiates a network request and sends res.code to the background in exchange for openId if (res.code) {var code = res.code) Wx.request ({url: host + 'write your backend request to exchange code for OpenId URL', method:' POST', data: {code: code,}, header: {"Content-Type": "application/x-www-form-urlencoded"} Success: (res) = > {console.log ("[user openid obtained successfully]") Console.log ("[get user openid from backend]" + res.data.data.openid) let openId = res.data.data.openid; wx.setStorage ({key: "openid", data: res.data.data.openid}); console.log ("[user openid put into cache successfully]); that.isRegister () })}))})

3. How does the java backend obtain openId through code

Import net.sf.json.JSONObject;/** * @ author niqinhua * @ date 9:19 on 2019-3-8 * / public class WXUtil {public static JSONObject getOpenidAndSessionKey (String code) {String url = "https://api.weixin.qq.com/sns/jscode2session"; String param =" appid= wrote his own appId&secret= key & js_code= "+ code +" & grant_type=authorization_code "; String wxReturnResult = sendGet (url, param) JSONObject wxReturnResultObject = JSONObject.fromObject (wxReturnResult); return wxReturnResultObject;} / * from the specification, it is recommended to extract this method and put it in the HttpUtil class * send a request for GET method to the specified URL * @ param url to send the request URL * @ param param request parameter, which should be in the form of name1=value1&name2=value2. * response result of the remote resource represented by * @ return URL * / public static String sendGet (String url, String param) {String result = ""; BufferedReader in = null; try {String urlNameString = url + "?" + param; URL realUrl = new URL (urlNameString); / / Open the connection to URL URLConnection connection = realUrl.openConnection () / / set general request properties connection.setRequestProperty ("accept", "* / *"); connection.setRequestProperty ("connection", "Keep-Alive"); connection.setRequestProperty ("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1 Sv1)"); / / establish the actual connection connection.connect () / / define the BufferedReader input stream to read the URL response in = new BufferedReader (new InputStreamReader (connection.getInputStream (); String line; while ((line = in.readLine ())! = null) {result + = line }} catch (Exception e) {System.out.println ("[an exception occurred when HTTP sent a GET request]: access URL:" + url+ ", error:" + e.getMessage ());} / / use finally block to close the input stream finally {try {if (in! = null) {in.close () }} catch (Exception e2) {System.out.println ("[HTTP request closes input stream exception]: access URL:" + url+ ", error:" + e2.getMessage ());}} return result;}}

The above is just a tool class that can be taken directly. The real business logic has to be written by myself. I will only give you the key parts.

JSONObject wxReturnJson = WXUtil.getOpenidAndSessionKey (code); if (wxReturnJson.get ("errCode")! = null) {/ / log.error ("[get user's openid] [failed] [pass parameter code is invalid]");} else {/ / log.info ("[get user's openid] [success] [pass parameter code is invalid]") } the above is all the contents of the article "WeChat Mini Programs login status and checking how to achieve unregistered app.js". Thank you for reading! I believe we all have a certain understanding, hope to share the content to help you, if you want to learn more knowledge, welcome to follow the industry information channel!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 260

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report