微信小程序注册与登录
登錄
常規的登錄流程時只存在客戶端與開發者服務器兩個端,而微信登錄則具有微信接口服務介入;
如上圖所示關于微信登錄流程:
1、通過wx.getUserProfile獲取用戶數據;
2、點擊授權按鈕調用wx.login獲取用戶的code,這里的code是臨時的code
3、從客戶端發送請求到開發者服務器,傳遞userInfo與code,此處使用的是nodejs搭建的服務
4、在開放者服務器需要去調用微信接口(·https://api.weixin.qq.com/sns/jscode2session?appid=${appid}&secret=${secretid}&js_code=${code}&grant_type=authorization_code·)來校驗登錄憑證,此處的appid,secretid就是自己的小程序appid,sercetId,code也就是前端傳遞的code;
5、如果登錄憑證校驗成功后會返回session_key及用戶的openid,此處的openid是微信用戶的唯一性id;
6、這里就可以查詢數據庫是否存在openid這條數據,如果不存在則將userinfo與openid存儲到數據庫中,如果存在則更新數據即可
7、我們將返回的openid加密后放在token中返回給前端;
8、前端就可以將這個token存儲起來,在需要token進行登錄驗證的接口攜帶token,來進行token驗證。
login: async (req, res) => {const { code } = req.query;const { userInfo } = req.body;const appid = "xxxxx";const secretid = "xxxxxx";const { data } = await axios.get(`https://api.weixin.qq.com/sns/jscode2session?appid=${appid}&secret=${secretid}&js_code=${code}&grant_type=authorization_code`);const token = jwt.sign(data, jwtSecretKey);if (data) {const selectSql = `select * from user where openId = ?`;db.dbConnect(selectSql, data.openid, (err, result) => {if (err) res.send(err);if (result.length === 0) {const insertSql = `insert into user set ?`;db.dbConnect(insertSql,{openId: data.openid,nickName: userInfo.nickName,avatarUrl: userInfo.avatarUrl,},(err, data) => {if (err) res.send(err);if (data.affectedRows !== 1) return res.send("授權失敗,請重試");res.send({token: "Bearer " + token,status: 200,message: "授權成功",});});} else {const sql = `update user set ? where openId = ?`;db.dbConnect(sql,[{openId: data.openid,nickName: userInfo.nickName,avatarUrl: userInfo.avatarUrl,},data.openid,],(err, result) => {if (err) return res.cc(err);res.send({token: "Bearer " + token,status: 200,messages: "授權成功123123",});});}});}},
注冊
注冊實際上是登錄時將用戶數據存儲在數據庫的一個操作。
獲取用戶數據wx.getUserProfile
調用方式: 頁面產生點擊事件才可以調用。
wx.getUserProfile({desc: '用于完善會員資料', // 聲明獲取用戶個人信息后的用途,后續會展示在彈窗中,請謹慎填寫success: (res) => {console.log(res)}})
當基礎庫小于等于2.27.0版本時獲取用戶信息會讓用戶進行允許操作,并且能獲取到用戶頭像及微信名。
當基礎庫大于2.27.0版本時,不會彈出允許彈窗,但是返回的用戶數據中頭像為微信默認灰色頭像,nickName返回為微信用戶。
頭像昵稱填寫功能
微信推薦單獨開一個頁面讓用戶能設置頭像及昵稱,提供的兩個button會默認返回微信頭像和微信昵稱;
使用方法如下:
1、設置頭像
open-type=“chooseAvatar”
<buttonclass="avatar-wrapper"open-type="chooseAvatar"bind:chooseavatar="onChooseAvatar"><image class="avatar" src="{{ avatarUrl }}"></image></button>
2、設置昵稱
type為nickname
<input type="nickname" class="weui-input" value="nickName" onchange="setNickName" placeholder="請輸入昵稱" />
總結
以上是生活随笔為你收集整理的微信小程序注册与登录的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 编辑词条
- 下一篇: ddr老化测试_手把手教你评估和测试固态