当前位置:网站首页>[2022 wechat applet demining] how to correctly obtain openid in cloud development and non cloud development environments?
[2022 wechat applet demining] how to correctly obtain openid in cloud development and non cloud development environments?
2022-07-18 05:54:00 【Concise200】
openid How to get
Preface
Recently, I was sorting out my first applet project , Found some Bug. Record the solution process here , On the one hand, sort out knowledge , On the other hand, help everyone clear the mine .
Text
1、 Error correction process
In applet development , We often call wx.login and wx.getUserProfile To enable users to authorize and collect users openid、 user name 、 Head portrait and other information .
The official documents describe these two interfaces as follows
wx.login(Object object)( Does not support to Promise style call )
Call interface get Login credentials (code). Exchange user login status information through credentials , Include the user's unique identity in the current applet (openid)、 The unique identity of wechat open platform account (unionid, If the current applet has been bound to wechat open platform account ) And the session key of this login (session_key) etc. . The communication of user data encryption and decryption depends on the session key .
wx.getUserProfile(Object object)( Support with Promise style call )
Get user information . Page click event ( for example button On bindtap In the callback ) Can only be called after , Each request will bring up an authorization window , The user agrees and returns userInfo.
In this way, I don't think there is any connection between the two , The order of precedence does not affect , I felt the same way at first , The code is as follows
getInfo(){
wx.getUserProfile({
desc: ' Sign in ',
success: (res) => {
console.log('getUserProfile', res)
let changeData = {
}, // need setData The data of , once setData The operation of
userInfo = {
username: res.userInfo.nickName,
userphoto: res.userInfo.avatarUrl
}
changeData.hasUserInfo = true
wx.login({
// Successfully put back
success: (res) => {
let code = res.code
wx.request({
url: `https://api.weixin.qq.com/sns/jscode2session?appid=${
appid}&${
this.data.my.lock}=${
this.data.my.key}&js_code=${
code}&grant_type=authorization_code`,
success: (res) => {
userInfo.openid = res.data.openid
changeData.userInfo = userInfo
this.setData(changeData)
app.globalData.openid = res.data.openid;
wx.setStorageSync('userInfo', userInfo)
db.collection('users')
.where({
openid:res.data.openid
})
.get().then((res)=>{
if(res.data.length===0){
db.collection('users').add({
data: {
...this.data.userInfo
}
})
db.collection('userData').add({
data:{
openid:res.data.openid,
late:0,
notCome:0,
cancel:0,
leaveEarly:0,
signIn:0
}
})
}
})
}
})
}
})
}
})
},
It can succeed in wechat developer tools and real machine debugging , however preview You cannot authorize successfully .
At first, I thought it was a wechat applet Bug, Try the experience version with a friend's mobile phone , Still unable to authorize successfully ., That should be my problem , Try debugging with your phone , It is found that the authorization is successful when debugging , It can also be printed and obtained in the log userInfo.

I don't understand , But I was shocked ! Read the code again , Feeling is wx.login and wx.getUserProfile The problem of , I checked it on the Internet , It's a discovery !!!

in other words , We must first call wx.login Get the latest code, Otherwise, it is easy to decrypt and fail . Guarantee wx.login It's better than wx.getUserProfile To complete . Put... Directly wx.getUserProfile Put it in wx.login It's OK in the callback ?
NO!!!wx.getUserProfile Generate a click event on the page ( for example button On bindtap In the callback ) Can only be called after , Don't put it in the callback .
Online promise.all How to deal with , I didn't try, but I don't think I can .all Just put login and getinfo Running at the same time , But these two are actually asynchronous , It is actually impossible to determine which triggers first .
I have searched for a long time and have no answer , Finally, I asked two predecessors who specialize in wechat applet development , I found that everyone solved it like this !!!


