Home >Web Front-end >JS Tutorial >Example method of obtaining user information in WeChat applet

Example method of obtaining user information in WeChat applet

小云云
小云云Original
2018-05-12 17:04:246346browse

This article mainly introduces in detail how the WeChat applet obtains user information. It has certain reference value. Interested friends can refer to it. I hope it can help everyone.

For example, in a browser we can get the DOM object of the page through document.getElementById. However, the DOM object cannot be obtained in the WeChat applet. document.getElementById() directly reports an error getElementById not function. I am also drunk. Without support for this, many interesting features cannot be implemented.
Getting back to business, let me talk about my thoughts on obtaining user information.

There are two options for obtaining user information.
1. A json object that does not contain the sensitive information openId (including basic information such as nickname, avatarUrl, etc.)
2. Contains the basic information of the sensitive information openId.

The first acquisition scheme

1. First call the wx.login() interface to allow user authorization verification, which is what we observe with the naked eye. Whether to authorize this information to xxxxx.
2. After the user is successfully authorized, call the wx.getUserInfo() interface to obtain user information.

The complete code is as follows

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

The second type is more complicated and requires interaction with the background to obtain userInfo, but the data obtained by this solution is complete (including openId).

1. Call the wx.login() interface to authorize and include code in the parameters of the success function.
2. Call the wx.getUserInfo() interface success function, which contains encryptedData and iv
3. Pass the above parameters to the background for analysis and generate userInfo

The code is as follows
js

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

Backend analysis

/**
 * 获取粉丝信息
 * 其中的参数就是前端传递过来的
 */
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);

 //载入用户服务
 //$userService = load_service("User");

 //$userService->checkUser($this->projectId,$userInfo);

 echo $userInfo; //微信响应的就是一个json数据
}

getUserInfo function where wxBizDataCrypt.php is the material package officially provided by WeChat

curlHttp function is a custom function. For the source code of this function, check out my article Article curlHttp

//获取粉丝信息
function getUserInfo($appid,$sessionKey,$encryptedData,$iv){
 require_once ROOTPATH . "/extends/wxUser/wxBizDataCrypt.php";
 $data = array();
 $pc = new WXBizDataCrypt($appid, $sessionKey);
 $errCode = $pc->decryptData($encryptedData, $iv, $data );

 if ($errCode == 0) {
 return $data;
 } else {
 return false;
 }
}

Write your own gadget request.js

var app = getApp();

//远程请求
var __httpsRequest = {

 //http 请求
 https_request : function(obj){
 wx.request(obj);
 },

 //文件上传
 upload_request : function(dataSource){
 wx.uploadFile(dataSource);
 }
};

module.exports = {
 //执行异步请求get
 httpsRequest:function(obj){
 var jsonUrl = {};
 jsonUrl.url = obj.url;
 if(obj.header)jsonUrl.header=obj.header;
 if(obj.type)
  jsonUrl.method = obj.type;
 else
  jsonUrl.method="GET";
 if(obj.data)jsonUrl.data = obj.data;
 obj.dataType?(jsonUrl.dataType=obj.dataType):(jsonUrl.dataType="json");

 jsonUrl.success = obj.success;

 jsonUrl.data.projectId = app.globalData.projectId;

 __httpsRequest.https_request(jsonUrl);
 },

 //get 请求
 httpsGetRequest:function(req_url,req_obj,res_func)
 {
 var jsonUrl = {
  url:app.globalData.host + req_url,
  header:{"Content-Type":"application/json"},
  dataType:"json",
  method:"get",
  success:function(res)
  {
  typeof res_func == "function" && res_func(res.data);
  }
 }

 if(req_obj)
 {
  jsonUrl.data = req_obj;
 }

 jsonUrl.data.projectId = app.globalData.projectId;

  __httpRequest.https_request(jsonUrl);
 },

 //post 请求
 httpsPostRequest:function(req_url,req_obj,res_func)
 {
 var jsonUrl = {
  url:app.globalData.host + req_url,
  header:{"Content-Type":"application/x-www-form-urlencoded"},
  dataType:"json",
  method:"post",
  success:function(res)
  {
  typeof res_func == "function" && res_func(res.data);
  }
 }

 if(req_obj)
 {
  jsonUrl.data = req_obj;
 }

 jsonUrl.data.projectId = app.globalData.projectId;

  __httpsRequest.https_request(jsonUrl);
 },

 //文件上传
 httpsUpload:function(uid,fileDataSource,res_func)
 {
 dataSource = {
  url:app.globalData.host + req_url,
  header:{
  "Content-Type":"multipart/form-data"
  },
  dataType:"json",
  formData : {
  "uid" : uid
  },
  filePath : fileDataSource,
  name : "fileObj",
  success:function(res){
  typeof res_func == "function" && res_func(res);
  }
 }

 __httpsRequest.upload_request(dataSource);
 }
};

app.globalData.host is the domain name address such as https://xxxxx.com;

Related recommendations:

How to implement the WeChat applet to obtain user information

Thinkphp5 A case study on how to implement the WeChat applet to obtain user information interface

10 recommended articles about obtaining user information

The above is the detailed content of Example method of obtaining user information in WeChat applet. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn