微信小程序注册登陆云函数 #202
virgoone
started this conversation in
Share & Show
Replies: 1 comment
-
像这样用 "```" 包住你的代码 排版,就不会乱了。 exports.main = async function (ctx: FunctionContext) {
// body, query 为请求参数, auth 是授权对象
const { code } = ctx.body || {}
if (!code) {
return { code: 10400, message: 'invalid code' }
}
const response = await axios.get(
'https://api.weixin.qq.com/sns/jscode2session',
{
params: {
appid: WECHAT_MINI_APP_ID,
secret: WECHAT_MINI_APP_SECRET,
grant_type: 'authorization_code',
js_code: code,
},
},
)
const { openid } = response.data
if (!openid) {
return { code: 10400, message: 'invalid code' }
}
// 数据库操作
const db = cloud.database()
const res = await db.collection('_userprofile').where({
openid,
appid: WECHAT_MINI_APP_ID,
})
.getOne()
let userId = null
if (!res.data) {
const { id } = await db.collection('_userprofile')
.add({
openid,
is_authorized: false,
appid: WECHAT_MINI_APP_ID,
nickName: '',
avatar: '',
created_at: new Date()
})
userId = id
} else {
userId = res.data._id
}
console.log('get user by openid', res)
const payload = {
uid: userId,
exp: Math.floor(Date.now() / 1000) + 60 * 60 * 24 * 7
}
const access_token = cloud.getToken(payload)
return {
...res.data,
_id: userId,
access_token,
expires: payload.exp
}
} |
Beta Was this translation helpful? Give feedback.
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
-
Gist: https://gist.github.com/virgoone/e1b5342d2ce95a57ae60a8b7c81657cc
Beta Was this translation helpful? Give feedback.
All reactions