Develop user authorization login function for WeChat applet

Guanhui
Release: 2020-04-28 15:52:29
forward
4950 people have browsed it

This article will help readers achieve authorized login of users on mini programs based on WeChat Developer Tools & C# environment.

Preparation:

WeChat developer tools download address: https://developers.weixin.qq.com/miniprogram/dev/devtools/download.html

WeChat mini program development documentation: https://developers.weixin.qq.com/miniprogram/dev/index.html

Development:

at At the beginning of development, we need to first clarify the authorization login process that WeChat has developed. Please refer to the official API - Login Interface.

You will see the login authorization process developed by WeChat for developers:

Develop user authorization login function for WeChat applet

As shown in the figure, it is the login authorization for a forward user process.

Why is it said to be a forward process? Because in real mini program development, we are not sure when the user needs to initiate the above login process (for example: the user loses his credentials in some specific scenarios, but he does not exit the mini program but inside the mini program Doing jumps and other related operations may lead to some unexpected exceptions), so we need to add a layer of detection mechanism in addition to this forward process to solve these abnormal scenarios, and in the official API,wx.checkSessioncan solve this problem to a certain extent.

Then, our authentication process should actually be:

- Mini Programwx.checkSessionVerify that the login status is invalid

-success: The callback function that the interface calls successfully,session_keyhas not expired, and the process is over;

-fail: The callback function that fails to call the interface,session_keyExpired

-》 Mini-terminalwx.loginGet the code andwx.requestSubmit the code to your own server

- 》 Your own server submitsAppid appSecret codeto the WeChat server to obtainsession_key & openid

-》 Your own server generates ## based onsession_key & openid#3rd_session(Based on security considerations proposed by WeChat, developers are advised not to transmit key information such as openid) and return3rd_sessionto the mini program

-》 Mini Terminal

wx.setStorageStorage3rd_session(This parameter is included when subsequent user operations require credentials)

-》 Mini Terminal

wx.getUserInfoGet user informationwx.getStorageAfter obtaining the3rd_sessiondata, submit it together withwx.requestto your own server

-》 The SQL user data information of your own server is updated, and the process ends;

The ideas are sorted out, and then the process is implemented

Mini program:

In the mini program, create a new general JS for basic support

Develop user authorization login function for WeChat applet

and reference it in some pages that need to be referenced

var common = require("../Common/Common.js")
Copy after login

Then, in

Common.jsImplement logic in

//用户登陆 function userLogin() { wx.checkSession({ success: function () { //存在登陆态 }, fail: function () { //不存在登陆态 onLogin() } }) } function onLogin() { wx.login({ success: function (res) { if (res.code) { //发起网络请求 wx.request({ url: 'Our Server ApiUrl', data: { code: res.code }, success: function (res) { const self = this if (逻辑成功) { //获取到用户凭证 存儲 3rd_session var json = JSON.parse(res.data.Data) wx.setStorage({ key: "third_Session", data: json.third_Session }) getUserInfo() } else { } }, fail: function (res) { } }) } }, fail: function (res) { } }) } function getUserInfo() { wx.getUserInfo({ success: function (res) { var userInfo = res.userInfo userInfoSetInSQL(userInfo) }, fail: function () { userAccess() } }) } function userInfoSetInSQL(userInfo) { wx.getStorage({ key: 'third_Session', success: function (res) { wx.request({ url: 'Our Server ApiUrl', data: { third_Session: res.data, nickName: userInfo.nickName, avatarUrl: userInfo.avatarUrl, gender: userInfo.gender, province: userInfo.province, city: userInfo.city, country: userInfo.country }, success: function (res) { if (逻辑成功) { //SQL更新用户数据成功 } else { //SQL更新用户数据失败 } } }) } }) }
Copy after login

At this point, the process of the mini program is basically completed, and then implement your own service API

Login interface logic example

if (dicRequestData.ContainsKey("CODE")) { string apiUrl = string.Format("https://api.weixin.qq.com/sns/jscode2session?appid={0}&secret={1}&js_code={2}&grant_type=authorization_code", ProUtil.SmartAppID, ProUtil.SmartSecret, dicRequestData["CODE"]); HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create(apiUrl); myRequest.Method = "GET"; HttpWebResponse myResponse = (HttpWebResponse)myRequest.GetResponse(); StreamReader reader = new StreamReader(myResponse.GetResponseStream(), Encoding.UTF8); string content = reader.ReadToEnd(); myResponse.Close(); reader.Close(); reader.Dispose(); //解析 userModel ReMsg = JSONUtil.JsonDeserialize(content); //解析 if ((!string.IsNullOrWhiteSpace(ReMsg.openid)) && (!string.IsNullOrWhiteSpace(ReMsg.session_key))) { // 成功 自定义生成3rd_session与openid&session_key绑定并返回3rd_session } else { // 错误 未获取到用户openid 或 session } } else { // 错误 未获取到用户凭证code }
Copy after login

UserInfoUpdateThe interface will not be described in detail here. Users can operate the data according to their own conditions. The relevant parameter information returned when the WeChat call is successful is as follows

Develop user authorization login function for WeChat applet

At this point, the basic authorization login of the mini program and the acquisition of user information are completed.

PHP Chinese website, a large number of

free small program development tutorials, welcome to learn!

The above is the detailed content of Develop user authorization login function for WeChat applet. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:csdn.net
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
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!