步骤
1.适配不同机型来创建微信授权按钮(可自定义 具体看微信API文档)
2.通过getSetting检查是否有授权过
3.有授权则会有scope.userInfo字段,可直接通过getUserInfo获取用户信息,否则获取信息失败,注意:openid等隐私数据需要解密获得,或者通过外部自主服务器的接口获得,因为微信小游戏不允许访问带api.weixin.com域名的接口
4.通过createUserInfoButton创建一个授权按钮,点击按钮会弹窗授权
5.onTap注入点击事件
setAuthBtn(btnNode:cc.Node){
let btnSize = cc.size(btnNode.width+10,btnNode.height+10);let frameSize = cc.view.getFrameSize();let winSize = cc.director.getWinSize();// console.log("winSize: ",winSize);// console.log("frameSize: ",frameSize);//适配不同机型来创建微信授权按钮this.left = (winSize.width*0.5+btnNode.x-btnSize.width*0.5)/winSize.width*frameSize.width;this.top = (winSize.height*0.5-btnNode.y-btnSize.height*0.5)/winSize.height*frameSize.height;this.weight = btnSize.width/winSize.width*frameSize.width;this.height = btnSize.height/winSize.height*frameSize.height;// console.log("button pos: ",cc.v2(left,top));// console.log("button size: ",cc.size(width,height));let self=this;self._wx.getSetting({
success (res){
if (res.authSetting['scope.userInfo']){
console.log(`微信已授权`)self.getUserInfo(success,fail);}else{
//未授权console.log(`弹窗授权:w`+self.weight+" h:"+self.height+" l:"+self.left+" t:"+self.top)//弹窗授权self.authBtn=self._wx.createUserInfoButton({
type: 'text',text: '',style: {
left: self.left,top: self.top,width: self.weight,height: self.height,backgroundColor: '#ff0000',color: '#ffffff',}});//点击授权self.authBtn.onTap(res => {
if(res.errMsg === 'getUserInfo:ok'){
//授权成功console.log(`获取用户信息成功`);var userInfo = res.userInfovar nickName = userInfo.nickNamevar avatarUrl = userInfo.avatarUrlvar gender = userInfo.gender //性别 0:未知、1:男、2:女var province = userInfo.provincevar city = userInfo.cityvar country = userInfo.countryconsole.log("nickName:"+nickName+" avatarUrl:"+avatarUrl+" gender:"+gender+" province:"+province+" city:"+city+" country:"+country+" openid:"+userInfo.openId+" unionId:"+userInfo.unionId);userInfo.openId=self.openId;self.authBtn.destroy();self.authBtn=null;} /* else{self.authBtn.destroy();fail&&fail();} */ });}}});}