经验首页 前端设计 程序设计 Java相关 移动开发 数据库/运维 软件/图像 大数据/云计算 其他经验
当前位置:技术经验 » 移动开发 » 微信小程序 » 查看文章
微信小程序获取用户信息及手机号(后端TP5.0)
来源:jb51  时间:2019/9/12 10:52:30  对本文有异议

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

wxml页面

  1. <view wx:if="{{config.tipsshow1}}" class='dialog-container'>
  2. <view class='dialog-mask'></view>
  3. <view class='dialog-info'>
  4. <view class='dialog-title'>login prompt</view>
  5. <view class='dialog-content'>To provide better service, click "allow" in the prompt box later!</view>
  6. <view class='dialog-footer'>
  7. <button class='dialog-btn' open-type="getUserInfo" bindgetuserinfo="getUserInfo">I see.</button>
  8. </view>
  9. </view>
  10. </view>
  11.  
  12. <view wx:if="{{config.tipsshow2}}" class='dialog-container'>
  13. <view class='dialog-mask'></view>
  14. <view class='dialog-info'>
  15. <view class='dialog-title'>login prompt</view>
  16. <view class='dialog-content'>To provide better service, click "allow" in the prompt box later!</view>
  17. <view class='dialog-footer'>
  18. <button class='dialog-btn' open-type="getPhoneNumber" bindgetphonenumber="getPhoneNumber">To authorize.</button>
  19. </view>
  20. </view>
  21. </view>

wxss页面

  1. .dialog-mask{
  2. position: fixed;
  3. z-index: 1000;
  4. top: 0;
  5. right: 0;
  6. left: 0;
  7. bottom: 0;
  8. background: rgba(0, 0, 0, 0.3);
  9. }
  10. .dialog-info{
  11. position: fixed;
  12. z-index: 5000;
  13. width: 80%;
  14. max-width: 600rpx;
  15. top: 50%;
  16. left: 50%;
  17. -webkit-transform: translate(-50%, -50%);
  18. transform: translate(-50%, -50%);
  19. background-color: #FFFFFF;
  20. text-align: center;
  21. border-radius: 3px;
  22. overflow: hidden;
  23. }
  24. .dialog-title{
  25. font-size: 36rpx;
  26. padding: 30rpx 30rpx 10rpx;
  27. }
  28. .dialog-content{
  29. padding: 10rpx 30rpx 20rpx;
  30. min-height: 80rpx;
  31. font-size: 32rpx;
  32. line-height: 1.3;
  33. word-wrap: break-word;
  34. word-break: break-all;
  35. color: #999999;
  36. }
  37. .dialog-footer{
  38. display: flex;
  39. align-items: center;
  40. position: relative;
  41. line-height: 90rpx;
  42. font-size: 34rpx;
  43. }
  44. .dialog-btn{
  45. display: block;
  46. -webkit-flex: 1;
  47. flex: 1;
  48. position: relative;
  49. color: #3CC51F;
  50. }

