当前位置:网站首页>微信小程序开发 – 用户授权登陆「建议收藏」
微信小程序开发 – 用户授权登陆「建议收藏」
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
边栏推荐
- Ten years of sharpening a sword: unveiling the secrets of ant group's observability platform antmonitor
- 【MAUI】为 Label、Image 等控件添加点击事件
- Huawei Equipment configure les services de base du réseau WLAN à grande échelle
- Development overview of fund internationalization
- LeetCode. 515. Find the maximum value in each tree row___ BFS + DFS + BFS by layer
- MIT's latest paper, "the need for interpretable features: motivation and classification": building interpretability in the constituent elements of machine learning models
- Getting started with Paxos
- 名创拟7月13日上市:最高发行价22.1港元 单季净利下降19%
- "Target detection" + "visual understanding" to realize the understanding and translation of the input image (with source code)
- MySQL IN 和 NOT IN () 空列表报错
猜你喜欢

Intel Labs announces new progress in integrated photonics research

kubernetes之ingress探索实践

【MAUI】为 Label、Image 等控件添加点击事件

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

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

“目标检测”+“视觉理解”实现对输入图像的理解及翻译(附源代码)

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

《数据安全法》出台一周年,看哪四大变化来袭?
![[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 >

商城小程序源码开源版-可二开
随机推荐
Tianrunyun, invested by Tian Suning, was listed: its market value was 2.2 billion Hong Kong, and its first year profit decreased by 75%
Whether lending a bank card to others constitutes a crime
Ask everyone in the group about the fact that the logminer scheme of flick Oracle CDC has been used to run stably in production
華為設備配置大型網絡WLAN基本業務
Valgrind usage of memory leak locating tool
Have the bosses ever done the operation of sink shunting and writing to Clickhouse or other databases.
Numpy的矩阵
优雅地翻转数组
TEMPEST HDMI泄漏接收 4
编译调试Net6源码
软件项目管理 9.2.软件项目配置管理过程
Mingchuang plans to be listed on July 13: the highest issue price is HK $22.1, and the net profit in a single quarter decreases by 19%
Cann operator: using iterators to efficiently realize tensor data cutting and blocking processing
Give up high paying jobs in Shenzhen and go back home
PHP realizes lottery function
华泰证券网上开户安全吗?
The first anniversary of the data security law, which four major changes are coming?
mysql如何把 一个数据库中的表数据 复制到 另一个数据库中(两个数据库不在同一个数据库链接下)
CVPR 2022 | 基于密度与深度分解的自增强非成对图像去雾
【MAUI】为 Label、Image 等控件添加点击事件