当前位置:网站首页>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
边栏推荐
- 开发说,“ 这个不用测,回归正常流程就行 “,测试人员怎么办?
- Skip the test cases to be executed in the unittest framework
- 田溯宁投的天润云上市:市值22亿港元 年利润下降75%
- Why must we move from Devops to bizdevops?
- Goldfish rhca memoirs: do447 uses ansible to communicate with API -- using ansible tower API to start jobs
- flutter path_ Provider: ^2.0.10 can get temporary directory
- 放弃深圳高薪工作回老家
- openinstall:微信小程序跳转H5配置业务域名教程
- 十年磨一剑:蚂蚁集团可观测性平台 AntMonitor 揭秘
- JS日期格式化转换方法
猜你喜欢

PHP有哪些优势和劣势

Node version manager NVM installation and switching

Website source code whole site download website template source code download

商汤进入解禁期:核心管理层自愿禁售 强化公司长期价值信心

妙啊!MarkBERT

Value 1000 graduation project campus information publishing platform website source code

YoDA统一数据应用——融合计算在蚂蚁风险场景下的探索与实践

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

Huawei Equipment configure les services de base du réseau WLAN à grande échelle

Neurips 2022 | cell image segmentation competition officially launched!
随机推荐
持续交付-Pipeline入门
VScode快捷键(最全)[通俗易懂]
Global filter (processing time format)
TEMPEST HDMI泄漏接收 4
Packet mode and three streaming modes in SDP protocol
Tempest HDMI leak receive 3
Get key code
LeetCode. One question of the day: offer II 091 Paint the house (DP problem)
activity工作流引擎
Mutual conversion of pictures in fluent uint8list format and pictures in file format
优雅地翻转数组
【AI资讯月刊】350+资源大盘点!6月不容错过的资料和动态,都都都在这里啦!<附下载>
Exposure:A White-Box Photo Post-Processing Framework阅读札记
CPI教程-异步接口创建及使用
Ten years of sharpening a sword: unveiling the secrets of ant group's observability platform antmonitor
mysql如何把 一个数据库中的表数据 复制到 另一个数据库中(两个数据库不在同一个数据库链接下)
Spam filtering challenges
CANN算子:利用迭代器高效实现Tensor数据切割分块处理
流动性质押挖矿系统开发如何制作,dapp丨defi丨nft丨lp流动性质押挖矿系统开发案例分析及源码
英特爾實驗室公布集成光子學研究新進展