js页面

  1. data: {
  2. userName: '',
  3. pwd: '',
  4. getUserInfoFail: '',
  5. userInfo: [],
  6. hasUserInfo: '',
  7. phone: '',
  8. config: {
  9. tipsshow1: true,
  10. tipsshow2: false
  11. }
  12. },
  13.  
  14.  
  15. /**
  16. * 生命周期函数--监听页面加载
  17. */
  18. onLoad: function(options) {
  19. var that = this;
  20. //用户是否授权过手机号
  21. wx.getStorage({
  22. key: 'phone',
  23. success: function (res) {
  24. that.setData({
  25. config: {
  26. tipsshow1: false,
  27. tipsshow2: false
  28. },
  29. })
  30. }
  31. })
  32.  
  33. //是否授权过用户信息
  34. wx.getSetting({
  35. success: function(res) {
  36. if (res.authSetting['scope.userInfo']) {
  37. // 已经授权,可以直接调用 getUserInfo 获取头像昵称
  38. wx.getUserInfo({
  39. success: function(res) {
  40. that.setData({
  41. userInfo: res.userInfo,
  42. config: {
  43. tipsshow1: false,
  44. },
  45. })
  46. }
  47. })
  48. }
  49. }
  50. })
  51.  
  52. },
  53.  
  54. getPhoneNumber: function(e) {
  55. if (e.detail.errMsg == "getPhoneNumber:fail user deny") return;
  56. //用户允许授权
  57. wx.showLoading()
  58. var self = this
  59. //1. 调用登录接口获取临时登录code
  60. wx.login({
  61. success: res => {
  62. console.log(res, 555)
  63. if (res.code) {
  64. //2. 访问登录凭证校验接口获取session_key、openid
  65. wx.request({
  66. url: "xxxxxxx/index/author/login",
  67. data: {
  68. 'js_code': res.code,
  69. },
  70. method: 'GET', // OPTIONS, GET, HEAD, POST, PUT, DELETE, TRACE, CONNECT
  71. header: {
  72. 'content-type': 'application/json'
  73. }, // 设置请求的 header
  74. success: function(data) {
  75. console.log(data, data)
  76. if (data.statusCode == 200) {
  77. //3. 解密
  78. wx.request({
  79. url: 'xxxxxx/index/author/number',
  80. data: {
  81. 'appid': data.data.appid,
  82. 'sessionKey': data.data.session_key,
  83. 'encryptedData': e.detail.encryptedData,
  84. 'iv': e.detail.iv,
  85. },
  86. method: 'GET', // OPTIONS, GET, HEAD, POST, PUT, DELETE, TRACE, CONNECT
  87. header: {
  88. 'content-type': 'application/json'
  89. }, // 设置请求的 header
  90. success: function(data2) {
  91. wx.hideLoading()
  92. console.log(data2.data.phoneNumber)
  93. if (data2.statusCode == 200 && data2.data.phoneNumber) {
  94. self.setData({
  95. phone: data2.data.phoneNumber,
  96. config: {
  97. tipsshow1: false,
  98. tipsshow2: false,
  99. },
  100. })
  101. wx.setStorageSync('phone', data2.data.phoneNumber);
  102. if (self.data.userInfo != '') {
  103. wx.request({
  104. url: 'xxxx/index/author/regist',
  105. data: {
  106. username: self.data.userInfo.nickName,
  107. sex: self.data.userInfo.gender,
  108. phone: self.data.phone,
  109. pwd: 123456,
  110. avatarimg: self.data.userInfo.avatarUrl
  111. },
  112. success: function(data) {
  113. console.log(data.data,56565)
  114. if (data.data != null) {
  115. wx.showToast({
  116. title: '登录中...',
  117. icon: 'loading',
  118. duration: 2000
  119. })
  120. wx.navigateTo({
  121. url: '../managementList/managementList'//管理页面
  122. })
  123. }
  124. }
  125. });
  126. }
  127. console.log(self.data, 526336)
  128. }
  129. },
  130. fail: function(err) {
  131. console.log(err);
  132. }
  133. })
  134. }
  135. },
  136. fail: function(err) {
  137. console.log(err);
  138. }
  139. })
  140. }
  141. }
  142. })
  143. },
  144.  
  145. getUserInfo: function(e) {
  146. var that = this;
  147. console.log(e.detail.userInfo, "getuserinfo")
  148. if (e.detail.userInfo) {
  149. that.setData({
  150. userInfo: e.detail.userInfo,
  151. config: {
  152. tipsshow1: false,
  153. tipsshow2: true,
  154. },
  155. })
  156. console.log(that.data.userInfo);
  157. } else {
  158. console.log("获取信息失败")
  159. }
  160. },

