如果不获取用户的openid,每次进入皆弹窗提示这个问题,实在是相当的不尽人意;
以下是app.js代码:
var plugin = requirePlugin("chatbot");
App({
onLaunch() {
// 展示本地存储能力
const logs = wx.getStorageSync('logs') || []
logs.unshift(Date.now())
wx.setStorageSync('logs', logs)
wx.cloud.init({
env: 'haibeifen-9ghr19lt5312e331'
})
wx.cloud.callFunction({
name: 'login',
complete: res => {
wx.setStorageSync('openId', res.result.openid)//云函数
}
})
plugin.init({
appid: "CBTuL6NX4nV26XQJTWn0REDqEIQ9Z0", //插件appid
openid: "openId", //用户的openid,必填项,可通过wx.login()获取code,然后通过后台接口获取openid
guideList:["社会成员是指什么","四星信用等次的年度评价指标得分为多少","服役期间荣立三等功的加几分","信用基金包括哪些类别"],
userName: "", // 用户昵称
guideCardHeight:90,
operateCardHeight:0,//调整输入框的高度,建议调一下,默认高度的UI输入框不尽如人意
history:false,//强烈建议配置此项,如若不然可能会显示所有用户的历史记录
navHeight:0,
anonymous: false, // 是否允许匿名用户评价,默认为false,设为ture时,未传递userName、userHeader两个字段时将弹出登录框
success: () => {}, //非必填
fail: (error) => {}, //非必填
});
wx.getSetting({
success: res => {
if (res.authSetting['scope.userInfo']) {
// 已经授权,可以直接调用 getUserInfo 获取头像昵称,不会弹框
wx.getUserInfo({
success: res => {
// 可以将 res 发送给后台解码出 unionId
this.globalData.userInfo = res.userInfo
// 由于 getUserInfo 是网络请求,可能会在 Page.onLoad 之后才返回
// 所以此处加入 callback 以防止这种情况
if (this.userInfoReadyCallback) {
this.userInfoReadyCallback(res)
}
}
})
}
}
})
},
globalData: {
userInfo: null
}
})
附上login云函数代码(index.js):
const cloud = require('wx-server-sdk')
exports.main = async (event, context) => {
// 这里获取到的 openId、 appId 和 unionId 是可信的,注意 unionId 仅在满足 unionId 获取条件时返回
let { OPENID, APPID, UNIONID } = cloud.getWXContext()
return {
OPENID,
APPID,
UNIONID,
}
}
顺带一提,如果不用云开发的话,代码是:
var plugin = requirePlugin("chatbot");
App({
onLaunch: function () {
wx.login({
success: (res) => {
// 通过code换取openid
if (res.code) {
wx.request({
url: "",
method: "post",
data: {
code: res.code,
},
success: (res) => {
if (res.data && res.data.openid) {
// 获取的openid存入storage,方便之后使用
wx.setStorageSync("openId", res.data.openid);
}
},
});
}
plugin.init({
appid: "CBTuL6NX4nV26XQJTWn0REDqEIQ9Z0", //小程序示例账户,仅供学习和参考
openid: "openId", //用户的openid,必填项,可通过wx.login()获取code,然后通过后台接口获取openid
guideList:["社会成员是指什么","四星信用等次的年度评价指标得分为多少"],
userName: "", // 用户昵称
anonymous: false, // 是否允许匿名用户评价,默认为false,设为ture时,未传递userName、userHeader两个字段时将弹出登录框
success: () => {}, //非必填
fail: (error) => {}, //非必填
});
},
fail: () => {},
complete: () => {},
});
},
});
其他如app.json等设置请参考平台官方接入文档