当前位置:网站首页>Wechat applet development - user authorization to log in to "suggestions collection"
Wechat applet development - user authorization to log in to "suggestions collection"
2022-07-01 11:16:00 【Full stack programmer webmaster】
Hello everyone , I meet you again , I'm your friend, Quan Jun .
This article will help the reader to realize based on WeChat Developer tools & C# Environmental Science Users under Applet Authorized login on .
Get ready :
Wechat developer tool download address :https://developers.weixin.qq.com/miniprogram/dev/devtools/download.html
Wechat applet development document :https://developers.weixin.qq.com/miniprogram/dev/index.html
Development :
At the beginning of development , We need to make sure that wechat has developed the authorization login process , see official API – Login interface .
You will see the login authorization process developed by wechat for developers :
Pictured , That is, a forward user login authorization process .
Why is it a forward process ? Because in real small program development , We are not sure when users need to start the above login process ( Such as : The user's credentials are lost in some specific scenarios , but Ta Instead of exiting the applet, I did jump and other related operations inside the applet , That is, it may cause some unexpected exceptions ), therefore , We need to be outside this forward process , Add a layer of detection mechanism , To solve these abnormal scenarios , And the official API in ,wx.checkSession It can solve this problem to a certain extent .
that , Our certification process should actually be :
– Applet wx.checkSession Verify that the login status is invalid
– success : Interface calls the successful callback function ,session_key Not expired , End of the process ;
– fail : Interface call failed callback function ,session_key Has expired
-》 Small program end wx.login obtain code and wx.request Submit code To your server
-》 Own server Submit Appid + appSecret + code Go to wechat server obtain session_key & openid
-》 Own server according to session_key & openid Generate 3rd_session( Wechat party proposed security considerations , It is recommended that developers do not use openid And other key information for data transmission ) And back to 3rd_session To the applet side
-》 Small program end wx.setStorage Storage 3rd_session ( When vouchers are required for subsequent user operations With this parameter )
-》 Small program end wx.getUserInfo Get user information + wx.getStorage obtain 3rd_session After the data , Together wx.request Submit to your server
-》 Own server SQL User data information update , End of the process ;
The train of thought is finished , Next, implement the process
Small program end :
In the applet , Create a new generic JS Do basic support
And reference it on some pages that need to be referenced
var common = require("../Common/Common.js")next , stay Common.js To implement logic
// The user login
function userLogin() {
wx.checkSession({
success: function () {
// Login status exists
},
fail: function () {
// There is no login status
onLogin()
}
})
}
function onLogin() {
wx.login({
success: function (res) {
if (res.code) {
// Initiate network request
wx.request({
url: 'Our Server ApiUrl',
data: {
code: res.code
},
success: function (res) {
const self = this
if ( Logical success ) {
// Get user credentials Storage 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 ( Logical success ) {
//SQL User data updated successfully
}
else {
//SQL Failed to update user data
}
}
})
}
})
}thus , The process of applet is basically completed , Then realize our own service API
Login Example of interface logic
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();
// analysis
userModel ReMsg = JSONUtil.JsonDeserialize<userModel>(content); // analysis
if ((!string.IsNullOrWhiteSpace(ReMsg.openid)) && (!string.IsNullOrWhiteSpace(ReMsg.session_key)))
{
// success Custom build 3rd_session And openid&session_key Bind and return 3rd_session
}
else
{
// error The user... Was not obtained openid or session
}
}
else
{
// error User credentials not obtained code
}UserInfoUpdate The interface will not be repeated here , Users can operate the data according to their own conditions , The relevant parameter information returned when the wechat party calls successfully is as follows
thus , Completed the basic authorization login of the small program and the acquisition of user information .
After reading all the above carefully
What don't you know Welcome to leave a message ~
notes : The above contents have been deleted , Keep only general content . In a specific project, there must be some logic that needs to be adjusted , Please pay attention to the students who quote
Publisher : Full stack programmer stack length , Reprint please indicate the source :https://javaforall.cn/131681.html Link to the original text :https://javaforall.cn
边栏推荐
猜你喜欢

我国蜂窝物联网用户已达 15.9 亿,年内有望超越移动电话用户

Shangtang entered the lifting period: the core management voluntarily banned and strengthened the company's long-term value confidence

关于Keil编译程序出现“File has been changed outside the editor,reload?”的解决方法

数据库实验报告(二)

2022年6月编程语言排行,第一名居然是它?!

Unittest 框架介绍及第一个demo

BAIC bluevale: performance under pressure, extremely difficult period

十年磨一剑:蚂蚁集团可观测性平台 AntMonitor 揭秘

The idea runs with an error command line is too long Shorten command line for...

CVPR 2022 | 基于密度与深度分解的自增强非成对图像去雾
随机推荐
个人商城二开逍遥B2C商城系统源码-可商用版/拼团拼购优惠折扣秒杀源码
MySQL IN 和 NOT IN () 空列表报错
LeetCode 438. 找到字符串中所有字母异位词__滑动窗口
获取键代码
树莓派4B安装tensorflow2.0[通俗易懂]
Nordic nrf52832 flash 下载M4错误
LeetCode. 515. Find the maximum value in each tree row___ BFS + DFS + BFS by layer
十年磨一剑:蚂蚁集团可观测性平台 AntMonitor 揭秘
网站源码整站下载 网站模板源代码下载
Question: what professional qualities should test engineers have?
华为设备配置大型网络WLAN基本业务
TEMPEST HDMI泄漏接收 3
Can servers bundled with flask be safely used in production- Is the server bundled with Flask safe to use in production?
LeetCode. One question of the day: offer II 091 Paint the house (DP problem)
Tempest HDMI leak reception 4
tmux使用
CANN算子:利用迭代器高效实现Tensor数据切割分块处理
ES6 Promise用法小结
Unittest 框架介绍及第一个demo
Continuous delivery -pipeline getting started