because code There is a time limit , So it is usually called directly when entering the page wx.login obtain code, And then use code Exchange for openid, Storage openid. When the user clicks the authorization button , We can call wx.getUserProfile.
The code is modified as follows :
var openid=''; // Don't render to the page, so don't exist data in
onLoad(options) {
var t = this
var userInfo = wx.getStorageSync('userInfo')
if(userInfo){
this.setData({
userInfo:userInfo,
hasUserInfo:true,
})
}else{
db.collection('importantKey')
.get()
.then((res)=>{
var my = {
...res.data[0]} // The key cannot be written in clear text , Therefore, it is obtained in the database
wx.login({
// Successfully put back
success: (res) => {
let code = res.code
wx.request({
url: `https://api.weixin.qq.com/sns/jscode2session?appid=${
appid}&${
my.lock}=${
my.key}&js_code=${
code}&grant_type=authorization_code`,
success: (res) => {
openid = res.data.openid
}
})
}
})
})
}
},
getInfo(){
var changeData = {
}// need setData The data of , once setData The operation of , Optimize performance
wx.getUserProfile({
desc: ' Sign in ',
success: (res) => {
var userInfo = {
username: res.userInfo.nickName,
userphoto: res.userInfo.avatarUrl,
openid:openid
}
changeData.hasUserInfo = true
changeData.userInfo = userInfo
this.setData(changeData) // Disposable setData
wx.setStorageSync('userInfo', userInfo)
db.collection('users')
.where({
openid:userInfo.openid
})
.get().then((res)=>{
console.log('openid',openid);
if(res.data.length===0){
db.collection('users').add({
data: {
...userInfo
}
})
db.collection('userData').add({
data:{
openid:userInfo.openid,
late:0,
notCome:0,
cancel:0,
leaveEarly:0,
signIn:0
}
})
}
})
}
})
},
Do you think this is right ? wrong !!!
If you use it directly , You will Found another new hole in wechat applet .
Is to test directly in the applet developer tool , Use real machine debugging , There's no problem , however Once the code is uploaded , Use the experience version of the applet to test , You can't get openid, Strangely enough , If the debugging mode is enabled in the experience version , You can get it again . in other words The development environment and production environment have the same code , The effect is different .
After a long time of searching for information , obtain openid You can't get it directly on wechat client , because api.weixin.qq.com Writing to the domain name configuration is invalid , The backend must call . You should use the back end to get openid And then back to the front end .
2、 summary
Non cloud development
If it weren't for cloud development , stay onLoad You can call wx.login obtain code, Then pass it to the back end , Let the backend get openid Back to the front end
Development of cloud
If it is cloud development , You can directly create a cloud function getopenid.
index.js The code is as follows
// Cloud function entry file
const cloud = require('wx-server-sdk')
cloud.init()
// Cloud function entry function
exports.main = async (event, context) => {
const wxContext = cloud.getWXContext()
return {
event,
openid: wxContext.OPENID,
appid: wxContext.APPID,
unionid: wxContext.UNIONID,
}
}
On the authorization page onLoad Function function call
var openid=''; // Don't render to the page, so don't exist data in
onLoad(options) {
var t = this
var userInfo = wx.getStorageSync('userInfo')
if(userInfo){
this.setData({
userInfo:userInfo,
hasUserInfo:true,
})
}else{
wx.cloud.callFunction({
// Call the cloud function to get openid
name: 'getopenid',
complete: res => {
openid = res.result.openid;
}
})
}
},
If you find this article helpful , Remember the praise. 、 Collection ~
边栏推荐
- 阿里云E-MapReduce 极客大赛开放报名 数十万奖金等你挑战
- Understand │ what is cross domain? How to solve cross domain problems?
- Operation and maintenance - skill hodgepodge
- 磁盘分区标为活动的方法及取消磁盘分区标为活动的方法
- The bill module of freeswitch
- 12
- Mysql/Mairadb主从复制
- SYD_Calculator技巧二[管理COS]
- Alibaba cloud e-mapreduce geek competition is open for registration. Hundreds of thousands of bonuses are waiting for you to challenge
- Huawei cloud stack opens its framework to the south to help ecological partners enter the cloud efficiently
猜你喜欢

助力开发者,全方位解读 APISIX 测试案例

阿里云架构师马颂:云上高性能计算助力基因测序

JMM memory model

OPENGL学习(一)认识OPENGL和各种库

电脑网速检测在哪里可以找到

SQL daily practice (Niuke new question bank) - day 2: condition query

CEO干货| CSDN演讲回顾:如何利用低代码提升研发和IT效能?
![[comprehensive pen test] difficulty 2/5, recursive application, prefix and optimization](/img/eb/fad095522129d13be7675a50e77af7.png)
[comprehensive pen test] difficulty 2/5, recursive application, prefix and optimization

梅科尔工作室-李庆浩 sql语句笔记

要想不踩SaaS那些坑,得先了解“SaaS架构”
随机推荐
[special topic of golang database 4] golang language operation PostgreSQL for addition, deletion, modification and query
go+mysql+redis+vue3简单聊室,第4弹:gin的websocket通讯和多go程任务处理
Sql笔记
七 异常处理
【动态规划】—— 数位统计DP
宝藏功能上新!日历视图+卡片视图强强联合,工作效率快到飞起
了解JVM语言
Do not know how to improve the visual language model? Zhejiang University and Lianhui Research Institute put forward a new multi-dimensional evaluation framework
Double data rate synchronous dynamic random access memory (DDR SDRAM)
测试开发的六大能力
[Golang数据库专题4]Golang语言操作PostgreSQL进行增删改查
CAS compare and swap exchange after comparison
About security details timing attack
数据库
【用户文章】P4合并实践指南之实例拆解Resolve
O & M - mélange de compétences
Is it safe for qiniu securities to open an account? Is it reliable?
Volatile low configuration syn, realizing visibility and order
CEO dry goods | CSDN speech review: how to use low code to improve R & D and it efficiency?
中国人力资源数字化生态图谱-灵活用工市场
