WeChat applet authorization login wx.getUserProfile cannot get nickname and avatar solution

I made a small program half a year ago, updated two texts, re-uploaded and passed the review, it was a tragedy, the nicknames of new users were all changed to WeChat users, and the avatars were all changed to default avatars. After checking the code for a long time, I couldn’t find the reason. It was quite a big headache. , I searched the document, I was embarrassed, the newly updated rules on November 9th no longer return nickname and avatar values... You need to use the avatar nickname acquisition ability to trigger the acquisition!

 solution

The first step is to click the login button to pop up a layer, obtain the OPENID value and mobile phone number information through authorization, and complete the registration first.

 

 The second step is to verify whether the nickname and avatar are empty after completing the registration. If it is empty, the data setting layer will pop up to verify whether the information is filled. Click the avatar button to get WeChat or upload a custom avatar, click the nickname column to get a WeChat nickname or a custom nickname. save!

 

 

 

 

wxml code 

  <view class="index">
       
        <view class="head">
            <view class="headbox">
                <view class="position">

                    <view class="face">
                 

                        <view class="img">
                            <block wx:if="{
   
   {avatarimg}}">
                                <image class="self" mode="widthFix" src="{
   
   {avatarimg}}"></image>
                            </block>
                            <block wx:else>
                                <image mode="widthFix" src="headlogonew.png"></image>
                            </block>
                        </view>

                        <block wx:if="{
   
   {nickname}}">
                            <view class="name">{
   
   {nickname}}</view>
                        </block>
                        <block wx:else>
                            <view class="name" bindtap="getUserProfile">点击登录/注册</view>
                        </block>
                    </view>
                    <block wx:if="{
   
   {isShowPhone}}">
                        <view class="dialog-mask"></view>
                          <view class="dialog-info">
                            <view class="dialog-title">请点击获取授权选择绑定的手机号</view>
                            <view class="dialog-footer"><button class="button" open-type="getPhoneNumber" bindgetphonenumber="getPhoneNumber">获取授权</button></view>
 
                        </view>
                    </block> 

                    <block wx:if="{
   
   {isShowUserInfo}}">
                        <view class="dialog-mask"></view>
                          <view class="dialog-info">
                            <view class="dialog-title">请设置头像和昵称</view>
                            <view class="dialog-footer dialog-line">
                            <div class="set">
                                <button open-type="chooseAvatar"  bindchooseavatar="onChooseAvatar">
                                    <block wx:if="{
   
   {avatarimg}}">
                                <image mode="widthFix" src="{
   
   {avatarimg}}"></image>
                            </block>
                            <block wx:else>
                                <image mode="widthFix" src="/images/uploadface.png"></image>
                            </block>
                               
                                </button>
                                </div>
                                <div class="set">
                                <input  placeholder="请输入您的昵称" type="nickname" value="{
   
   {nickname}}" bindblur="bindblur"></input>
                                </div>
                               <div class="set">
                                <button class="button" bindtap="setBtnTap">保存</button>
                                </div>
                                </view>
                        </view>
                    </block> 
                    
                    <div class="clear"></div>
                </view>
            </view>
        </view>
    </view>

js code