PHP后端

  1. <?php
  2.  
  3. namespace app\index\controller;
  4.  
  5. use think\Controller;
  6. use app\admin\model\UserRecharge;
  7. use think\Db;
  8.  
  9.  
  10. class Author extends Controller
  11. {
  12.  
  13. /**
  14. * 发送HTTP请求方法
  15. * @param string $url 请求URL
  16. * @param array $params 请求参数
  17. * @param string $method 请求方法GET/POST
  18. * @return array $data 响应数据
  19. */
  20. function httpCurl($url, $params, $method = 'POST', $header = array(), $multi = false){
  21. date_default_timezone_set('PRC');
  22. $opts = array(
  23. CURLOPT_TIMEOUT => 30,
  24. CURLOPT_RETURNTRANSFER => 1,
  25. CURLOPT_SSL_VERIFYPEER => false,
  26. CURLOPT_SSL_VERIFYHOST => false,
  27. CURLOPT_HTTPHEADER => $header,
  28. CURLOPT_COOKIESESSION => true,
  29. CURLOPT_FOLLOWLOCATION => 1,
  30. CURLOPT_COOKIE =>session_name().'='.session_id(),
  31. );
  32. /* 根据请求类型设置特定参数 */
  33. switch(strtoupper($method)){
  34. case 'GET':
  35. // $opts[CURLOPT_URL] = $url . '?' . http_build_query($params);
  36. // 链接后拼接参数 & 非?
  37. $opts[CURLOPT_URL] = $url . '?' . http_build_query($params);
  38. break;
  39. case 'POST':
  40. //判断是否传输文件
  41. $params = $multi ? $params : http_build_query($params);
  42. $opts[CURLOPT_URL] = $url;
  43. $opts[CURLOPT_POST] = 1;
  44. $opts[CURLOPT_POSTFIELDS] = $params;
  45. break;
  46. default:
  47. throw new Exception('不支持的请求方式!');
  48. }
  49. /* 初始化并执行curl请求 */
  50. $ch = curl_init();
  51. curl_setopt_array($ch, $opts);
  52. $data = curl_exec($ch);
  53. $error = curl_error($ch);
  54. curl_close($ch);
  55. if($error) throw new Exception('请求发生错误:' . $error);
  56. return $data;
  57. }
  58. /**
  59. * 微信信息解密
  60. * @param string $appid 小程序id
  61. * @param string $sessionKey 小程序密钥
  62. * @param string $encryptedData 在小程序中获取的encryptedData
  63. * @param string $iv 在小程序中获取的iv
  64. * @return array 解密后的数组
  65. */
  66. function decryptData( $appid , $sessionKey, $encryptedData, $iv ){
  67. $OK = 0;
  68. $IllegalAesKey = -41001;
  69. $IllegalIv = -41002;
  70. $IllegalBuffer = -41003;
  71. $DecodeBase64Error = -41004;
  72. if (strlen($sessionKey) != 24) {
  73. return $IllegalAesKey;
  74. }
  75. $aesKey=base64_decode($sessionKey);
  76.  
  77. if (strlen($iv) != 24) {
  78. return $IllegalIv;
  79. }
  80. $aesIV=base64_decode($iv);
  81.  
  82. $aesCipher=base64_decode($encryptedData);
  83.  
  84. $result=openssl_decrypt( $aesCipher, "AES-128-CBC", $aesKey, 1, $aesIV);
  85. $dataObj=json_decode( $result );
  86. if( $dataObj == NULL )
  87. {
  88. return $IllegalBuffer;
  89. }
  90. if( $dataObj->watermark->appid != $appid )
  91. {
  92. return $DecodeBase64Error;
  93. }
  94. $data = json_decode($result,true);
  95. return $result;
  96. }
  97.  
  98. /**
  99. * 请求过程中因为编码原因+号变成了空格
  100. * 需要用下面的方法转换回来
  101. */
  102. function define_str_replace($data)
  103. {
  104. return str_replace(' ','+',$data);
  105. }
  106.  
  107.  
  108. //获取手机号
  109. public function number($appid , $sessionKey, $encryptedData, $iv)
  110. {
  111. include_once (ROOT_PATH."./public/author/wxBizDataCrypt.php"); //引入 wxBizDataCrypt.php 文件
  112. $appid = $appid;
  113. $sessionKey = $sessionKey;
  114. $encryptedData= $encryptedData;
  115. $iv = $iv;
  116. $data = '';
  117.  
  118. $pc = new \WXBizDataCrypt($appid, $sessionKey); //注意使用\进行转义
  119. $errCode = $pc->decryptData($encryptedData, $iv, $data );
  120. if ($errCode == 0) {
  121. print($data . "\n");
  122. } else {
  123. print($errCode . "\n");
  124. }
  125. }
  126.  
  127. //微信登录
  128. public function login(){
  129. $get = input('get.');
  130. $param['appid'] = 'xxxxxxxxxx'; //小程序id
  131. $param['secret'] = 'xxxxxxxxxx'; //小程序密钥
  132. $param['js_code'] = $this->define_str_replace($get['js_code']);
  133. $param['grant_type'] = 'authorization_code';
  134. $http_key = $this->httpCurl('https://api.weixin.qq.com/sns/jscode2session', $param, 'GET');
  135. $session_key = json_decode($http_key,true);//获取openid和session_key
  136. //print_r(http_build_query($param));
  137. if (!empty($session_key['session_key'])) {
  138. $data['appid'] = $param['appid'];
  139. $data['session_key'] = $session_key['session_key'];
  140. return json($data);
  141. }else{
  142. echo '获取session_key失败!';
  143. }
  144. }
  145.  
  146. //用户注册
  147. public function regist($username = "",$sex = "", $phone = "",$password = "",$avatarimg = "")
  148. {
  149. if ($phone){
  150. //判断该用户是否已经注册
  151. $userdata = Db::name('user')->where('phone',$phone)->find();
  152. if ($userdata){
  153. return json_encode(2);
  154. }
  155.  
  156. //整合数组
  157. $salt = '1122';
  158. $password = Md5(Md5($password) . $salt);
  159. $data = [
  160. 'name' => $username,
  161. 'sex' => $sex,
  162. 'phone' => $phone,
  163. 'password' => $password,
  164. 'avatarimg' => $avatarimg,
  165. 'logtime' => date("Y-m-d H:i:s"),
  166. 'addTime' => date("Y-m-d H:i:s")
  167. ];
  168. //注册新用户
  169. $userid = db('user')->insertGetId($data);
  170. if ($userid){
  171. return json_decode(1);
  172. }else{
  173. return json_encode(0);
  174. }
  175. }
  176. }
  177. }

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

 友情链接:直通硅谷  点职佳  北美留学生论坛

本站QQ群:前端 618073944 | Java 606181507 | Python 626812652 | C/C++ 612253063 | 微信 634508462 | 苹果 692586424 | C#/.net 182808419 | PHP 305140648 | 运维 608723728

W3xue 的所有内容仅供测试,对任何法律问题及风险不承担任何责任。通过使用本站内容随之而来的风险与本站无关。
关于我们  |  意见建议  |  捐助我们  |  报错有奖  |  广告合作、友情链接(目前9元/月)请联系QQ:27243702 沸活量
皖ICP备17017327号-2 皖公网安备34020702000426号