亚洲激情专区-91九色丨porny丨老师-久久久久久久女国产乱让韩-国产精品午夜小视频观看

溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

微信小程序獲取用戶信息及手機號(后端TP5.0)

發布時間:2020-10-18 02:18:15 來源:腳本之家 閱讀:520 作者:Emma'''''''' 欄目:web開發

本文實例為大家分享了微信小程序獲取用戶信息及手機號的具體代碼,供大家參考,具體內容如下

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);
   }
  }
 }
}

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持億速云。

向AI問一下細節

免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。

AI

嘉黎县| 略阳县| 辽阳市| 休宁县| 涟水县| 阿城市| 阿瓦提县| 绥德县| 儋州市| 永年县| 三台县| 肥西县| 甘泉县| 克东县| 沁阳市| 万源市| 巍山| 台南县| 微博| 乌拉特中旗| 宁蒗| 商洛市| 西畴县| 武胜县| 浦县| 枝江市| 仙游县| 柳河县| 时尚| 仙居县| 武安市| 观塘区| 广州市| 衢州市| 宁蒗| 都昌县| 香港| 呈贡县| 西乌珠穆沁旗| 青冈县| 江门市|