Example method of obtaining user information in WeChat applet
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!

JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

SublimeText3 Linux new version
SublimeText3 Linux latest version

Dreamweaver Mac version
Visual web development tools

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

SublimeText3 Mac version
God-level code editing software (SublimeText3)