欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

微信小程序获取用户信息及手机号(后端TP5.0)

程序员文章站 2023-11-03 13:28:16
本文实例为大家分享了微信小程序获取用户信息及手机号的具体代码,供大家参考,具体内容如下 wxml页面

本文实例为大家分享了微信小程序获取用户信息及手机号的具体代码,供大家参考,具体内容如下

wxml页面

<view wx:if="{{config.tipsshow1}}" class='dialog-container'>
 <view class='dialog-mask'></view>
 <view class='dialog-info'>
 <view class='dialog-title'>login prompt</view>
 <view class='dialog-content'>to provide better service, click "allow" in the prompt box later!</view>
 <view class='dialog-footer'>
  <button class='dialog-btn' open-type="getuserinfo" bindgetuserinfo="getuserinfo">i see.</button>
 </view>
 </view>
</view>

<view wx:if="{{config.tipsshow2}}" class='dialog-container'>
 <view class='dialog-mask'></view>
 <view class='dialog-info'>
 <view class='dialog-title'>login prompt</view>
 <view class='dialog-content'>to provide better service, click "allow" in the prompt box later!</view>
 <view class='dialog-footer'>
  <button class='dialog-btn' open-type="getphonenumber" bindgetphonenumber="getphonenumber">to authorize.</button>
 </view>
 </view>
</view>

wxss页面

.dialog-mask{
 position: fixed;
 z-index: 1000;
 top: 0;
 right: 0;
 left: 0;
 bottom: 0;
 background: rgba(0, 0, 0, 0.3);
}
.dialog-info{
 position: fixed;
 z-index: 5000;
 width: 80%;
 max-width: 600rpx;
 top: 50%;
 left: 50%;
 -webkit-transform: translate(-50%, -50%);
 transform: translate(-50%, -50%);
 background-color: #ffffff;
 text-align: center;
 border-radius: 3px;
 overflow: hidden;
}
.dialog-title{
 font-size: 36rpx;
 padding: 30rpx 30rpx 10rpx;
}
.dialog-content{
 padding: 10rpx 30rpx 20rpx;
 min-height: 80rpx;
 font-size: 32rpx;
 line-height: 1.3;
 word-wrap: break-word;
 word-break: break-all;
 color: #999999;
}
.dialog-footer{
 display: flex;
 align-items: center;
 position: relative;
 line-height: 90rpx;
 font-size: 34rpx;
}
.dialog-btn{
 display: block;
 -webkit-flex: 1;
 flex: 1;
 position: relative;
 color: #3cc51f;
}

js页面

