微信小程序获取昵称和头像

前提:做一个文档方便二次复制使用!

注意:真机调试才能正常测试调用头像+昵称事件!

微信端wxml


    <view class="weixin_login">
      <form catchsubmit="formSubmit" catchreset="formReset">
          <view class="weixin_login_img" wx:if="{
   
   {avatarUrl != null}}">
                <image wx:if="{
   
   {avatarUrl != null}}" src="{
   
   {avatarUrl}}" />
          </view>

          <view class="weixin_login_img"  wx:elif="{
   
   {avatarUrl == null}}">
            <button class="avatar-wrapper" open-type="chooseAvatar" bind:chooseavatar="onChooseAvatar">
                <image src="../icon/plus.png" />
            </button> 
          </view>

          <view class="weixin_login_box">
                <view class="weixin_login_nickName">
                    <view>微信昵称</view>
                    <!-- <view class="weixin_login_button"  bindtap="getNickname">授权头像和昵称</view> -->
                </view>
                <view class="weixin_login_input">
                  <input class="weui-input" name="nikename"  type="nickname" maxlength="20" value="{
   
   {nickname}}"  name="nickname" placeholder="请输入" />
                </view>
          </view>
          <view class="weixin_login_box">
                <view class="weixin_login_nickName">
                    <view>手机号码</view>
                    <view class="weixin_login_button" >
                      <button open-type="getPhoneNumber" bindgetphonenumber="getPhoneNumber">点击授权手机</button>
                    </view>
                </view>
                <view class="weixin_login_input">
                  <input class="weui-input" name="phonenumber" maxlength="11" value="{
   
   {phonenumber}}" placeholder="请输入" />
                </view>
          </view>

          <view class="weixin_login_box">
                <view class="weixin_login_input none">
                  <button class="submit" type="primary" formType="submit"  >提交注册</button>
                </view>
          </view>        
        </form>
    </view>

微信端css

.weixin_login_img{
    width:100px;
    height:100px;
    border:3px solid #ddd;
    margin:0px auto;
    border-radius:50%;
    overflow:hidden;
    text-align: center;
}
.weixin_login_img image{
    width:100px;
    height:100px;
}

.weixin_login_img button{
  display: inline;
  background:#ffffff;
}
.weixin_login_img button image{
  width:100px;
  height:100px;
  margin-left:-22px;
}
.weixin_login_box{
  width:95%;
  margin:20px auto;
}
.weixin_login_nickName{
  display: flex;
  justify-content: space-between;
  padding:10px;
  box-sizing: border-box;
}
.weixin_login_input{
  width:100%;
  font-size:32rpx;
  line-height:40px;
  border:1px solid #ddd;
  margin-top:10px;
  padding:10px;
  box-sizing: border-box;
  border-radius:5px;
}
.weixin_login_button{
  color:burlywood;
  font-size:14px;
}
.weixin_login_button button{
    display: inline;
    color:burlywood;
    font-weight:500;
    background:none;
    text-align: right;
    font-size:14px;
}
.submit{
  text-align: center;
  background-color:#6BB779;
  height:40px;
  border-radius:5px;
  color:#ffffff!important;
  font-weight: bold;
}
.none{
  border:none!important
}

微信端js

var app = getApp();
Page({
  data: {

    avatarUrl:null,
    nickname:'',
    phonenumber:'',
    pid:'',
    accessId:'',

  },
  onLoad(options) {
      this.setData({
        pid:options.id,
        accessId:app.globalData.accessId,
      })
  },
  getPhoneNumber (e) {
    var that =this;
    wx.request({
      url:app.globalData.url+'/api.openid/getPhonenumber',
      method:"post",
      data:{code:e.detail.code},
      success:res=>{
        //console.log(res.data.code);
        if(res.data.code == 0){
          this.setData({
            phonenumber :res.data.phonenumber
          })
        }else if(res.data.code == 1){
          wx.showToast({
            title: res.data.msg,
            icon: 'error',    //如果要纯文本,不要icon,将值设为'none'
            duration: 1500,
            mask:true,   
          })  
        }

      }
    })
  },
  onChooseAvatar(e) {
    wx.uploadFile({
      url:app.globalData.url+'/api.openid/updateAvatarUrl',
      filePath:e.detail.avatarUrl,
      name: 'file',
      formData: {'user': 'test' },
      success:(res) => {
        var date=JSON.parse(res.data);
       // console.log(date);
        this.setData({
          avatarUrl:date.img
        })
      }
    })  
  },
  formSubmit(e) {
   // console.log('form发生了submit事件,携带数据为:', e.detail.value)
    var that =this;
    wx.request({
      url:app.globalData.url+'/api.openid/insertUser',
      method:"post",
      data:e.detail.value,
      success:(res) => {
        if(res.data.code == 1){
          app.showBox('请检查表单完整','error');
        }else if(res.data.code == 0){
          app.globalData.access='1';
          wx.showToast({
            title: res.data.msg,
            icon: 'success',    //如果要纯文本,不要icon,将值设为'none'
            duration: 2000,
            mask:true,//是否显示透明蒙层,防止触摸穿透,默认:false 
            success:function(){
             
                setTimeout(function () { 
                
                  wx.switchTab({ url: '/pages/user/index' }) 
                
                }, 2500);
              

            }   
          })  

        }
      }
    })

  },
 

})

服务器端php 上传头像

    public function updateAvatarUrl(){
        
        
        $file   = request()->file('file');
        $img    = $this->move($file);
        $img    = substr($img['path'],2);
        return json([ "code"=>0,"img"=>$img]);
        
    }
    
   	//同步图片
	public function move($file){
	 
	    try {

	        $ext = strtolower($file->getOriginalExtension());
	        if (!in_array($ext, ['png', 'jpg', 'jpeg', 'pdf', 'webp'], true)) {
	            // 非法的文件类型
	            return '上传的图片的类型不正确,允许的类型有:' . implode(',', $this->allowed_ext);
	        }
	 
	        // 文件原名称(带扩展类型)
	        $originalName = $file->getOriginalName();
	        $newname = date('Ymd').rand(100,9999) . '.' . $ext;
	        $filePath = './upload/' . date('Ymd') . '/';
	        
	        $file->move($filePath, $newname);
	        return ['path' => $filePath . $newname];
	    } catch (\Exception $e) {
			
	        return $e->getMessage() . $e->getLine();
			
	    }
	} 
	

PHP 电话获取

	public function getPhonenumber(){
	    

	    $res                 = request()->param();
	    $url                 ='https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token='.$this->token;
	    $result              =$this->http_curl_post($url,json_encode($res));
	    if($result['errmsg'] == 'ok'){
	        
	         return json([ "code"=>0,"phonenumber"=>$result['phone_info']['phoneNumber']]);
	         
	    }else{
	        
	         return json([ "code"=>1,"msg"=>'获取失败']);
	        
	    }
	    
	}

猜你喜欢

转载自blog.csdn.net/munchmills/article/details/130717594
今日推荐