当前位置:网站首页>微信小程序开发 – 用户授权登陆「建议收藏」
微信小程序开发 – 用户授权登陆「建议收藏」
2022-07-01 11:12:00 【全栈程序员站长】
大家好,又见面了,我是你们的朋友全栈君。
本篇将帮助读者实现基于 微信开发者工具 & C#环境 下的用户在小程序上的授权登陆。
准备:
微信开发者工具下载地址:https://developers.weixin.qq.com/miniprogram/dev/devtools/download.html
微信小程序开发文档:https://developers.weixin.qq.com/miniprogram/dev/index.html
开发:
在开发之初,我们需要先明确微信方已经制定好的授权登陆流程,参看 官方API – 登陆接口。
你会看到微信方为开发者制定好的登陆授权流程:
如图,即为一个顺向的用户登陆授权的流程。
为什么说它是一个顺向的流程呢?因为在真正的小程序开发中,我们并不确定用户何时需要起调如上的登陆流程(如:用户在某些特定场景下的凭证丢失,但Ta并没有退出小程序而是在小程序内部做跳转等相关操作,即有可能导致一些预期之外的异常),所以,我们需要在这个顺向的流程之外,加一层检测机制,来解决这些异常场景,而官方API中,wx.checkSession 刚好可以一定程度上解决这个问题。
那么,我们的认证流程其实应该是:
– 小程序 wx.checkSession 校验登陆态为失效
– success :接口调用成功的回调函数,session_key未过期,流程结束;
– fail :接口调用失败的回调函数,session_key已过期
-》 小程序端 wx.login 获取code 并 wx.request 提交code给己方服务器
-》 己方服务器 提交Appid + appSecret + code 到微信方服务器 获取 session_key & openid
-》 己方服务器 根据 session_key & openid 生成 3rd_session(微信方提出的基于安全性的考虑,建议开发者不要将openid等关键性信息进行数据传输) 并返回 3rd_session 到小程序端
-》 小程序端 wx.setStorage 存储 3rd_session ( 在后续用户操作需要凭证时 附带该参数 )
-》 小程序端 wx.getUserInfo 获取用户信息 + wx.getStorage 获取 3rd_session 数据后,一并 wx.request 提交给己方服务器
-》 己方服务器 SQL用户数据信息更新,流程结束;
思路整理完毕,接下来实现流程
小程序端:
在小程序中,新建一个通用的JS做基础支持
并在一些需要引用的页面进行引用
var common = require("../Common/Common.js")接着,在Common.js 中实现逻辑
//用户登陆
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更新用户数据失败
}
}
})
}
})
}至此,小程序端的流程基本实现完毕,接着实现己方服务API
Login 接口逻辑范例
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<userModel>(content); //解析
if ((!string.IsNullOrWhiteSpace(ReMsg.openid)) && (!string.IsNullOrWhiteSpace(ReMsg.session_key)))
{
// 成功 自定义生成3rd_session与openid&session_key绑定并返回3rd_session
}
else
{
// 错误 未获取到用户openid 或 session
}
}
else
{
// 错误 未获取到用户凭证code
}UserInfoUpdate 接口在此不加赘述,用户根据自身情况对数据进行操作即可,微信方调用成功时返回的相关参数信息如下
至此,完成了小程序基本的授权登陆及用户信息的获取。
认真看完以上所有后
有啥不懂的 欢迎留言提问~
注:以上内容有所删减,仅保留通用内容。在具体项目中必定存在部分逻辑需要调整,引鉴的同学请注意
发布者:全栈程序员栈长,转载请注明出处:https://javaforall.cn/131681.html原文链接:https://javaforall.cn
边栏推荐
- MIT's latest paper, "the need for interpretable features: motivation and classification": building interpretability in the constituent elements of machine learning models
- LeetCode. One question of the day: offer II 091 Paint the house (DP problem)
- Packet mode and three streaming modes in SDP protocol
- Nordic nrf52832 flash 下载M4错误
- No statements may be issued when any streaming result sets are open and in use on a given connection
- Huawei HMS core joins hands with hypergraph to inject new momentum into 3D GIS
- Win平台下influxDB导出、导入
- 为什么一定要从DevOps走向BizDevOps?
- 网站源码整站下载 网站模板源代码下载
- 【AI资讯月刊】350+资源大盘点!6月不容错过的资料和动态,都都都在这里啦!<附下载>
猜你喜欢
![[paper reading] trajectory guided control prediction for end to end autonomous driving: a simple yet strong Ba](/img/fa/f2d24ee3dbbbe6332c84a82109338e.png)
[paper reading] trajectory guided control prediction for end to end autonomous driving: a simple yet strong Ba
![[AI information monthly] 350 + resources! All the information and trends that can't be missed in June are here! < Download attached >](/img/62/562e93e66addc8e86c0a19bc514389.png)
[AI information monthly] 350 + resources! All the information and trends that can't be missed in June are here! < Download attached >

The list of winners of the digital collection of "century master" was announced

Uncover the secrets of new products! Yadi Guanneng 3 multi product matrix to meet the travel needs of global users

The first anniversary of the data security law, which four major changes are coming?

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

Numpy的矩阵

Mobile hard drive reads but does not display drive letter

Oracle和JSON的结合

Mall applet source code open source version - two open
随机推荐
Give up high paying jobs in Shenzhen and go back home
Database experiment report (I)
Intel Labs announces new progress in integrated photonics research
CANN算子:利用迭代器高效实现Tensor数据切割分块处理
选择在中金证券上炒股开户可以吗?安全吗?
持续交付-Pipeline入门
YoDA统一数据应用——融合计算在蚂蚁风险场景下的探索与实践
Harbor webhook从原理到构建
Compliance management of fund managers
Technology sharing | introduction to linkis parameters
No statements may be issued when any streaming result sets are open and in use on a given connection
力扣(LeetCode)181. 超过经理收入的员工(2022.06.29)
Oneconnect plans to be listed in Hong Kong on July 4: a loss of nearly 3 billion in two years, with a market capitalization evaporation of more than 90%
TEMPEST HDMI泄漏接收 3
Export and import of incluxdb on WIN platform
LeetCode 438. Find all letter ectopic words in the string__ sliding window
【MAUI】为 Label、Image 等控件添加点击事件
CPI教程-异步接口创建及使用
Rising stars in Plant Sciences (rsps2022) final Science Lecture (6.30 pm)
放弃深圳高薪工作回老家