data: {
 username: '',
 pwd: '',
 getuserinfofail: '',
 userinfo: [],
 hasuserinfo: '',
 phone: '',
 config: {
  tipsshow1: true,
  tipsshow2: false
 }
 },


 /**
 * 生命周期函数--监听页面加载
 */
 onload: function(options) {
 var that = this;
 //用户是否授权过手机号
 wx.getstorage({
  key: 'phone',
  success: function (res) {
  that.setdata({
   config: {
   tipsshow1: false,
   tipsshow2: false
   },
  })
  }
 })

 //是否授权过用户信息
 wx.getsetting({
  success: function(res) {
  if (res.authsetting['scope.userinfo']) {
   // 已经授权,可以直接调用 getuserinfo 获取头像昵称
   wx.getuserinfo({
   success: function(res) {
    that.setdata({
    userinfo: res.userinfo,
    config: {
     tipsshow1: false,
    },
    })
   }
   })
  }
  }
 })

 },

 getphonenumber: function(e) {
 if (e.detail.errmsg == "getphonenumber:fail user deny") return;
 //用户允许授权
 wx.showloading()
 var self = this
 //1. 调用登录接口获取临时登录code
 wx.login({
  success: res => {
  console.log(res, 555)
  if (res.code) {
   //2. 访问登录凭证校验接口获取session_key、openid
   wx.request({
   url: "xxxxxxx/index/author/login",
   data: {
    'js_code': res.code,
   },
   method: 'get', // options, get, head, post, put, delete, trace, connect
   header: {
    'content-type': 'application/json'
   }, // 设置请求的 header
   success: function(data) {
    console.log(data, data)
    if (data.statuscode == 200) {
    //3. 解密
    wx.request({
     url: 'xxxxxx/index/author/number',
     data: {
     'appid': data.data.appid,
     'sessionkey': data.data.session_key,
     'encrypteddata': e.detail.encrypteddata,
     'iv': e.detail.iv,
     },
     method: 'get', // options, get, head, post, put, delete, trace, connect
     header: {
     'content-type': 'application/json'
     }, // 设置请求的 header
     success: function(data2) {
     wx.hideloading()
     console.log(data2.data.phonenumber)
     if (data2.statuscode == 200 && data2.data.phonenumber) {
      self.setdata({
      phone: data2.data.phonenumber,
      config: {
       tipsshow1: false,
       tipsshow2: false,
      },
      })
      wx.setstoragesync('phone', data2.data.phonenumber);
      if (self.data.userinfo != '') {
      wx.request({
       url: 'xxxx/index/author/regist',
       data: {
       username: self.data.userinfo.nickname,
       sex: self.data.userinfo.gender,
       phone: self.data.phone,
       pwd: 123456,
       avatarimg: self.data.userinfo.avatarurl
       },
       success: function(data) {
        console.log(data.data,56565)
        if (data.data != null) {
        wx.showtoast({
         title: '登录中...',
         icon: 'loading',
         duration: 2000
        })
        wx.navigateto({
         url: '../managementlist/managementlist'//管理页面
        })
        }
       }
      });
      }
      console.log(self.data, 526336)
     }
     },
     fail: function(err) {
     console.log(err);
     }
    })
    }
   },
   fail: function(err) {
    console.log(err);
   }
   })
  }
  }
 })
 },

 getuserinfo: function(e) {
 var that = this;
 console.log(e.detail.userinfo, "getuserinfo")
 if (e.detail.userinfo) {
  that.setdata({
  userinfo: e.detail.userinfo,
  config: {
   tipsshow1: false,
   tipsshow2: true,
  },
  })
  console.log(that.data.userinfo);
 } else {
  console.log("获取信息失败")
 }
 },

php后端

<?php

namespace app\index\controller;

use think\controller;
use app\admin\model\userrecharge;
use think\db;


class author extends controller
{

