在微信小程序中,往往需要將用戶(hù)信息錄入自己的數(shù)據(jù)庫(kù)中,就得有一個(gè)唯一標(biāo)記區(qū)分用戶(hù),這個(gè)標(biāo)記就是openid。
我這里用云函數(shù)的方式,比較簡(jiǎn)單
先創(chuàng)建一個(gè)名為getOPenid的云函數(shù)
?在云函數(shù)中獲取微信調(diào)用上下文cloud.getWXContext
?可選擇性的返回openid、appid、unionid等,可詳細(xì)查看官方接口文檔
?index.js代碼中修改? ?
// 云函數(shù)入口文件
const cloud = require('wx-server-sdk')
cloud.init()
// 云函數(shù)入口函數(shù)
exports.main = async (event, context) => {
let{ APPID,OPENID}=cloud.getWXContext()
return {
APPID,
OPENID
}
}
接著在頁(yè)面.js中調(diào)用就行
頁(yè)面中.js代碼?
/**
* 頁(yè)面的初始數(shù)據(jù)
*/
data: {
openid : "",
},
/**
* 生命周期函數(shù)--監(jiān)聽(tīng)頁(yè)面加載
*/
onLoad(options) {
wx.cloud.callFunction({
name:'getOpenid',
}).then(res=>{
//res就將openid返回了
this.setData({
openid : res.result.openid
})
//可以把openid放入緩存
wx.setStorageSync('openid',res.result.openid)
})
},
另外我們可以通過(guò)wx.getUserProfile接口讓用戶(hù)授權(quán)獲得用戶(hù)頭像和名字文章來(lái)源:http://www.zghlxwxcb.cn/news/detail-532784.html
//獲取用戶(hù)信息
getUserProfile(){
wx.getUserProfile({
desc: '用于提供個(gè)人服務(wù)', //聲明獲取用途,會(huì)展示在彈框中
success: (res) => {
let user = res.userInfo
wx.setStorageSync('user',user) //保存用戶(hù)信息到本地緩存
this.setData({
isShowUserName : true,
userInfo : user
})
wx.showToast({
title: '登錄成功',
})
},
fail: (res) => {
console.log("獲取用戶(hù)信息失敗",res)
},
})
},
頁(yè)面顯示時(shí)先看看緩存中有沒(méi)有?文章來(lái)源地址http://www.zghlxwxcb.cn/news/detail-532784.html
/**
* 生命周期函數(shù)--監(jiān)聽(tīng)頁(yè)面顯示
*/
onShow(options) {
this.getUserProfile()
var user = wx.getStorageSync('user'); //從本地緩存取用戶(hù)信息
if (user && user.nickName){ //如果用就顯示本地緩存
this.setData({
isShowUserName : true,
userInfo : user
})
}
},
到了這里,關(guān)于微信小程序獲取用戶(hù)的openid以及授權(quán)登錄拿到用戶(hù)頭像及姓名的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!