/**
     * 页面的初始数据
     */
    data: {

        isShowPhone: false, //默认先不显示获取手机号
        isShowUserInfo: false,
        user_id: '',
        phone: '',
        avatarimg: '',
        nickname:'',
    },
    /** 获取昵称信息 */
    bindblur(e) {
        this.data.nickname = e.detail.value
    },
    /** 更换头像 */
    onChooseAvatar(e) {
        var that = this
        wx.getFileSystemManager().readFile({
            filePath: e.detail.avatarUrl, //选择图片返回的相对路径 
            encoding: 'base64',
            success: res => {
                wx.request({
                    url: app.SiteUrl + "imgupload",
                    data: {
                        file: 'data:image/png;base64,' + res.data,
                    },
                    header: {
                        'content-type': 'multipart/form-data'
                    },
                    success: function (res) {
                        if (res.data.status == 'success') {
                            that.setData({
                                avatarimg: res.data.data.image_name,
                                //isShowUserInfo: false,
                            })
                        } else {
                            console.log('fail');
                        }
                    }
                })
                console.log('data:image/png;base64,' + res.data)
            }
        })
    },
    setBtnTap() {
        var that = this
        if (that.data.avatarimg.length == 0) {
            wx.showToast({
                title: '请上传头像!',
                icon: 'error',
                duration: 1500
            })
        } else if (that.data.nickname.length == 0) {
            wx.showToast({
                title: '请填写昵称!',
                icon: 'error',
                duration: 1500
            })
        } else {
            wx.request({
                url: app.SiteUrl + "setUserInfo",
                data: {
                    user_id: that.data.user_id,
                    nickname: that.data.nickname,
                    avatarimg: that.data.avatarimg,
                },
                method: 'GET',
                header: {
                    'content-type': 'application/json'
                },
                success: function (res) {
                    if (res.data.data.phone != '') {
                        that.setData({
                            isShowPhone: false,
                            isShowUserInfo: false,
                            nickname: that.data.nickname,
                        })
                        wx.setStorageSync('user_id', res.data.data.user_id);
                        wx.setStorageSync('phone', res.data.data.phone);
                        wx.setStorageSync('nickname', that.data.nickname);
                        wx.setStorageSync('avatarimg', that.data.avatarimg);
                        wx.showToast({
                            title: '更新成功!',
                            icon: 'success',
                            duration: 1500
                        });
                    } else {
                        that.setData({
                            isShowUserInfo: false,
                            isShowPhone: true,
                        })
                    }
                }
            })
        }

    },

    getUserProfile() {
        var that = this
        wx.showLoading({
            title: '获取授权中'
        })
        wx.getUserProfile({
            desc: '使用户得到更好的体验',
            success: (res) => {
                wx.hideLoading()
                wx.request({
                        url: app.SiteUrl + "getopenid",
                        data: {
                            code: that.data.code
                        },
                        method: 'GET',
                        header: {
                            'content-type': 'application/json'
                        },
                        success: function (res) {
          
                            that.setData({
                                session_key: res.data.data.session_key,
                                openid: res.data.data.openid
                            })
                 
                            wx.request({
                                url: app.SiteUrl + "checkuser",
                                data: {
                                    openid: res.data.data.openid
                                },
                                method: 'GET',
                                header: {
                                    'content-type': 'application/json'
                                },
                                success: function (res) {
                            
                                    if (res.data.data.phone == '') {
                                        that.setData({
                                            isShowUserInfo: false,
                                            isShowPhone: true,
                                        })
                                    }else if (res.data.data.nickname == '') {
                                        that.setData({
                                            isShowUserInfo: true,
                                            isShowPhone: false,
                                        })
                                    }else {
                                        that.setData({
                                            isShowPhone: false,
                                            isShowUserInfo: false,
                                            user_id:res.data.data.user_id,
                                            phone:res.data.data.phone,
                                            nickname:res.data.data.nickname,
                                            avatarimg:res.data.data.avatarimg,
                                        })
                                        wx.setStorageSync('user_id', res.data.data.user_id);
                                        wx.setStorageSync('phone', res.data.data.phone);
                                        wx.setStorageSync('nickname', res.data.data.nickname);
                                        wx.setStorageSync('avatarimg', res.data.data.avatarimg);
                                    } 
                                }
                            })
                        }
                    }),
                    that.setData({

                    })
            },
            fail: res => {
                wx.hideLoading()
                console.log("获取用户信息失败", res)
            }
        })
    },

    getLogin() {
        //code获取成功,保存为当前页面的全局变量code
        wx.login({
            success: res => {
                this.setData({
                    code: res.code
                })
            },
            fail: res => {
                //失败
            }
        })
    },
    getPhoneNumber: function (e) {
        // 登录
        wx.showLoading({
            title: '加载中...'
        })
        var self = this
        wx.login({
            success: res => {
                wx.hideLoading()
                var encryptedData = encodeURI(e.detail.encryptedData) // 完整的加密数据
                var iv = e.detail.iv //加密算法的初始向量
                console.log('encryptedData', encryptedData)
                console.log('iv', iv)
                wx.request({
                    url: app.SiteUrl + 'getPhoneNumber',
                    data: {
                        'session_key': self.data.session_key,
                        'encryptedData': encryptedData,
                        'iv': iv,
                    },
                    method: 'GET',
                    header: {
                        'content-type': 'application/json'
                    },
                    success: function (res) {
                        wx.hideLoading()
                        if (res.data.status == 1) {
                            self.setData({
                                phone: res.data.data.phoneNumber,
                                isShowPhone: false,
                                isShowUserInfo: false,
                            })
                            wx.setStorageSync('phone', res.data.data.phoneNumber);
                            if (self.data.nickname == '') {
                                wx.request({
                                    url: app.SiteUrl + 'login',
                                    data: {
                                        phone: self.data.phone,
                                        password: 888888,
                                        openid: self.data.openid,

                                    },
                                    success: function (res) {
                                        if (res.data != null) {
                                            wx.showToast({
                                                title: "" + res.data.msg + "",
                                                icon: 'loading',
                                                duration: 2000
                                            })
                                                self.setData({
                                                    user_id: res.data.data.user_id,
                                                    isShowPhone: false,
                                                    isShowUserInfo: true,
                                                })
                                            wx.setStorageSync('user_id', res.data.data.user_id);
                                        }
                                    }
                                });
                            }
                        }
                    },
                    fail: function (err) {
                        console.log(err);
                    }
                })
            }
        })
    },

