当前位置:网站首页>微信小程序开发 – 用户授权登陆「建议收藏」
微信小程序开发 – 用户授权登陆「建议收藏」
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
边栏推荐
- Mutual conversion of pictures in fluent uint8list format and pictures in file format
- Technology sharing | introduction to linkis parameters
- 选择在中金证券上炒股开户可以吗?安全吗?
- 放弃深圳高薪工作回老家
- Node version manager NVM installation and switching
- kubernetes之ingress探索实践
- flutter path_ Provider: ^2.0.10 can get temporary directory
- Database experiment report (II)
- 优雅地翻转数组
- (POJ - 1456) supermarket
猜你喜欢
![[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

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

mysql如何把 一个数据库中的表数据 复制到 另一个数据库中(两个数据库不在同一个数据库链接下)

价值1000毕业设计校园信息发布平台网站源码

Cvpr22 | CMT: efficient combination of CNN and transformer (open source)

Unittest 框架介绍及第一个demo

Oracle和JSON的結合

The exclusive collection of China lunar exploration project is limited to sale!

TEMPEST HDMI泄漏接收 3

英特爾實驗室公布集成光子學研究新進展
随机推荐
Cvpr22 | CMT: efficient combination of CNN and transformer (open source)
華為設備配置大型網絡WLAN基本業務
我国蜂窝物联网用户已达 15.9 亿,年内有望超越移动电话用户
In June 2022, it was the first programming language?!
银行卡借给别人是否构成犯罪
Mutual conversion of pictures in fluent uint8list format and pictures in file format
Mysql的四个隔离级别是如何实现的 (简要)
Google's new paper Minerva: solving quantitative reasoning problems with language models
LeetCode. 515. Find the maximum value in each tree row___ BFS + DFS + BFS by layer
How does MySQL copy table data from one database to another (two databases are not linked to the same database)
Huawei HMS core joins hands with hypergraph to inject new momentum into 3D GIS
商汤进入解禁期:核心管理层自愿禁售 强化公司长期价值信心
数据库实验报告(二)
Getting started with Paxos
Unittest框架中测试用例编写规范以及如何运行测试用例
Mall applet source code open source version - two open
金融壹账通拟7月4日香港上市:2年亏近30亿 市值蒸发超90%
“目标检测”+“视觉理解”实现对输入图像的理解及翻译(附源代码)
Paxos 入门
Get key code