小程序模板网

微信小程序 - 获取用户信息

发布时间:2018-02-10 10:56 所属栏目:小程序开发教程

最近在研究微信小程序怎么玩的。接触后发现好多的坑。 
比如在浏览器中我们可以通过document.getElementById 获取到页面的DOM对象。而在微信小程序中是获取不到DOM对象的。document.getElementById() 直接报错 getElementById not function 我也是醉了。不支持这个好多有趣的功能不能实现了。 
言归正传,我谈下获取用户信息的感想。

有两种获取用户信息的方案。 
1、不包含敏感信息openId 的json对象(包含:nickname、avatarUrl等基本信息) 
2、包含敏感信息openId的基本信息。

第一种获取方案 
1、首先调用wx.login()接口 让用户授权验证,也就是我们肉眼观察到的,你是否对xxxxx授权这种信息。 
2、用户成功授权后,调用wx.getUserInfo() 接口获取用户信息。 
完整代码如下

 

  1. wx.login({
    success:function(){
    wx.getUserInfo({
    success:function(res){
    var simpleUser = res.userInfo;
    console.log(simpleUser.nickName);
    }
    });
    }
    });

第二种比较复杂了,需要与后台进行交互才能获得userInfo,但是这种方案获得的数据是完整的(包含openId)。  1、调用wx.login()接口 授权 在success 成功函数的参数中包含code。  2、调用wx.getUserInfo()接口success 函数中包含encryptedData、iv  3、将上述参数传给后台解析,生成userInfo  代码如下  js

 

  1. var request = require("../../utils/request.js");
    
    wx.login({
    success:function(res_login){
    if(res_login.code)
    {
    wx.getUserInfo({
    withCredentials:true,
    success:function(res_user){
    var requestUrl = "/getUserApi/xxx.php";
    var jsonData = {
    code:res_login.code,
    encryptedData:res_user.encryptedData,
    iv:res_user.iv
    };
    request.httpsPostRequest(requestUrl,jsonData,function(res){
    console.log(res.openId);
    });
    }
    })
    }
    }
    })

后台解析

 

  1. /**
    * 获取粉丝信息
    * 其中的参数就是前端传递过来的
    */
    public function wxUserInfo($code,$encryptedData,$iv)
    {
    $apiUrl = "https://api.weixin.qq.com/sns/jscode2session?appid={$this->wxConfig['appid']}&secret={$this->wxConfig['appsecret']}&js_code={$code}&grant_type=authorization_code";
    
    $apiData = json_decode(curlHttp($apiUrl,true),true);
    
    if(!isset($apiData['session_key']))
    {
    echoJson(array(
    "code" => 102,
    "msg" => "curl error"
    ),true);
    }
    
    $userInfo = getUserInfo($this->wxConfig['appid'],$apiData['session_key'],$encryptedData,$iv);
    
    if(!$userInfo)
    {
    echoJson(array(
    "code" => 105,
    "msg" => "userInfo not"
    ));
    }
    
    //$userInfo = json_decode($userInfo,true);
    
    //载入用户服务
  2. <code o="" cl="" ptm="" pbm"="" style="word-wrap: break-word; margin: 0px; padding: 0px; font-family: Monaco, Menlo, Consolas, &quot;Courier New&quot;, monospace;">


易优小程序(企业版)+灵活api+前后代码开源 码云仓库:starfork
本文地址:https://www.eyoucms.com/wxmini/doc/course/21914.html 复制链接 如需定制请联系易优客服咨询:800182392 点击咨询
QQ在线咨询