TP5 interface

    //登陆时先判断用户是否存在,OPENID唯一值
	public function api_checkuser() {
		$attr = $this->getattr();
		$openid = trim($attr['openid']);
			$usercount = db('user')->where(['openid' => $openid])->count();
			if ($usercount!=0) {
			    $usercheck = db('user')->where(['openid' => $openid])->find();
				$newid = $usercheck['id'];
				$phone = $usercheck['phone'];
				$nickname = $usercheck['nickname'];
				$avatarimg=$usercheck['avatarimg'];
				$tiptext = "0";
			} else {
			    $newid='';
			    $phone = '';
			    $nickname = '';
				$avatarimg='';
			    $tiptext = "1";
			}
		$json = $this->message(1,$tiptext,["user_id" => $newid,"phone" => $phone,"nickname" => $nickname,"avatarimg" => $avatarimg]);
		return $this->returnjson($json, $attr['callback']);
	}
	
	
	//登陆/注册
	public function api_login() {
		$attr = $this->getattr();
		$phone = trim($attr['phone']);
		$password = trim($attr['password']);
		$openid = trim($attr['openid']);
		$nickname = trim($attr['nickname']);
		$avatarimg = trim($attr['avatarimg']);
		$gender = trim($attr['gender']);
		$params = [
			"phone" => $phone,
			"password" => md5($password),
			"openid" => $openid,
			"nickname" => $nickname,
			"avatarimg" => $avatarimg,
			"gender" => $gender,
			"status" => 1,
			"create_time" => time(),
		];
		$newid = 0;
		try {
			$newid = db('user')->where(['openid' => $openid])->count() >= 1 ? true : false;
			if (!$newid) {
				$newid = db('user')->insert($params, false, true, "id");
				$tiptext = "注册成功";
			} else {
				$newid = db('user')->where(['openid' => $openid])->find();
				$newid = $newid['id'];
				$tiptext = "登陆成功";
			}
		} catch (Exception $ex1) {
			$json = $this->message(0, "网络错误,请刷新后再填写!");
			return $this->returnjson($json, $attr['callback']);
		} catch (PDOException $ex) {
			$json = $this->message(0, "网络错误,请刷新后再填写!");
			return $this->returnjson($json, $attr['callback']);
		}
		if ($newid <= 0) {
			$json = $this->message(0, "网络错误,请刷新后再填写!");
			return $this->returnjson($json, $attr['callback']);
		}
		$json = $this->message(1, $tiptext, ["user_id" => $newid]);
		return $this->returnjson($json, $attr['callback']);
	}
	
	
	
		
	//更新头像和昵称
	public function api_setUserInfo() {
		$attr = $this->getattr();
		
		$user_id = trim($attr['user_id']);
		$nickname = trim($attr['nickname']);
		$avatarimg = trim($attr['avatarimg']);
		$params = [
			"nickname" => $nickname,
			"avatarimg" => $avatarimg,
		];
		$newid = 0;
		try {
			$newid = db('user')->where(['id' => $user_id])->count() >= 1 ? true : false;
		//	echo($newid);
			if (!$newid) {
			//	$newid = db('user')->update(['nickname' => 'thinkphp','avatarimg'=>1])->where('id',$user_id);
			//	echo($newid);
				$tiptext = "更新失败";
			} else {
			//	$tiptext = "更新失败";
			$newid = db('user')->where(['id'=>$user_id])->update($params);
				$tiptext = "更新成功";
			}
		} catch (Exception $ex1) {
			$json = $this->message(0, "网络错误,请刷新后再填写!");
			return $this->returnjson($json, $attr['callback']);
		} catch (PDOException $ex) {
			$json = $this->message(0, "网络错误,请刷新后再填写!");
			return $this->returnjson($json, $attr['callback']);
		}
		if ($newid <= 0) {
			$json = $this->message(0, "网络错误,请刷新后再填写!");
			return $this->returnjson($json, $attr['callback']);
		}
		$json = $this->message(1, $tiptext, ["user_id" => $newid]);
		return $this->returnjson($json, $attr['callback']);
	}
	

Guess you like

Origin blog.csdn.net/oZhongRan/article/details/127827906