当前位置:网站首页>微信小程序开发 – 用户授权登陆「建议收藏」
微信小程序开发 – 用户授权登陆「建议收藏」
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
边栏推荐
- Oracle和JSON的结合
- 优雅地翻转数组
- Can I choose to open an account on CICC securities? Is it safe?
- Dameng data rushes to the scientific innovation board: it plans to raise 2.4 billion yuan. Feng Yucai was once a professor of Huake
- Tempest HDMI leak receive 3
- Oracle和JSON的結合
- 华泰证券网上开户安全吗?
- Paxos 入门
- Goldfish rhca memoirs: do447 uses ansible to communicate with API -- using ansible tower API to start jobs
- China's cellular Internet of things users have reached 1.59 billion, and are expected to surpass mobile phone users within this year
猜你喜欢
Spam filtering challenges
全局过滤器(处理时间格式)
Applymiddleware principle
TEMPEST HDMI泄漏接收 4
LeetCode.515. 在每个树行中找最大值___逐一BFS+DFS+按层BFS
China's cellular Internet of things users have reached 1.59 billion, and are expected to surpass mobile phone users within this year
Database experiment report (II)
Intel Labs annonce de nouveaux progrès en photonique intégrée
PHP有哪些优势和劣势
京东与腾讯续签合作:向腾讯发行A类股 价值最高达2.2亿美元
随机推荐
Google's new paper Minerva: solving quantitative reasoning problems with language models
NeurIPS 2022 | 细胞图像分割竞赛正式启动!
Unittest框架中测试用例编写规范以及如何运行测试用例
基金国际化的发展概况
编译调试Net6源码
Applymiddleware principle
持续交付-Pipeline入门
Give up high paying jobs in Shenzhen and go back home
Combinaison Oracle et json
Intel Labs announces new progress in integrated photonics research
Database experiment report (II)
Harbor webhook从原理到构建
[AI information monthly] 350 + resources! All the information and trends that can't be missed in June are here! < Download attached >
证券账户随便哪里开都能使用吗 开户安全吗
PHP realizes lottery function
Mall applet source code open source version - two open
2022年6月编程语言排行,第一名居然是它?!
金融壹账通拟7月4日香港上市:2年亏近30亿 市值蒸发超90%
Get key code
Flip the array gracefully