 /**
  * 发送http请求方法
  * @param string $url 请求url
  * @param array $params 请求参数
  * @param string $method 请求方法get/post
  * @return array $data 响应数据
  */
 function httpcurl($url, $params, $method = 'post', $header = array(), $multi = false){
  date_default_timezone_set('prc');
  $opts = array(
   curlopt_timeout  => 30,
   curlopt_returntransfer => 1,
   curlopt_ssl_verifypeer => false,
   curlopt_ssl_verifyhost => false,
   curlopt_httpheader  => $header,
   curlopt_cookiesession => true,
   curlopt_followlocation => 1,
   curlopt_cookie   =>session_name().'='.session_id(),
  );
  /* 根据请求类型设置特定参数 */
  switch(strtoupper($method)){
   case 'get':
    // $opts[curlopt_url] = $url . '?' . http_build_query($params);
    // 链接后拼接参数 & 非?
    $opts[curlopt_url] = $url . '?' . http_build_query($params);
    break;
   case 'post':
    //判断是否传输文件
    $params = $multi ? $params : http_build_query($params);
    $opts[curlopt_url] = $url;
    $opts[curlopt_post] = 1;
    $opts[curlopt_postfields] = $params;
    break;
   default:
    throw new exception('不支持的请求方式!');
  }
  /* 初始化并执行curl请求 */
  $ch = curl_init();
  curl_setopt_array($ch, $opts);
  $data = curl_exec($ch);
  $error = curl_error($ch);
  curl_close($ch);
  if($error) throw new exception('请求发生错误:' . $error);
  return $data;
 }
 /**
  * 微信信息解密
  * @param string $appid 小程序id
  * @param string $sessionkey 小程序密钥
  * @param string $encrypteddata 在小程序中获取的encrypteddata
  * @param string $iv 在小程序中获取的iv
  * @return array 解密后的数组
  */
 function decryptdata( $appid , $sessionkey, $encrypteddata, $iv ){
  $ok = 0;
  $illegalaeskey = -41001;
  $illegaliv = -41002;
  $illegalbuffer = -41003;
  $decodebase64error = -41004;
  if (strlen($sessionkey) != 24) {
   return $illegalaeskey;
  }
  $aeskey=base64_decode($sessionkey);

  if (strlen($iv) != 24) {
   return $illegaliv;
  }
  $aesiv=base64_decode($iv);

  $aescipher=base64_decode($encrypteddata);

  $result=openssl_decrypt( $aescipher, "aes-128-cbc", $aeskey, 1, $aesiv);
  $dataobj=json_decode( $result );
  if( $dataobj == null )
  {
   return $illegalbuffer;
  }
  if( $dataobj->watermark->appid != $appid )
  {
   return $decodebase64error;
  }
  $data = json_decode($result,true);
  return $result;
 }

 /**
  * 请求过程中因为编码原因+号变成了空格
  * 需要用下面的方法转换回来
  */
 function define_str_replace($data)
 {
  return str_replace(' ','+',$data);
 }


 //获取手机号
 public function number($appid , $sessionkey, $encrypteddata, $iv)
 {
  include_once (root_path."./public/author/wxbizdatacrypt.php"); //引入 wxbizdatacrypt.php 文件
  $appid = $appid;
  $sessionkey = $sessionkey;
  $encrypteddata= $encrypteddata;
  $iv = $iv;
  $data = '';

  $pc = new \wxbizdatacrypt($appid, $sessionkey); //注意使用\进行转义
  $errcode = $pc->decryptdata($encrypteddata, $iv, $data );
  if ($errcode == 0) {
   print($data . "\n");
  } else {
   print($errcode . "\n");
  }
 }

 //微信登录
 public function login(){
  $get = input('get.');
  $param['appid'] = 'xxxxxxxxxx'; //小程序id
  $param['secret'] = 'xxxxxxxxxx'; //小程序密钥
  $param['js_code'] = $this->define_str_replace($get['js_code']);
  $param['grant_type'] = 'authorization_code';
  $http_key = $this->httpcurl('https://api.weixin.qq.com/sns/jscode2session', $param, 'get');
  $session_key = json_decode($http_key,true);//获取openid和session_key
  //print_r(http_build_query($param));
  if (!empty($session_key['session_key'])) {
   $data['appid'] = $param['appid'];
   $data['session_key'] = $session_key['session_key'];
   return json($data);
  }else{
   echo '获取session_key失败!';
  }
 }

 //用户注册
 public function regist($username = "",$sex = "", $phone = "",$password = "",$avatarimg = "")
 {
  if ($phone){
   //判断该用户是否已经注册
   $userdata = db::name('user')->where('phone',$phone)->find();
   if ($userdata){
    return json_encode(2);
   }

   //整合数组
   $salt = '1122';
   $password = md5(md5($password) . $salt);
   $data = [
    'name' => $username,
    'sex' => $sex,
    'phone' => $phone,
    'password' => $password,
    'avatarimg' => $avatarimg,
    'logtime' => date("y-m-d h:i:s"),
    'addtime' => date("y-m-d h:i:s")
   ];
   //注册新用户
   $userid = db('user')->insertgetid($data);
   if ($userid){
    return json_decode(1);
   }else{
    return json_encode(0);
   }
  }
 }
}

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。