uniCloud云函数——微信小程序登录凭证校验[code2Session](即:使用 code 换取 openid 和 session_key 等信息)解决方案
Posted Starzkg
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了uniCloud云函数——微信小程序登录凭证校验[code2Session](即:使用 code 换取 openid 和 session_key 等信息)解决方案相关的知识,希望对你有一定的参考价值。
接口文档
https://developers.weixin.qq.com/miniprogram/dev/api-backend/open-api/login/auth.code2Session.html
解决方案
'use strict';
exports.main = async (event, context) => {
//event为客户端上传的参数
console.log('event : ', event)
let result = {}
if("mp-weixin"==context.PLATFORM){
result = (await uniCloud.httpclient.request("https://api.weixin.qq.com/sns/jscode2session",{
method: "GET",
data: {
'appid': "xxx",
'secret': "xxx",
'js_code': event.code,
'grant_type': "authorization_code"
},
dataType: 'json' // 指定返回值为json格式,自动进行parse
})).data
return {code:0,data: result}
}
//返回数据给客户端
return {code:-1,data: result}
};
调用示例
uniCloud.callFunction({
name: 'code2Session',
data: {code}
}).then((res) => {
if (res.result.code === 0) {
let openid = res.result.data.openid;
uni.setStorageSync('openid', openid)
}
}).catch((e) => {
console.error(e)
})
参考文章
以上是关于uniCloud云函数——微信小程序登录凭证校验[code2Session](即:使用 code 换取 openid 和 session_key 等信息)解决方案的主要内容,如果未能解决你的问题,请参考以下文章